openxiangda-contracts 2.95.0 → 2.95.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- import{createHash as Pc}from"node:crypto";function $c(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ar(e,t){if(e===null)return"null";if(typeof e=="string"||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="number"){if(!Number.isFinite(e))throw new TypeError(`JSON number must be finite: ${t}`);return JSON.stringify(e)}if(Array.isArray(e))return`[${e.map((n,r)=>Ar(n,`${t}[${r}]`)).join(",")}]`;if($c(e))return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort((r,i)=>r===i?0:r<i?-1:1).map(r=>`${JSON.stringify(r)}:${Ar(e[r],`${t}.${r}`)}`).join(",")}}`;let o=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${o})`)}function re(e){return Ar(e,"$")}function ee(e){return Pc("sha256").update(re(e)).digest("hex")}var Sp=8,_s={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function qt(e){if(e.roleCodes===void 0)return[];let t=e.roleCodes;if(!["app_role","app_role_in_scope"].includes(e.provider||"")||e.roleCode!==void 0||e.candidateField!==void 0||!Array.isArray(t)||t.length<2||t.length>8||new Set(t).size!==t.length||t.some(o=>typeof o!="string"||o.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let o=e.scope,n=typeof o?.value=="string"&&o.value.length>0&&o.value.length<=255&&o.valueFrom===void 0,r=typeof o?.valueFrom=="string"&&o.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(o.valueFrom)&&!o.valueFrom.split(".").some(i=>["__proto__","prototype","constructor"].includes(i))&&o.value===void 0;if(!o||typeof o!="object"||Array.isArray(o)||Object.keys(o).some(i=>!["dimension","value","valueFrom"].includes(i))||typeof o.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.dimension)||!n&&!r)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function Yn(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:typeof e.until=="object"&&e.until.roleCode?[e.until.roleCode]:[]}function Dp(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.roleCodes!==void 0))}function Xn(e){if(e.selectedInputPath===void 0)return[];let t=e.selectedInputPath;return!["app_role","app_role_in_scope"].includes(e.provider||"")||e.candidateField!==void 0||e.inputPath!==void 0||e.routing!==void 0||e.roleCode===void 0&&e.roleCodes===void 0||typeof t!="string"||t.length>255||!/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(t)||t.split(".").some(o=>["__proto__","constructor","prototype"].includes(o))?["WORKFLOW_V2_ROLE_INPUT_SELECTION_INVALID"]:[]}function kp(e){return e.some(t=>Object.values(t.binding.bindings).some(o=>o.selectedInputPath!==void 0))}var Fc="platform-notify-v1",vp="platform.notify",Vc={type:"object",additionalProperties:!1,properties:{text:{type:"string",minLength:1,maxLength:2048}},required:["text"]},Wc={type:"object",additionalProperties:!1,properties:{}},Er=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Zn=e=>JSON.stringify(e,(t,o)=>Er(o)?Object.fromEntries(Object.keys(o).sort().map(n=>[n,o[n]])):o);function ie(e){return e?.kind==="action"&&e.handler?.code===Fc&&e.notification!==void 0}function Pp(e){return{...e.notification.recipients,min:1,max:50,delegatable:!1}}function Qn(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(n?.notification===void 0)continue;(!ie(n)||n.handler.version!==1||n.handler.mode!=="reconciled-effect"||n.handler.dataTransaction!==void 0||Zn(n.inputSchema)!==Zn(Vc)||Zn(n.outputSchema)!==Zn(Wc))&&t.push(`WORKFLOW_NOTIFY_PRESET_INVALID:${o}`),n.inputs?.text?.source==="literal"&&(typeof n.inputs.text.value!="string"||!n.inputs.text.value.trim())&&t.push(`WORKFLOW_NOTIFY_TEXT_INVALID:${o}`);let r=n.notification,i=r?.recipients;if(!Er(r)||Object.keys(r).some(a=>!["template","recipients"].includes(a))||r.template!=="workflow_message"||!Er(i)){t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`);continue}let s=Object.keys(i);i.provider==="initiator"?s.length!==1&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`):i.provider==="fixed_users"?(s.some(a=>!["provider","users"].includes(a))||!Array.isArray(i.users)||i.users.length<1||i.users.length>50||new Set(i.users).size!==i.users.length||i.users.some(a=>typeof a!="string"||!a.trim()||a.length>255))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`):i.provider==="app_role"?(s.some(a=>!["provider","roleCode"].includes(a))||typeof i.roleCode!="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(i.roleCode))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`):i.provider==="form_field_users"?(s.some(a=>!["provider","inputPath"].includes(a))||typeof i.inputPath!="string"||!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*$/.test(i.inputPath)||i.inputPath.length>256||i.inputPath.split(".").length>8||i.inputPath.split(".").some(a=>["prototype","constructor","__proto__"].includes(a)))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`):t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${o}`)}return t}var Ir="openxiangda.workflow.step.requested.v2",Vp=[Ir,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],br=16384,xc=2048,Wp="steps",hr=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Is=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ct=new Set(["__proto__","prototype","constructor"]),X=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),ys=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},zt=(e,t,o=0)=>{if(o>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((i,s)=>zt(i,t[s],o+1));if(!X(e)||!X(t))return!1;let n=Object.keys(e).filter(i=>e[i]!==void 0),r=Object.keys(t).filter(i=>t[i]!==void 0);return n.length===r.length&&n.every(i=>Object.hasOwn(t,i)&&zt(e[i],t[i],o+1))};function yr(e,t){let o=0,n=(r,i)=>++o>1e4||i>8?!1:r===null||typeof r=="boolean"||typeof r=="string"?!0:typeof r=="number"?Number.isFinite(r):Array.isArray(r)?r.length<=200&&r.every(s=>n(s,i+1)):X(r)&&Object.keys(r).length<=32&&Object.keys(r).every(s=>!Ct.has(s))&&Object.values(r).every(s=>n(s,i+1));return ys(e)<=t&&n(e,0)}function jc(e){return!X(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&&X(e.output)&&yr(e.output,br)&&(e.receipt===void 0||X(e.receipt)&&yr(e.receipt,xc))}function xp(e){return X(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","dataTransaction","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&hr.test(e.nodeId)&&!Ct.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&jc({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function Gt(e,t,o=br){if(!yr(t,o))return!1;let n=1e4,r=(i,s,a)=>{if(--n<0||a>8||!X(i))return!1;let d=s===null?"null":Array.isArray(s)?"array":typeof s=="number"&&Number.isSafeInteger(s)?"integer":typeof s,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(d)&&!(d==="integer"&&c.includes("number"))||i.enum!==void 0&&(!Array.isArray(i.enum)||!i.enum.some(l=>zt(l,s)))||Object.hasOwn(i,"const")&&!zt(i.const,s))return!1;if(typeof s=="number")return Number.isFinite(s)&&(i.minimum===void 0||s>=i.minimum)&&(i.maximum===void 0||s<=i.maximum);if(typeof s=="string"){let l=Array.from(s).length;return(i.minLength===void 0||l>=i.minLength)&&(i.maxLength===void 0||l<=i.maxLength)}return Array.isArray(s)?s.length<=i.maxItems&&(i.minItems===void 0||s.length>=i.minItems)&&s.every(l=>r(i.items,l,a+1)):X(s)?!X(i.properties)||Object.keys(s).some(l=>Ct.has(l)||!Object.hasOwn(i.properties,l))||(Array.isArray(i.required)?i.required:[]).some(l=>!Object.hasOwn(s,l))||i.minProperties!==void 0&&Object.keys(s).length<i.minProperties||i.maxProperties!==void 0&&Object.keys(s).length>i.maxProperties?!1:Object.entries(s).every(([l,f])=>r(i.properties[l],f,a+1)):s===null||typeof s=="boolean"};return r(e,t,0)}function Uc(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>hr.test(t)&&!Ct.has(t))}function Jt(e){let t=0,o=(n,r)=>{if(!X(n)||r>6||++t>256||Object.keys(n).some(a=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(a)))return!1;let i=Array.isArray(n.type)?n.type:[n.type];if(!i.length||i.length>2||i.some(a=>!["object","array","string","integer","number","boolean","null"].includes(a))||i.length>1&&(!i.includes("null")||new Set(i).size!==i.length))return!1;for(let a of["title","description"])if(n[a]!==void 0&&(typeof n[a]!="string"||n[a].length>2e3))return!1;for(let a of["minimum","maximum"])if(n[a]!==void 0&&(typeof n[a]!="number"||!Number.isFinite(n[a])))return!1;for(let[a,d]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(n[a]!==void 0&&(!Number.isSafeInteger(n[a])||n[a]<0||n[a]>d))return!1;for(let[a,d]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(n[a]!==void 0&&n[d]!==void 0&&n[a]>n[d])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(a=>n[a]!==void 0)&&!i.includes("object")||["items","maxItems","minItems"].some(a=>n[a]!==void 0)&&!i.includes("array")||["maxLength","minLength"].some(a=>n[a]!==void 0)&&!i.includes("string")||["minimum","maximum"].some(a=>n[a]!==void 0)&&!i.some(a=>a==="integer"||a==="number")||n.enum!==void 0&&(!Array.isArray(n.enum)||!n.enum.length||n.enum.length>100)||i.includes("object")&&(!X(n.properties)||n.additionalProperties!==!1||Object.keys(n.properties).length>32||Object.keys(n.properties).some(a=>!Is.test(a)||Ct.has(a))||n.required!==void 0&&(!Array.isArray(n.required)||new Set(n.required).size!==n.required.length||n.required.some(a=>typeof a!="string"||!Object.hasOwn(n.properties,a)))||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(a=>o(a,r+1)))||i.includes("array")&&(!Number.isSafeInteger(n.maxItems)||!o(n.items,r+1)))return!1;let s={...n};return delete s.enum,delete s.const,!(n.enum!==void 0&&(!n.enum.every(a=>Gt(s,a))||n.enum.some((a,d)=>n.enum.slice(0,d).some(c=>zt(a,c))))||Object.hasOwn(n,"const")&&!Gt(s,n.const))};return X(e)&&e.type==="object"&&ys(e)<=br&&o(e,0)}function _t(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(o=>o?.kind==="action").map(o=>[o.id,o.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function Os(e,t){let o=e;for(let n of t.split(".")){if(!X(o?.properties)||!Object.hasOwn(o.properties,n))return;o=o.properties[n]}return X(o)?o:void 0}var As=(e,t)=>!!Os(e,t);function jp(e){return X(e)&&Object.keys(e).every(t=>["version","mode","dataTransaction","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&Jt(e.inputSchema)&&Jt(e.outputSchema)}function Es(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="parallel"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.join]:e.kind==="join"?[e.next]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"||e.kind==="handle"?[e.next]:[]}function Or(e,t=0){return!X(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(o=>Or(e[o],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(o=>Or(o,t+1)):[])}function Mc(e){if(e.authoring===void 0)return[];let t=e.authoring;if(!X(t)||Object.keys(t).some(r=>r!=="businessSteps")||t.businessSteps!==void 0&&(!Array.isArray(t.businessSteps)||t.businessSteps.length>100))return["WORKFLOW_AUTHORING_CATALOG_INVALID"];let o=[],n=new Set;for(let r of t.businessSteps||[]){let i=r?.handler;(!X(r)||Object.keys(r).some(s=>!["title","handler","inputSchema","outputSchema"].includes(s))||typeof r.title!="string"||!r.title.trim()||r.title.length>160||!X(i)||Object.keys(i).some(s=>!["code","version","mode","dataTransaction"].includes(s))||!Number.isSafeInteger(i.version)||i.version<1||i.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(i.code||"")||!i.code.endsWith(`-v${i.version}`)||!["pure","reconciled-effect"].includes(i.mode)||i.dataTransaction!==void 0&&(i.dataTransaction!==!0||i.mode!=="reconciled-effect")||!Jt(r.inputSchema)||!Jt(r.outputSchema)||n.has(i.code))&&o.push("WORKFLOW_AUTHORING_STEP_INVALID"),i?.code&&n.add(i.code)}return o}function eo(e,t){if(!X(e)||!X(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let o=e.nodes,n=Object.entries(o).filter(([,a])=>a?.kind==="action");if(!n.length)return[];let r=[...Qn(e),...Mc(e)];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&r.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let i=_t(e);for(let[a,d]of n){(Object.keys(d).some(f=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs",...ie(d)?["notification"]:[]].includes(f))||d.id!==a||!hr.test(a)||Ct.has(a)||typeof d.title!="string"||!d.title.trim()||d.title.length>255||typeof d.next!="string"||!Object.hasOwn(o,d.next))&&r.push(`WORKFLOW_STEP_NODE_INVALID:${a}`);let c=d.handler;(!X(c)||Object.keys(c).some(f=>!["code","version","mode","dataTransaction"].includes(f))||!Number.isSafeInteger(c.version)||c.version<1||c.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(c.code||"")||!String(c.code).endsWith(`-v${c.version}`)||!["pure","reconciled-effect"].includes(c.mode)||c.dataTransaction!==void 0&&(c.dataTransaction!==!0||c.mode!=="reconciled-effect"))&&r.push(`WORKFLOW_STEP_HANDLER_INVALID:${a}`);let l=Jt(d.inputSchema);if((!l||!Jt(d.outputSchema))&&r.push(`WORKFLOW_STEP_SCHEMA_INVALID:${a}`),!X(d.inputs)||Object.keys(d.inputs).length>32){r.push(`WORKFLOW_STEP_INPUTS_INVALID:${a}`);continue}for(let f of Array.isArray(d.inputSchema?.required)?d.inputSchema.required:[])Object.hasOwn(d.inputs,f)||r.push(`WORKFLOW_STEP_INPUT_REQUIRED:${a}:${f}`);for(let[f,p]of Object.entries(d.inputs)){if(!Is.test(f)||Ct.has(f)||!Object.hasOwn(d.inputSchema?.properties||{},f)||!X(p)){r.push(`WORKFLOW_STEP_INPUT_INVALID:${a}:${f}`);continue}if(p.source==="literal")(!l||Object.keys(p).some(m=>!["source","value"].includes(m))||!Object.hasOwn(p,"value")||!Gt(d.inputSchema.properties[f],p.value))&&r.push(`WORKFLOW_STEP_LITERAL_INVALID:${a}:${f}`);else if(p.source!=="fact"||Object.keys(p).some(m=>!["source","path"].includes(m))||!Uc(p.path)||!As(i,p.path))r.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${a}:${f}`);else if(l){let m=Os(i,p.path),A=d.inputSchema.properties[f],I=Array.isArray(m.type)?m.type:[m.type],O=Array.isArray(A.type)?A.type:[A.type];I.some(b=>!O.includes(b)&&!(b==="integer"&&O.includes("number")))&&r.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${a}:${f}`)}}}let s=(a,d)=>{let c=new Set,l=[e.startAt||""];for(;l.length&&c.size<=200;){let f=l.shift();if(!(f===d||c.has(f)||!o[f])){if(f===a)return!0;c.add(f),l.push(...Es(o[f]))}}return!1};for(let[a,d]of Object.entries(o)){if(!X(d))continue;let c=d.kind==="action"?Object.values(d.inputs||{}).flatMap(f=>f?.source==="fact"?[f.path]:[]):(Array.isArray(d.branches)?d.branches:[]).flatMap(f=>Or(f?.when)),l=t?.bindings?.[d.binding];l&&c.push(...[l.inputPath,l.departmentIdFrom,l.resourceIdFrom,l.scope?.valueFrom].filter(f=>typeof f=="string"));for(let f of c.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=f.split(".")[1];(o[p]?.kind!=="action"||p===a||!As(i,f)||s(a,p))&&r.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${a}:${f}`)}}if(t)for(let[,a]of n.filter(([,d])=>!ie(d))){let d=new Set,c=[a.next];for(;c.length&&d.size<=200;){let l=c.shift();if(d.has(l)||!X(o[l]))continue;d.add(l);let f=o[l];if(!(f.kind==="action"||f.kind==="end")){if(f.kind==="approval"){let p=t.bindings?.[f.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&r.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${l}`);continue}c.push(...Es(f))}}}return[...new Set(r)]}function Up(e,t){let o={};for(let[n,r]of Object.entries(e.inputs)){let i=r.source==="literal"?r.value:r.path.split(".").reduce((s,a)=>X(s)&&Object.hasOwn(s,a)?s[a]:void 0,t);i!==void 0&&(o[n]=i)}if(!Gt(e.inputSchema,o))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return o}function bs(e,t,o){let n=Nr(e),r=[];Object.keys(n).length&&!o&&r.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let i of Object.keys(n)){let s=t.find(a=>a.code===i);(!s||s.execution||s.action||!Array.isArray(s.eventTypes)||s.eventTypes.length!==1||s.eventTypes[0]!==Ir||!X(s.filter)||Object.keys(s.filter).length!==1||!X(s.filter.workflowStep)||Object.keys(s.filter.workflowStep).length!==1||s.filter.workflowStep.handlerCode!==i||!X(s.payload)||s.payload.includeChanges!==!1||!Array.isArray(s.payload.fields)||s.payload.fields.length)&&r.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${i}`)}for(let i of t)(i.eventTypes?.includes(Ir)&&!n[i.code]||i.filter?.workflowStep&&!n[i.code])&&r.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${i.code}`);return r}function Nr(e){let t={};for(let o of e){let n=eo(o);if(n.length)throw new Error(n.join("; "));for(let r of[...Object.values(o.nodes||{}),...o.authoring?.businessSteps||[]]){if(!r.handler||ie(r))continue;let i={version:r.handler.version,mode:r.handler.mode,...r.handler.dataTransaction?{dataTransaction:!0}:{},inputSchema:r.inputSchema,outputSchema:r.outputSchema},s=t[r.handler.code];if(s&&!zt(s,i))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${r.handler.code}`);t[r.handler.code]=i}}return t}var wr=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Bc=e=>typeof e=="string"&&e.length<=255&&e.split(".").length<=8&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function Ht(e){if(e?.provider!=="supervisor_chain")return e&&["from","until","continuous","missing"].some(n=>e[n]!==void 0)?["WORKFLOW_SUPERVISOR_CHAIN_PROVIDER_INVALID"]:[];let t=e.from,o=e.until;return!wr(e)||Object.keys(e).some(n=>!["provider","from","until","continuous","missing","min","max","delegatable"].includes(n))||!(t==="initiator"||wr(t)&&Object.keys(t).length===1&&Bc(t.field))||!(o==="top"||wr(o)&&Object.keys(o).length===1&&(Number.isInteger(o.level)&&o.level>=1&&o.level<=20||typeof o.roleCode=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(o.roleCode)&&o.roleCode.length<=128))||e.continuous!==void 0&&typeof e.continuous!="boolean"||e.missing!==void 0&&!["skip_level","block"].includes(e.missing)?["WORKFLOW_SUPERVISOR_CHAIN_BINDING_INVALID"]:[]}function At(e,t){let o=[];for(let[n,r]of Object.entries(t?.bindings||{}))o.push(...Ht(r).map(i=>`${i}:${n}`));for(let[n,r]of Object.entries(e?.nodes||{})){let i=t?.bindings?.[r?.binding];if(!(i?.provider!=="supervisor_chain"||Ht(i).length))if(["approval","handle"].includes(r.kind)||o.push(`WORKFLOW_SUPERVISOR_CHAIN_HUMAN_REQUIRED:${n}`),i.continuous!==!1&&r.mode!=="sequence"&&o.push(`WORKFLOW_SUPERVISOR_CHAIN_SEQUENCE_REQUIRED:${n}`),i.from==="initiator")(!e.organizationContext?.department||e.organizationContext.department.source==="none")&&o.push(`WORKFLOW_SUPERVISOR_CHAIN_DEPARTMENT_CONTEXT_REQUIRED:${n}`);else{let s=_t(e);for(let d of i.from.field.split("."))s=s?.properties?.[d];let a=Array.isArray(s?.type)?s.type.filter(d=>d!=="null")[0]:s?.type;(!s||!["string","array","object"].includes(a))&&o.push(`WORKFLOW_SUPERVISOR_CHAIN_USER_FACT_REQUIRED:${n}`)}}return o}function Kp(e){let t=e.from==="initiator"?"\u7533\u8BF7\u4EBA":`\u6210\u5458\u53D8\u91CF ${e.from.field}`,o=e.until==="top"?"\u6700\u4E0A\u7EA7":"level"in e.until?`\u7B2C ${e.until.level} \u7EA7`:`\u89D2\u8272 ${e.until.roleCode}`;return`${t}\u7684\u4E3B\u7BA1\u94FE \xB7 \u81F3${o} \xB7 ${e.continuous!==!1?"\u9010\u7EA7\u529E\u7406":"\u4EC5\u7EC8\u70B9\u529E\u7406"}`}var zp=256,Gp=64,Jp=262144,Kc=/^[a-z][a-z0-9_-]{0,127}$/,qc=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,Ns=new Set(["__proto__","prototype","constructor"]),Ze=e=>!!e&&typeof e=="object"&&!Array.isArray(e),In=(e,t)=>Object.keys(e).every(o=>t.includes(o)),St=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),dt=e=>typeof e=="string"&&Kc.test(e)&&!Ns.has(e),ws=e=>typeof e=="string"&&e.length<=255&&qc.test(e)&&!e.split(".").some(t=>Ns.has(t)),zc=e=>Ze(e)&&In(e,["dimension","valueFrom","value"])&&dt(e.dimension)&&(St(e.value,255)&&e.valueFrom===void 0||ws(e.valueFrom)&&e.value===void 0),hs=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)),En={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},Rr={type:"string",minLength:1,maxLength:128},Rs={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:En,title:Rr,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:En,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:Rr,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:En,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:Rr,provider:{enum:["app_role","app_role_in_scope"]},roleCode:En,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:En,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function Yt(e){if(!Ze(e)||!In(e,["policyCode","title","strategy","dimensions","sources"])||!dt(e.policyCode)||!St(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Ze(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([o,n])=>!dt(o)||!Ze(n)||!In(n,["title","valueFrom"])||!St(n.title,128)||!ws(n.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Ze(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([o,n])=>!dt(o)||!Ze(n)||!In(n,["title","provider","roleCode","scope"])||!St(n.title,128)||!dt(n.roleCode)||!["app_role","app_role_in_scope"].includes(n.provider)||(n.provider==="app_role_in_scope"?!zc(n.scope):n.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function Hp(e,t){if(Yt(e).length)return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];if(!Array.isArray(t)||t.length>256||new TextEncoder().encode(JSON.stringify(t)).length>262144)return["WORKFLOW_V2_ROUTING_RULE_LIMIT_EXCEEDED"];let o=[],n=new Set;for(let r of t){if(!Ze(r)||!In(r,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!dt(r.ruleCode)||!St(r.title,128)||typeof r.enabled!="boolean"||!dt(r.sourceCode)||!Object.hasOwn(e.sources,r.sourceCode)||!["append","replace"].includes(r.effect)||!Number.isSafeInteger(r.priority)||r.priority<-1e3||r.priority>1e3||r.workflowCode!==void 0&&!dt(r.workflowCode)||r.nodeId!==void 0&&(!dt(r.nodeId)||r.workflowCode===void 0)||r.validFrom!==void 0&&!hs(r.validFrom)||r.validTo!==void 0&&!hs(r.validTo)||r.validFrom&&r.validTo&&Date.parse(r.validFrom)>=Date.parse(r.validTo)){o.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}n.has(r.ruleCode)&&o.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${r.ruleCode}`),n.add(r.ruleCode),(!Ze(r.matches)||Object.entries(r.matches).some(([i,s])=>!Object.hasOwn(e.dimensions,i)||!Array.isArray(s)||s.length<1||s.length>64||new Set(s).size!==s.length||s.some(a=>!St(a,255))))&&o.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${r.ruleCode}`)}return[...new Set(o)]}function Gc(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 Ts(e){let t=[],o=new Map;for(let n of e)for(let[r,i]of Object.entries(n.bindings||{})){if(!Ze(i)||i.routing===void 0)continue;let s=Yt(i.routing);if(s.length){t.push(...s.map(c=>`${c}:${r}`));continue}let a=Gc(i.routing),d=o.get(i.routing.policyCode);d&&d!==a&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${i.routing.policyCode}`),o.set(i.routing.policyCode,a)}return[...new Set(t)]}function Yp(e,t){let o={};for(let[n,r]of Object.entries(e.dimensions)){let i=t;for(let s of r.valueFrom.split("."))i=Ze(i)&&Object.hasOwn(i,s)?i[s]:void 0;if(!(typeof i=="string"&&St(i,255)||typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${n}`);o[n]=String(i)}return o}function Xp(e,t,o){let n=t.filter(c=>c.enabled&&(!c.validFrom||Date.parse(c.validFrom)<=o.at)&&(!c.validTo||Date.parse(c.validTo)>o.at)&&(!c.workflowCode||c.workflowCode===o.workflowCode)&&(!c.nodeId||c.nodeId===o.nodeId)&&Object.entries(c.matches).every(([l,f])=>f.includes(o.facts[l])));if(n.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let r=(c,l)=>l.priority-c.priority||+!!c.workflowCode-+!!l.workflowCode||+!!c.nodeId-+!!l.nodeId||(c.ruleCode<l.ruleCode?-1:c.ruleCode>l.ruleCode?1:0),i=n.filter(c=>c.effect==="replace").sort(r);if(i.length>1&&i[0].priority===i[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let s=i[0],a=s&&e.strategy==="replace_only"?[]:n.filter(c=>c.effect==="append").sort(r),d=[...s?[s]:[],...a];return{matched:n.sort(r),replacement:s,applied:d,ignored:n.filter(c=>!d.includes(c))}}var Tr={type:"string",minLength:1},Jc={type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},Dt={type:"object",additionalProperties:!1,required:["provider"],allOf:[{if:{required:["roleCodes"]},then:{properties:{provider:{enum:["app_role","app_role_in_scope"]}},not:{anyOf:[{required:["roleCode"]},{required:["candidateField"]}]}}},{if:{required:["candidateField"]},then:{required:["inputPath"],properties:{provider:{const:"form_field_users"}},not:{anyOf:[{required:["roleCode"]},{required:["scope"]},{required:["routing"]}]}}},{if:{required:["selectedInputPath"]},then:{properties:{provider:{enum:["app_role","app_role_in_scope"]}},anyOf:[{required:["roleCode"]},{required:["roleCodes"]}],not:{anyOf:[{required:["candidateField"]},{required:["inputPath"]},{required:["routing"]}]}}}],properties:{provider:{enum:["fixed_users","initiator","input_users","form_field_users","department_supervisor","supervisor_chain","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"]},users:{type:"array",uniqueItems:!0,items:Tr},inputPath:{type:"string"},selectedInputPath:{type:"string",maxLength:255,pattern:"^[A-Za-z][A-Za-z0-9_-]*(?:\\.[A-Za-z][A-Za-z0-9_-]*)*$"},candidateField:Jc,from:{oneOf:[{const:"initiator"},{type:"object",additionalProperties:!1,required:["field"],properties:{field:{type:"string",maxLength:255}}}]},until:{oneOf:[{const:"top"},{type:"object",additionalProperties:!1,required:["level"],properties:{level:{type:"integer",minimum:1,maximum:20}}},{type:"object",additionalProperties:!1,required:["roleCode"],properties:{roleCode:Tr}}]},continuous:{type:"boolean"},missing:{enum:["skip_level","block"]},departmentIdFrom:{type:"string"},level:{type:"integer",minimum:1,maximum:20},fallbackToAncestorSupervisor:{type:"boolean"},roleCode:{type:"string"},roleCodes:_s,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:Tr,valueFrom:{type:"string"},value:{type:"string"}}},relationCode:{type:"string"},resourceCode:{type:"string"},resourceIdFrom:{type:"string"},providerCode:{type:"string"},min:{type:"integer",minimum:1,maximum:200},max:{type:"integer",minimum:1,maximum:200},delegatable:{type:"boolean"},routing:Rs}};var kt={type:"object",required:["op"],properties:{op:{enum:["literal","path","eq","neq","gt","gte","lt","lte","in","contains","and","or","not","exists"]},value:{},path:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_.]{0,254}$"},left:{type:"object"},right:{type:"object"},values:{type:"array",minItems:1,items:{type:"object"}}}};var no=20,Cr=16384,yn=["fixed_users","app_role","app_role_in_scope","supervisor_chain","department_supervisor","form_field_users","input_users","initiator","previous_node_actor","business_relation"],to=Dt,Sr={type:"object",additionalProperties:!1,required:["provider","cases","otherwise"],properties:{provider:{const:"conditional"},cases:{type:"array",minItems:1,maxItems:no,items:{type:"object",additionalProperties:!1,required:["when","assignee"],properties:{label:{type:"string",minLength:1,maxLength:160},when:kt,assignee:{...to,properties:{...to.properties,provider:{enum:yn}}}}}},otherwise:{...to,properties:{...to.properties,provider:{enum:yn}}}}};var Hc=Dt,Cs=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Dr=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Ss=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),oo=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(e)&&e.split(".").every(t=>!!t&&!["__proto__","prototype","constructor"].includes(t)),ro=e=>typeof e=="string"&&e.length<=128&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e);function Lt(e,t=!1){if(!Cs(e)||!yn.includes(e.provider)||!Dr(e,Object.keys(Hc.properties)))return["WORKFLOW_CONDITIONAL_LEAF_INVALID"];let o=[...Ht(e),...qt(e),...Xn(e)];return Dr(e,["provider","min","max","delegatable",...{fixed_users:["users"],app_role:["roleCode","roleCodes","selectedInputPath","routing"],app_role_in_scope:["roleCode","roleCodes","scope","selectedInputPath","routing"],supervisor_chain:["from","until","continuous","missing"],department_supervisor:["departmentIdFrom","level","fallbackToAncestorSupervisor"],form_field_users:["inputPath","candidateField"],input_users:["inputPath"],initiator:[],previous_node_actor:[],business_relation:["relationCode","resourceCode","resourceIdFrom"]}[e.provider]])||o.push("WORKFLOW_CONDITIONAL_LEAF_FIELDS_INVALID"),e.routing!==void 0&&o.push(...Yt(e.routing)),(["min","max"].some(r=>e[r]!==void 0&&(!Number.isInteger(e[r])||e[r]<1||e[r]>200))||(e.min??1)>(e.max??200)||e.delegatable!==void 0&&typeof e.delegatable!="boolean")&&o.push("WORKFLOW_CONDITIONAL_LEAF_BOUNDS_INVALID"),e.provider==="fixed_users"&&(!Array.isArray(e.users)||!t&&!e.users.length||e.users.length>200||new Set(e.users).size!==e.users.length||e.users.some(r=>!Ss(r,255)))&&o.push("WORKFLOW_CONDITIONAL_USERS_INVALID"),["app_role","app_role_in_scope"].includes(e.provider)&&e.roleCodes===void 0&&!(t&&e.roleCode===void 0)&&!ro(e.roleCode)&&o.push("WORKFLOW_CONDITIONAL_ROLE_INVALID"),e.provider==="app_role_in_scope"&&(!Cs(e.scope)||!Dr(e.scope,["dimension","value","valueFrom"])||!ro(e.scope.dimension)||!(Ss(e.scope.value,255)&&e.scope.valueFrom===void 0||oo(e.scope.valueFrom)&&e.scope.value===void 0))&&o.push("WORKFLOW_CONDITIONAL_SCOPE_INVALID"),["input_users","form_field_users"].includes(e.provider)&&!oo(e.inputPath)&&o.push("WORKFLOW_CONDITIONAL_INPUT_PATH_INVALID"),e.provider==="business_relation"&&(!ro(e.relationCode)||!ro(e.resourceCode)||!oo(e.resourceIdFrom))&&o.push("WORKFLOW_CONDITIONAL_RELATION_INVALID"),e.provider==="department_supervisor"&&(!oo(e.departmentIdFrom)||e.level!==void 0&&(!Number.isInteger(e.level)||e.level<1||e.level>20)||e.fallbackToAncestorSupervisor!==void 0&&typeof e.fallbackToAncestorSupervisor!="boolean")&&o.push("WORKFLOW_DEPARTMENT_SUPERVISOR_INVALID"),o}var Ds={department_supervisor:["departmentIdFrom","level","fallbackToAncestorSupervisor","min","max"],supervisor_chain:["from","until","continuous","missing","min","max"],form_field_users:["inputPath","min","max"],input_users:["inputPath","min","max"],app_role_in_scope:["roleCode","scope","min","max"]},vt=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function ks(e){let t=4096,o=(n,r)=>--t<0||r>12?!1:n===null||typeof n=="boolean"?!0:typeof n=="string"?n.length<=2048:typeof n=="number"?Number.isFinite(n):Array.isArray(n)?n.length<=200&&n.every(i=>o(i,r+1)):vt(n)&&Object.keys(n).every(i=>!["__proto__","prototype","constructor"].includes(i)&&!Object.getOwnPropertyDescriptor(n,i)?.get&&o(n[i],r+1));try{return o(e,0)&&new TextEncoder().encode(JSON.stringify(e)).length<=32768}catch{return!1}}var Pt=e=>{let t=o=>Array.isArray(o)?o.map(t):vt(o)?Object.fromEntries(Object.keys(o).filter(n=>o[n]!==void 0).sort().map(n=>[n,t(o[n])])):o;return JSON.stringify(t(e))},Yc=(e,t)=>Array.isArray(t.values)?t.values.some(o=>Pt(o)===Pt(e)):Number.isSafeInteger(e)&&e>=t.minimum&&e<=t.maximum;function kr(e){if(!ks(e)||!vt(e)||Object.keys(e).some(t=>!["code","title","entry","parameters"].includes(t))||typeof e.code!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.code)||typeof e.title!="string"||!e.title.trim()||e.title.length>160||!vt(e.entry)||!Ds[e.entry.provider]||Lt(e.entry).length||!vt(e.parameters)||!Object.keys(e.parameters).length||Object.keys(e.parameters).length>8)return["WORKFLOW_PEOPLE_SOURCE_TEMPLATE_INVALID"];for(let[t,o]of Object.entries(e.parameters)){if(!Ds[e.entry.provider].includes(t)||!vt(o))return["WORKFLOW_PEOPLE_SOURCE_PARAMETER_INVALID"];if(Object.hasOwn(o,"values")){if(Object.keys(o).length!==1||!Array.isArray(o.values)||!o.values.length||o.values.length>32||new Set(o.values.map(Pt)).size!==o.values.length)return["WORKFLOW_PEOPLE_SOURCE_PARAMETER_INVALID"];for(let n of o.values){let r={...e.entry,[t]:n};if(Lt(r).length||t==="scope"&&n?.dimension!==e.entry.scope?.dimension||t==="min"&&n<(e.entry.min??1)||t==="max"&&n>(e.entry.max??200))return["WORKFLOW_PEOPLE_SOURCE_PARAMETER_CEILING"]}}else if(Object.keys(o).some(n=>!["minimum","maximum"].includes(n))||!["level","min","max"].includes(t)||!Number.isSafeInteger(o.minimum)||!Number.isSafeInteger(o.maximum)||o.minimum<1||o.maximum<o.minimum||o.maximum>(t==="level"?20:200)||t==="min"&&o.minimum<(e.entry.min??1)||t==="max"&&o.maximum>(e.entry.max??200))return["WORKFLOW_PEOPLE_SOURCE_PARAMETER_CEILING"]}return[]}function Ls(e){let t=e.authoring?.peopleSources;if(t===void 0)return[];if(!Array.isArray(t)||t.length>32)return["WORKFLOW_PEOPLE_SOURCE_TEMPLATE_LIMIT"];let o=t.flatMap(kr);if(o.length)return[...new Set(o)];if(new Set(t.map(s=>s.code)).size!==t.length)return["WORKFLOW_PEOPLE_SOURCE_TEMPLATE_LIMIT"];let n=_t(e),r=s=>{if(typeof s!="string"||s.split(".").some(d=>!d||["__proto__","prototype","constructor"].includes(d)))return;let a=n;for(let d of s.split("."))a=vt(a?.properties)&&Object.hasOwn(a.properties,d)?a.properties[d]:void 0;return a},i=[];for(let s of t){let a=kr(s);if(a.length){i.push(...a);continue}let d=[s.entry,...Object.entries(s.parameters).flatMap(([c,l])=>l.values?.map(f=>({...s.entry,[c]:f}))||[])];for(let c of d){for(let l of[c.inputPath,c.departmentIdFrom,c.scope?.valueFrom,...typeof c.from=="object"?[c.from.field]:[]].filter(f=>f!==void 0))r(l)||i.push("WORKFLOW_PEOPLE_SOURCE_FACT_UNAVAILABLE");if(c.provider==="supervisor_chain"){let l={...e,nodes:{probe:{id:"probe",kind:"approval",mode:c.continuous===!1?"single":"sequence",binding:"probe"}}};i.push(...At(l,{bindings:{probe:c}}))}}}return[...new Set(i)]}function Xc(e,t,o=!0){if(!ks(e)||kr(t).length||e.provider!==t.entry.provider)return!1;let n=r=>Object.fromEntries(Object.entries(r).filter(([i])=>!Object.hasOwn(t.parameters,i)));return Pt(n(e))!==Pt(n(t.entry))?!1:!o||!Lt(e).length&&Object.entries(t.parameters).every(([r,i])=>Pt(e[r])===Pt(t.entry[r])||Yc(e[r],i))}function io(e,t=[]){return Array.isArray(t)&&t.length<=32&&t.some(o=>Xc(e,o))}function vs(e,t,o={}){let n=1024,r=()=>{throw new Error("WORKFLOW_V2_EXPRESSION_TYPE_INVALID")},i=d=>d===null||["string","number","boolean"].includes(typeof d),s=d=>o.strict?typeof d=="boolean"?d:r():!!d,a=(d,c=0,l=!1)=>{if(--n<0||c>32)throw new Error("WORKFLOW_V2_EXPRESSION_LIMIT");let f=p=>a(p,c+1);switch(d?.op){case"literal":return o.strict&&typeof d.value=="number"&&!Number.isFinite(d.value)&&r(),d.value;case"path":{if(!/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(d.path||"")||d.path.split(".").some(m=>["__proto__","prototype","constructor"].includes(m)))throw new Error("WORKFLOW_V2_EXPRESSION_PATH_INVALID");let p=d.path.split(".").reduce((m,A)=>!m||typeof m!="object"||Array.isArray(m)||!Object.hasOwn(m,A)?void 0:m[A],t);if(o.strict){if(p===void 0&&(!l||o.requiredForPath?.(d.path)))throw new Error("WORKFLOW_V2_EXPRESSION_FACT_MISSING");let m=o.schemaForPath?.(d.path);(!m||p!==void 0&&!Gt(m,p))&&r()}return o.onPathRead?.(d.path,p),p}case"eq":case"neq":{let p=f(d.left),m=f(d.right);return o.strict&&(!i(p)||!i(m)||p!==null&&m!==null&&typeof p!=typeof m)&&r(),d.op==="eq"?p===m:p!==m}case"gt":case"gte":case"lt":case"lte":{let p=f(d.left),m=f(d.right);if(p===void 0||m===void 0)return!1;o.strict&&(typeof p!=typeof m||!["string","number"].includes(typeof p)||typeof p=="number"&&(!Number.isFinite(p)||!Number.isFinite(m)))&&r();let A=p===m?0:p>m?1:-1;return d.op==="gt"?A>0:d.op==="gte"?A>=0:d.op==="lt"?A<0:A<=0}case"in":{let p=f(d.left),m=f(d.right);return o.strict&&(!i(p)||!Array.isArray(m)||m.some(A=>!i(A)||typeof A!=typeof p))&&r(),Array.isArray(m)&&m.includes(p)}case"contains":{let p=f(d.left),m=f(d.right);return o.strict&&!(typeof p=="string"&&typeof m=="string"||Array.isArray(p)&&i(m)&&p.every(A=>i(A)&&typeof A==typeof m))&&r(),Array.isArray(p)?p.includes(m):typeof p=="string"&&p.includes(String(m))}case"and":return d.values.every(p=>s(f(p)));case"or":return d.values.some(p=>s(f(p)));case"not":return!s(f(d.value));case"exists":{let p=a(d.value,c+1,o.strict&&d.value.op==="path");return p!=null}default:throw new Error("WORKFLOW_V2_EXPRESSION_OPERATOR_INVALID")}};return a(e)}var ct=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Ke=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Zc=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),Vs=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(e)&&e.split(".").every(t=>!!t&&!["__proto__","prototype","constructor"].includes(t));function Qc(e){let t=4096,o=(n,r)=>--t<0||r>24?!1:n===null||["string","boolean"].includes(typeof n)?!0:typeof n=="number"?Number.isFinite(n):Array.isArray(n)?n.length<=200&&n.every(i=>o(i,r+1)):ct(n)&&Object.keys(n).every(i=>!["__proto__","prototype","constructor"].includes(i)&&Object.getOwnPropertyDescriptor(n,i)?.get===void 0&&o(n[i],r+1));try{return o(e,0)&&new TextEncoder().encode(JSON.stringify(e)).length<=Cr}catch{return!1}}var Ps=e=>{let t=o=>Array.isArray(o)?o.map(t):ct(o)?Object.fromEntries(Object.keys(o).sort().map(n=>[n,t(o[n])])):o;return JSON.stringify(t(e))};function ae(e,t={}){if(e.provider!=="conditional")return[e];if(ke(e,typeof t=="number"?{}:t).length)throw new Error("WORKFLOW_CONDITIONAL_BINDING_INVALID");return[...e.cases.map(o=>o.assignee),e.otherwise]}function Xt(e,t,o={}){let n=[];for(let[r,i]of Object.entries(t.bindings)){if(i.provider!=="conditional")continue;let s=ke(i,o);if(s.length){n.push(...s.map(a=>`${a}:${r}`));continue}for(let a of Object.values(e.nodes))!("binding"in a)||a.binding!==r||n.push(...Zt(i,{definition:e,nodeId:a.id,frozenDefault:i,releasedSources:{},standardProviders:[]},o).map(d=>`${d}:${r}:${a.id}`))}return[...new Set(n)]}function co(e,t={}){return{bindings:Object.fromEntries(Object.entries(e.bindings).flatMap(([o,n])=>n.provider==="conditional"?ae(n,t).map((r,i)=>[`${o}/leaves/${i}`,r]):[[o,n]]))}}function Ws(e,t=0,o={remaining:1024}){if(--o.remaining<0||t>20)return["WORKFLOW_CONDITIONAL_EXPRESSION_LIMIT"];if(!ct(e))return["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"];let n=r=>Ws(r,t+1,o);return e.op==="literal"?Ke(e,["op","value"])&&Object.hasOwn(e,"value")?[]:["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"]:e.op==="path"?Ke(e,["op","path"])&&Vs(e.path)?[]:["WORKFLOW_CONDITIONAL_PATH_INVALID"]:["and","or"].includes(e.op)?Ke(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=128?e.values.flatMap(n):["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"]:e.op==="exists"?Ke(e,["op","value"])&&ct(e.value)&&e.value.op==="path"?n(e.value):["WORKFLOW_CONDITIONAL_EXISTS_PATH_REQUIRED"]:e.op==="not"?Ke(e,["op","value"])?n(e.value):["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"]:["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&Ke(e,["op","left","right"])?[...n(e.left),...n(e.right)]:["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"]}function ke(e,t={}){if(!Qc(e))return["WORKFLOW_CONDITIONAL_BINDING_LIMIT"];if(!ct(e)||e.provider!=="conditional"||!Ke(e,["provider","cases","otherwise"])||!Array.isArray(e.cases)||e.cases.length<1||e.cases.length>no)return["WORKFLOW_CONDITIONAL_BINDING_INVALID"];let o=[];for(let[n,r]of e.cases.entries()){if(!ct(r)||!Ke(r,["label","when","assignee"])||r.label!==void 0&&!Zc(r.label,160)){o.push(`WORKFLOW_CONDITIONAL_CASE_INVALID:${n}`);continue}o.push(...Ws(r.when).map(i=>`${i}:${n}`),...Lt(r.assignee,t.allowIncomplete).map(i=>`${i}:${n}`))}return o.push(...Lt(e.otherwise,t.allowIncomplete).map(n=>`${n}:otherwise`)),[...new Set(o)]}function el(e){switch(e.kind){case"approval":return[e.onApprove,e.onReject];case"parallel":return[...e.branches.map(t=>t.target),e.join];case"condition":return[...e.branches.map(t=>t.target),e.otherwise];case"handle":case"cc":case"action":case"join":return[e.next];default:return[]}}function $s(e,t,o){let n=new Set,r=[e.startAt];for(;r.length&&n.size<200;){let i=r.shift(),s=e.nodes[i];if(!(i===o||n.has(i)||!s)){if(i===t)return!0;n.add(i),r.push(...el(s))}}return!1}function so(e,t,o){if(!Vs(o)||Object.keys(e.nodes).length>200||!e.nodes[t]||!$s(e,t))return;let n=e.inputSchema,r=o.split("."),i=!0;if(r[0]==="steps"){let s=r[1],a=e.nodes[s];if(a?.kind!=="action"||s===t||$s(e,t,s)||(n=a.outputSchema,r=r.slice(2),!r.length))return}for(let s of r)if(i&&=Array.isArray(n?.required)&&n.required.includes(s),n=ct(n?.properties)&&Object.hasOwn(n.properties,s)?n.properties[s]:void 0,!ct(n))return;return{schema:n,required:i}}var Fs=e=>[...new Set((Array.isArray(e.type)?e.type:[e.type]).map(t=>t==="integer"?"number":typeof t=="string"?t:"unknown"))];function ao(e,t,o,n,r=!1){let i=c=>ao(c,t,o,n),s=()=>{n.push("WORKFLOW_CONDITIONAL_OPERAND_TYPE_INVALID")},a=c=>c.types.every(l=>["string","number","boolean","null"].includes(l)),d=c=>c.types.length===1&&c.types[0]==="boolean";switch(e.op){case"path":{let c=so(t,o,e.path);return c?(!r&&!c.required&&n.push(`WORKFLOW_CONDITIONAL_FACT_OPTIONAL:${e.path}`),{types:Fs(c.schema),...ct(c.schema.items)?{itemTypes:Fs(c.schema.items)}:{}}):(n.push(`WORKFLOW_CONDITIONAL_FACT_UNAVAILABLE:${e.path}`),{types:["unknown"]})}case"literal":{let c=e.value;return{types:[c===null?"null":Array.isArray(c)?"array":typeof c],...Array.isArray(c)?{itemTypes:[...new Set(c.map(l=>l===null?"null":typeof l))]}:{}}}case"exists":return ao(e.value,t,o,n,!0),{types:["boolean"]};case"not":return d(i(e.value))||s(),{types:["boolean"]};case"and":case"or":for(let c of e.values)d(i(c))||s();return{types:["boolean"]};default:{let c=i(e.left),l=i(e.right);if(["eq","neq"].includes(e.op))(!a(c)||!a(l)||!c.types.some(f=>l.types.includes(f)))&&s();else if(["gt","gte","lt","lte"].includes(e.op))(c.types.length!==1||l.types.length!==1||c.types[0]!==l.types[0]||!["number","string"].includes(c.types[0]))&&s();else{let f=e.op==="in"?l:c,p=e.op==="in"?c:l;!(e.op==="contains"&&c.types.length===1&&l.types.length===1&&c.types[0]==="string"&&l.types[0]==="string")&&!(f.types.length===1&&f.types[0]==="array"&&a(p)&&f.itemTypes&&f.itemTypes.every(A=>["string","number","boolean","null"].includes(A)&&p.types.includes(A)))&&s()}return{types:["boolean"]}}}}function tl(e,t){return t.standardProviders.includes(e.provider)?e.provider==="fixed_users"?Ke(e,["provider","users"]):e.provider==="app_role"?Ke(e,["provider","roleCode","roleCodes"]):e.provider==="app_role_in_scope"&&Ke(e,["provider","roleCode","roleCodes","scope"])&&!!e.scope&&!!t.scopeDimensions?.includes(e.scope.dimension):!1}function Zt(e,t,o={}){let n=ke(e,o);if(n.length)return n;let r=e,i=t.definition.nodes[t.nodeId];if(!i||i.kind!=="approval"&&i.kind!=="handle")return["WORKFLOW_CONDITIONAL_HUMAN_REQUIRED"];let s=[],a=t.frozenDefault?ae(t.frozenDefault,o):[],d=Object.values(t.releasedSources);for(let[c,l]of[...r.cases.map(f=>f.assignee),r.otherwise].entries())!tl(l,t)&&![...a,...d].some(f=>Ps(f)===Ps(l))&&!io(l,t.peopleSourceTemplates)&&s.push(`WORKFLOW_CONDITIONAL_LEAF_UNRELEASED:${c}`),s.push(...Lr(l,t.definition,t.nodeId).map(f=>f.startsWith("WORKFLOW_CONDITIONAL_LEAF_FACT_UNAVAILABLE:")?`WORKFLOW_CONDITIONAL_LEAF_FACT_UNAVAILABLE:${c}:${f.slice(43)}`:f));for(let[c,l]of r.cases.entries()){let f=[],p=ao(l.when,t.definition,t.nodeId,f);(p.types.length!==1||p.types[0]!=="boolean")&&f.push("WORKFLOW_CONDITIONAL_BOOLEAN_REQUIRED"),s.push(...f.map(m=>`${m}:${c}`))}return[...new Set(s)]}function Nm(e,t,o,n){let r=ke(e);if(r.length)throw new Error(r[0]);let i=t.nodes[o];if(!i||!["approval","handle"].includes(i.kind))throw new Error("WORKFLOW_CONDITIONAL_HUMAN_REQUIRED");for(let d of e.cases){let c=[],l=ao(d.when,t,o,c);if((l.types.length!==1||l.types[0]!=="boolean")&&c.push("WORKFLOW_CONDITIONAL_BOOLEAN_REQUIRED"),c.length)throw new Error(c[0])}let s=[],a={strict:!0,schemaForPath:d=>so(t,o,d)?.schema,requiredForPath:d=>so(t,o,d)?.required===!0,onPathRead:(d,c)=>{s.push({path:d,present:c!==void 0,...c!==void 0?{value:c}:{}})}};for(let[d,c]of e.cases.entries()){let l=vs(c.when,n,a);if(typeof l!="boolean")throw new Error("WORKFLOW_CONDITIONAL_BOOLEAN_REQUIRED");if(l)return{assignee:c.assignee,matched:d,...c.label!==void 0?{label:c.label}:{},factReads:s}}return{assignee:e.otherwise,matched:"otherwise",factReads:s}}function Lr(e,t,o){let n=t.nodes[o];if(!n||!("binding"in n))return["WORKFLOW_CONDITIONAL_HUMAN_REQUIRED"];let r=[];e.provider==="supervisor_chain"&&r.push(...At(t,{bindings:{[n.binding]:e}}));let i=[e.inputPath,e.departmentIdFrom,e.selectedInputPath,e.resourceIdFrom,e.scope?.valueFrom,...typeof e.from=="object"?[e.from.field]:[],...Object.values(e.routing?.dimensions||{}).map(s=>s.valueFrom),...Object.values(e.routing?.sources||{}).map(s=>s.scope?.valueFrom)].filter(s=>typeof s=="string");for(let s of i)so(t,o,s)||r.push(`WORKFLOW_CONDITIONAL_LEAF_FACT_UNAVAILABLE:${s}`);return[...new Set(r)]}var Cm=200,nl=["text.short","uuid","option.single","resource-ref.single"],vr=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,js=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Us=new Set(["__proto__","prototype","constructor"]),Pr=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),xs=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Qt=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,$t=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer};function me(e,t){throw new $t(e,t)}function lo(e,t,o){if(e===void 0)return;["user.single","user.multiple"].includes(t)||me("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",o),(!Pr(e)||!xs(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!Qt(e.roleCode,128)||!vr.test(String(e.roleCode)))&&me("DATA_USER_CANDIDATES_SOURCE_INVALID",o),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&me("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${o}/pageSize`);let n;if(e.scope!==void 0){let r=e.scope;(!Pr(r)||!xs(r,["dimensionCode","operation","field","value","creation"])||!Qt(r.dimensionCode,128)||!vr.test(String(r.dimensionCode))||!Qt(r.operation,64)||!vr.test(String(r.operation))||Object.hasOwn(r,"field")===Object.hasOwn(r,"value"))&&me("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope`),r.creation!==void 0&&(r.creation!=="prospective"||!Object.hasOwn(r,"field"))&&me("DATA_USER_CANDIDATES_SCOPE_INVALID",`${o}/scope/creation`),Object.hasOwn(r,"field")?((!Qt(r.field,63)||!js.test(String(r.field))||Us.has(String(r.field)))&&me("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${o}/scope/field`),n={dimensionCode:String(r.dimensionCode),operation:String(r.operation),field:String(r.field),...r.creation==="prospective"?{creation:"prospective"}:{}}):(Qt(r.value,255)||me("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${o}/scope/value`),n={dimensionCode:String(r.dimensionCode),operation:String(r.operation),value:String(r.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...n?{scope:n}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function $r(e){return e.some(t=>t.schema.fields.some(o=>{let n=o.userCandidates?.scope;return n?.creation==="prospective"||!!(n?.field&&t.schema.fields.find(r=>r.code===n.field)?.type==="resource-ref.single")}))}function Ms(e,t,o,n){for(let[r,i]of e.entries()){let s=`${n}/${r}/userCandidates`,a=lo(i.userCandidates,i.type,s);if(a&&(t.has(a.roleCode)||me("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${s}/roleCode`),a.scope&&!o.has(a.scope.dimensionCode)&&me("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${s}/scope/dimensionCode`),a.scope?.field)){let d=e.find(c=>c.code===a.scope.field);(!d||!nl.some(c=>c===d.type))&&me("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${s}/scope/field`)}}}function ol(e,t,o,n){let r=e.subject.factProjection,i=typeof t.inputPath=="string"&&Object.entries(r).some(([c,l])=>(t.inputPath===c||t.inputPath.startsWith(`${c}.`))&&o.get(l)?.userCandidates!==void 0);if(t.candidateField===void 0&&!i)return;(t.provider!=="form_field_users"||!t.candidateField||!js.test(t.candidateField)||Us.has(t.candidateField)||!t.inputPath||r[t.inputPath]!==t.candidateField)&&me("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",n),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&me("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",n);let s=o.get(t.candidateField),a=s&&lo(s.userCandidates,s.type,`${n}/candidateField`);a||me("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${n}/candidateField`);let d;if(a.scope?.field){let c=Object.entries(r).filter(([,l])=>l===a.scope.field).map(([l])=>l);c.length!==1&&me("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",n),d=c[0]}return{fieldCode:s.code,inputPath:t.inputPath,source:a,...d?{scopeInputPath:d}:{}}}function Bs(e,t,o,n,r=new Map){for(let[i,s]of Object.entries(co(t).bindings))ol(e,s,o,`${n}/${i}`);for(let[i,s]of Object.entries(e.taskPages||{})){let a=new Set(s.fields.filter(d=>d.readonly!==!0).map(d=>d.code));for(let d of s.fields){let c=o.get(d.code)?.userCandidates?.scope;if(a.has(d.code)&&c?.field&&a.has(c.field)&&me("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${n}/taskPages/${i}/${d.code}`),!a.has(d.code)||!d.subtable)continue;let l=o.get(d.code)?.subtable?.resourceCode,f=l?r.get(l):void 0;d.subtable.fields.some(p=>p.readonly!==!0&&f?.get(p.code)?.userCandidates)&&me("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${n}/taskPages/${i}/${d.code}`)}}}function Sm(e,t){if(!e.scope)return;let o=e.scope.field?t[e.scope.field]:e.scope.value,n=Pr(o)?o.value:o;return Qt(n,255)||me("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(n)}var uo=200,Vr=205;function Wr(e,t=[]){return e.some(o=>o.schema.fields.length>100)||t.some(o=>Object.values(o.definition.taskPages||{}).some(n=>(n.fields?.length??0)>64)||[o.launch?.submission?.create,o.launch?.submission?.existing].some(n=>Object.keys(n?.inputs||{}).length>64))}var lt=500,Fr=500,en=1e3,Ks=2*en+16,km=2*1024*1024,Lm=2*1024*1024;function On(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1&&e<=en}function fo(e){if(e.ownedRowLimit===void 0)return Fr;if(!On(e.ownedRowLimit))throw new Error("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID");return e.ownedRowLimit}function xr(e){return e.some(t=>(t.schema.ownedRowLimit??Fr)>Fr)}function jr(e){return e.some(t=>{let o=t.schema.fields.filter(n=>n.type==="subtable").map(n=>n.subtable?.maxRows??20);return o.some(n=>n>100)||o.reduce((n,r)=>n+r,0)>400})}function vm(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var Hs=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Br=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,rl=["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 Kr(e){return e.some(t=>t.schema.fields.some(o=>(o.type==="datetime"||o.type==="datetime-range")&&o.timePrecision==="minute"))}function qr(e){return e.some(t=>t.schema.fields.some(o=>o.type==="subtable"&&(o.subtable?.minRows??0)>0))}var il=new Set(rl),Ys=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),qs=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),zs=new Set(["resource-ref.single","resource-ref.multiple"]),zr=[{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}],tn=new Map(zr.map(e=>[e.code,e])),We=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataFieldContractV2Error"}code;pointer};function go(e){return Ys.has(e)}function Et(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!go(e.type)||t.requiredHint===!0)}function bn(e,t,o=500){Array.isArray(e)||L("NATIVE_ARRAY_REQUIRED",t),e.length===0&&L("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>o&&L("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=new Set;return e.map((r,i)=>{let s=`${t}/${i}`,a=xe(r,s);qe(a,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],s);let d=ze(a.code,`${s}/code`,63);Hs.test(d)||L("NATIVE_FIELD_CODE_INVALID",`${s}/code`),n.has(d)&&L("NATIVE_DATA_FIELD_DUPLICATE",`${s}/code`),n.add(d);let c=ze(a.type,`${s}/type`,32);il.has(c)||L("NATIVE_DATA_FIELD_TYPE_INVALID",`${s}/type`);let l=c,f=Mr(a.nullable,`${s}/nullable`),p=Mr(a.indexed,`${s}/indexed`);f===!0&&Ys.has(l)&&L("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${s}/nullable`);let m=dl(a.options,l,s),A=cl(a.source,l,s),I=lo(a.userCandidates,l,`${s}/userCandidates`),O=ll(a,l,s),b=Mr(a.exactDecimal,`${s}/exactDecimal`);b!==void 0&&l!=="number.decimal"&&L("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${s}/exactDecimal`);let g=sl(a.rangeBoundary,l,s),y=ul(a.file,l,s),h=fl(a.serial,l,s),u=pl(a.subtable,l,s);return{code:d,type:l,...f===void 0?{}:{nullable:f},...p===void 0?{}:{indexed:p},...m?{options:m}:{},...A?{source:A}:{},...I?{userCandidates:I}:{},...O,...b===void 0?{}:{exactDecimal:b},...g?{rangeBoundary:g}:{},...y?{file:y}:{},...h?{serial:h}:{},...u?{subtable:u}:{}}})}function sl(e,t,o){let n=`${o}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&L("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",n);return}return e!=="closed"&&e!=="half-open"&&L("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",n),e}function Xs(e,t){Array.isArray(e)||L("NATIVE_ARRAY_REQUIRED",t);let o=new Map;e.forEach((n,r)=>{let i=`${t}/${r}`,s=xe(n,i),a=ze(s.code,`${i}/code`,64);(!Br.test(a)||o.has(a))&&L("NATIVE_RESOURCE_CODE_INVALID",`${i}/code`);let d=xe(s.schema,`${i}/schema`);d.ownedRowLimit!==void 0&&!On(d.ownedRowLimit)&&L("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${i}/schema/ownedRowLimit`),o.set(a,{pointer:i,ownedRowLimit:fo(d),fields:bn(d.fields,`${i}/schema/fields`)})});for(let[n,r]of o){let i=new Map(r.fields.map(a=>[a.code,a]));r.fields.filter(a=>a.type==="subtable").reduce((a,d)=>a+(d.subtable?.maxRows??20),0)>r.ownedRowLimit&&L("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${r.pointer}/schema/fields`),r.fields.forEach((a,d)=>{let c=`${r.pointer}/schema/fields/${d}`;if(a.source&&al(a.source,i,o,`${c}/source`),a.subtable){let l=o.get(a.subtable.resourceCode);(!l||a.subtable.resourceCode===n)&&L("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${c}/subtable/resourceCode`);let f=l.fields.find(m=>m.code===a.subtable?.foreignKey);(!f||f.type!=="uuid"||f.nullable!==!1)&&L("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${c}/subtable/foreignKey`);let p=l.fields.find(m=>m.code===a.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&L("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${c}/subtable/orderField`)}})}}function Zs(e,t,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&L("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",o);let n=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,s)=>{let a=`${o}/${s}`,d=xe(i,a);qe(d,["code","message","expression"],a);let c=ze(d.code,`${a}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(c)||r.has(c))&&L("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${a}/code`),r.add(c);let l=mo(d.message,`${a}/message`,500);l!==void 0&&l.length===0&&L("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${a}/message`);let f=xe(d.expression,`${a}/expression`);if(f.kind==="nonBlankTextWhenOption"){qe(f,["kind","optionField","optionValue","textField"],`${a}/expression`);let g=Qe(f.optionField,`${a}/expression/optionField`),y=Qe(f.textField,`${a}/expression/textField`),h=ze(f.optionValue,`${a}/expression/optionValue`,128),u=n.get(g),E=n.get(y);return(!u||!E)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${a}/expression`),(u.type!=="option.single"||!["text.short","text.long"].includes(E.type)||!u.options?.some(w=>w.value===h))&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${a}/expression`),{code:c,...l===void 0?{}:{message:l},expression:{kind:"nonBlankTextWhenOption",optionField:g,optionValue:h,textField:y}}}qe(f,["leftField","operator","rightField"],`${a}/expression`);let p=Qe(f.leftField,`${a}/expression/leftField`),m=Qe(f.rightField,`${a}/expression/rightField`),A=n.get(p),I=n.get(m);(!A||!I)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${a}/expression`),A.type===I.type||["number.integer","number.decimal"].includes(A.type)&&["number.integer","number.decimal"].includes(I.type)||L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${a}/expression`);let b=String(f.operator);return["eq","neq","gt","gte","lt","lte"].includes(b)||L("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${a}/expression/operator`),!["eq","neq"].includes(b)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(A.type)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${a}/expression`),{code:c,...l===void 0?{}:{message:l},expression:{leftField:p,operator:b,rightField:m}}})}function al(e,t,o,n){let r=o.get(e.resourceCode);r||L("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${n}/resourceCode`);let i=new Map(r.fields.map(a=>[a.code,a])),s=i.get(e.labelField);(!s||!["text.short","text.long"].includes(s.type))&&L("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${n}/labelField`);for(let a of["searchFields","descriptionFields","snapshotFields"])for(let d of e[a]||[])i.has(d)||L("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${n}/${a}`);for(let[a,d]of(e.filterWhere||[]).entries())i.has(d.field)||L("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filterWhere/${a}/field`);for(let[a,d]of(e.filters||[]).entries())i.has(d.field)||L("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${n}/filters/${a}/field`),"binding"in d&&!t.has(d.binding.field)&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${n}/filters/${a}/binding/field`)}function dl(e,t,o){let n=`${o}/options`;if(e===void 0){qs.has(t)&&L("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",n);return}(!qs.has(t)||!Array.isArray(e))&&L("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",n),(e.length<1||e.length>100)&&L("NATIVE_DATA_FIELD_OPTIONS_INVALID",n);let r=0,i=(s,a,d)=>{d>5&&L("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",a);let c=new Set;return s.map((l,f)=>{r+=1,r>1e3&&L("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",n);let p=`${a}/${f}`,m=xe(l,p);qe(m,["label","value","description","color","children"],p);let A=ze(m.label,`${p}/label`,500),I=ze(m.value,`${p}/value`,500);c.has(I)&&L("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),c.add(I);let O=mo(m.description,`${p}/description`,2e3),b=mo(m.color,`${p}/color`,64),g;return m.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(m.children))&&L("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(m.children.length<1||m.children.length>100)&&L("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),g=i(m.children,`${p}/children`,d+1)),{label:A,value:I,...O===void 0?{}:{description:O},...b===void 0?{}:{color:b},...g?{children:g}:{}}})};return i(e,n,1)}function cl(e,t,o){let n=`${o}/source`;if(e===void 0){zs.has(t)&&L("NATIVE_DATA_FIELD_SOURCE_REQUIRED",n);return}zs.has(t)||L("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",n);let r=xe(e,n);qe(r,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","filterWhere","pageSize","loadMode","clearOnBindingChange"],n),r.kind!=="resource"&&L("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${n}/kind`);let i=ze(r.resourceCode,`${n}/resourceCode`,64);Br.test(i)||L("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let s=Qe(r.labelField,`${n}/labelField`),a=Ur(r.searchFields,`${n}/searchFields`,10),d=Ur(r.descriptionFields,`${n}/descriptionFields`,10),c=Ur(r.snapshotFields,`${n}/snapshotFields`,50),l=Ft(r.pageSize,`${n}/pageSize`,1,100),f;r.loadMode!==void 0&&(["search","all"].includes(String(r.loadMode))||L("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${n}/loadMode`),f=r.loadMode);let p=Gs(r.filters,`${n}/filters`),m=Gs(r.filterWhere,`${n}/filterWhere`,!1);return r.clearOnBindingChange!==void 0&&typeof r.clearOnBindingChange!="boolean"&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${n}/clearOnBindingChange`),{kind:"resource",resourceCode:i,labelField:s,...a?{searchFields:a}:{},...d?{descriptionFields:d}:{},...c?{snapshotFields:c}:{},...p?{filters:p}:{},...m?{filterWhere:m}:{},...l===void 0?{}:{pageSize:l},...f?{loadMode:f}:{},...r.clearOnBindingChange===void 0?{}:{clearOnBindingChange:r.clearOnBindingChange}}}function Gs(e,t,o=!0){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&L("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((n,r)=>{let i=`${t}/${r}`,s=xe(n,i),a=Object.prototype.hasOwnProperty.call(s,"value"),d=Object.prototype.hasOwnProperty.call(s,"binding");qe(s,a?["field","operator","value"]:["field","operator","binding"],i),(a===d||d&&!o)&&L("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let c=Qe(s.field,`${i}/field`);["eq","in"].includes(String(s.operator))||L("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let l=s.operator;if(a)return{field:c,operator:l,value:s.value};let f=xe(s.binding,`${i}/binding`);return qe(f,["kind","field"],`${i}/binding`),f.kind!=="field"&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:c,operator:l,binding:{kind:"field",field:Qe(f.field,`${i}/binding/field`)}}})}function ll(e,t,o){let n={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||L("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${o}/maxLength`),n.maxLength=po(e.maxLength,`${o}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&L("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",o),n.precision=po(e.precision,`${o}/precision`,1,1e3),n.scale=e.scale===void 0?0:po(e.scale,`${o}/scale`,0,n.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",o);let r=Js(e.min,`${o}/min`),i=Js(e.max,`${o}/max`);t==="number.integer"&&[r,i].some(s=>s!==void 0&&!Number.isSafeInteger(s))&&L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),r!==void 0&&i!==void 0&&r>i&&L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",o),r!==void 0&&(n.min=r),i!==void 0&&(n.max=i)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&L("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${o}/timePrecision`),n.timePrecision=e.timePrecision),n}function ul(e,t,o){if(e===void 0)return;let n=`${o}/file`;["file","image","signature"].includes(t)||L("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",n);let r=xe(e,n);qe(r,["maxCount","maxSizeMb","accept"],n);let i=Ft(r.maxCount,`${n}/maxCount`,1,100);t==="signature"&&i!==void 0&&i!==1&&L("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${n}/maxCount`);let s=Ft(r.maxSizeMb,`${n}/maxSizeMb`,1,1024),a;return r.accept!==void 0&&((!Array.isArray(r.accept)||r.accept.length>50)&&L("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`),a=r.accept.map((d,c)=>ze(d,`${n}/accept/${c}`,255)),new Set(a).size!==a.length&&L("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${n}/accept`)),{...i===void 0?{}:{maxCount:i},...s===void 0?{}:{maxSizeMb:s},...a===void 0?{}:{accept:a}}}function fl(e,t,o){let n=`${o}/serial`;if(e===void 0){t==="serial-number"&&L("NATIVE_DATA_FIELD_SERIAL_REQUIRED",n);return}t!=="serial-number"&&L("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",n);let r=xe(e,n);qe(r,["prefix","digits","start"],n);let i=mo(r.prefix,`${n}/prefix`,64),s=Ft(r.digits,`${n}/digits`,1,32),a=Ft(r.start,`${n}/start`,0,Number.MAX_SAFE_INTEGER);return{...i===void 0?{}:{prefix:i},...s===void 0?{}:{digits:s},...a===void 0?{}:{start:a}}}function pl(e,t,o){let n=`${o}/subtable`;if(e===void 0){t==="subtable"&&L("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",n);return}t!=="subtable"&&L("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",n);let r=xe(e,n);qe(r,["resourceCode","foreignKey","orderField","minRows","maxRows"],n);let i=ze(r.resourceCode,`${n}/resourceCode`,64);Br.test(i)||L("NATIVE_RESOURCE_CODE_INVALID",`${n}/resourceCode`);let s=Qe(r.foreignKey,`${n}/foreignKey`),a=Qe(r.orderField,`${n}/orderField`);a===s&&L("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${n}/orderField`);let d=Ft(r.maxRows,`${n}/maxRows`,1,lt),c=Ft(r.minRows,`${n}/minRows`,0,lt);return(c??0)>(d??20)&&L("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${n}/minRows`),{resourceCode:i,foreignKey:s,orderField:a,...c===void 0?{}:{minRows:c},...d===void 0?{}:{maxRows:d}}}function Ur(e,t,o){if(e===void 0)return;(!Array.isArray(e)||e.length>o)&&L("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let n=e.map((r,i)=>Qe(r,`${t}/${i}`));return new Set(n).size!==n.length&&L("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),n}function Qe(e,t){let o=ze(e,t,63);return Hs.test(o)||L("NATIVE_FIELD_CODE_INVALID",t),o}function xe(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&L("NATIVE_OBJECT_REQUIRED",t),e}function qe(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||L("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function ze(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&L("NATIVE_STRING_INVALID",t),e}function mo(e,t,o){if(e!==void 0)return(typeof e!="string"||e.length>o)&&L("NATIVE_STRING_INVALID",t),e}function Mr(e,t){if(e!==void 0)return typeof e!="boolean"&&L("NATIVE_BOOLEAN_REQUIRED",t),e}function Ft(e,t,o,n){if(e!==void 0)return po(e,t,o,n)}function Js(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&L("NATIVE_NUMBER_REQUIRED",t),e}function po(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&L("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function L(e,t){throw new We(e,t)}var _o=["created_by","updated_by","created_at","updated_at"];function Vt(e){return _o.includes(e)}function Qs(e){return _o.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var ml=zr.map(e=>e.code);function Ao(e){return ml.includes(e)}var gl=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],_l=new Set(gl);function jm(e){return _l.has(String(e))}var Gr=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],hn=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Al=["eq","neq","in","isEmpty"],Eo=["eq","neq","in","isEmpty","isNotEmpty"],nn=["has","hasAny","hasAll","isEmpty","isNotEmpty"],ea=["overlaps","contains","containedBy","isEmpty"],Jr=["jsonContains","isEmpty","isNotEmpty"],Hr=["isEmpty","isNotEmpty"],El={"text.short":Gr,"text.long":Gr,"text.rich":Gr,"number.integer":hn,"number.decimal":hn,boolean:Al,date:hn,time:hn,datetime:hn,"date-range":ea,"datetime-range":ea,"option.single":Eo,"option.multiple":nn,"cascade.single":nn,"cascade.multiple":nn,"user.single":Eo,"user.multiple":nn,"department.single":Eo,"department.multiple":nn,"resource-ref.single":Eo,"resource-ref.multiple":nn,file:Hr,image:Hr,signature:Hr,address:Jr,location:Jr,uuid:["eq","neq","in","isEmpty"],json:Jr,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},Il=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),yl=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function na(e){return El[e]}function Um(e,t){return na(e).includes(t)}function Yr(e){return Il.has(e)}function Nn(e){return!yl.has(e)}function oa(e){return na(e).length>0}var ta=new Set(["number.integer","number.decimal"]),ra=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),Ol=new Set([...ra,"boolean","uuid"]),bl=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Mm(e,t){return t==="sum"||t==="avg"?ta.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?ra.has(e)?{valueExpression:"column",numericResult:ta.has(e)}:null:bl.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:Ol.has(e)?{valueExpression:"column",numericResult:!0}:null}var Zr=["version","maxBytes","fields"];function sa(e,t){if(e===void 0)return;let o=Xr(e,t);ia(o,Zr,t);let n=Io(o.version,`${t}/version`,1,1e6),r=Io(o.maxBytes,`${t}/maxBytes`,2,196608);(!n||!r)&&we("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let i=Xr(o.fields,`${t}/fields`),s=Object.entries(i);(!s.length||s.length>50)&&we("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[a,d]of s){let c=`${t}/fields/${a}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||we("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",c);let l=Xr(d,c),f=aa(l.type,`${c}/type`,32),p=f==="string"?["type","required","maxLength","enum"]:f==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(f)||we("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${c}/type`),ia(l,p,c),Nl(l.required,`${c}/required`),f==="string"){let m=Io(l.maxLength,`${c}/maxLength`,1,196608);m||we("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c),l.enum!==void 0&&hl(l.enum,`${c}/enum`,100,!1).some(I=>I.length>m)&&we("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${c}/enum`)}else if(f==="json.object"){let m=Io(l.maxBytes,`${c}/maxBytes`,2,65536);(!m||m>r)&&we("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c)}}}function hl(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&we("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,s)=>aa(i,`${t}/${s}`,255));return new Set(r).size!==r.length&&we("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function Xr(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&we("NATIVE_OBJECT_REQUIRED",t),e}function ia(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||we("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function aa(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&we("NATIVE_STRING_INVALID",t),e}function Nl(e,t){e!==void 0&&typeof e!="boolean"&&we("NATIVE_BOOLEAN_REQUIRED",t)}function Io(e,t,o,n){return(!Number.isSafeInteger(e)||Number(e)<o||Number(e)>n)&&we("NATIVE_INTEGER_INVALID",t),Number(e)}function we(e,t){throw new We(e,t)}var wl=500,It={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:Zr,mobile:["enabled"]},Rl={"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 ti(e,t,o){if(e===void 0)return;let n=be(e,o);et(n,It.surface,o);let r=n.mutationOwner===void 0?"native":ut(n.mutationOwner,`${o}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(r)||j("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${o}/mutationOwner`);let i=n.generated===void 0?{}:be(n.generated,`${o}/generated`);et(i,It.generated,`${o}/generated`);for(let d of It.generated)ei(i[d],`${o}/generated/${d}`);if(r!=="native")for(let d of["create","update","delete"])i[d]===!0&&j("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${o}/generated/${d}`);let s=new Map(t.map(d=>[d.code,d])),a=be(n.fields,`${o}/fields`);for(let d of Object.keys(a))s.has(d)||j("NATIVE_DATA_SURFACE_FIELD_MISSING",`${o}/fields/${d}`);for(let d of t)Object.prototype.hasOwnProperty.call(a,d.code)||j("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${o}/fields/${d.code}`),Cl(a[d.code],d,`${o}/fields/${d.code}`);for(let d of["create","update"]){let c=i[d]??r==="native",l=t.some(f=>{let p=be(a[f.code],`${o}/fields/${f.code}`);return ca(f,p,d)});c&&!l&&j("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${o}/generated/${d}`)}if(Sl(n.list,s,`${o}/list`),da(n.form,s,`${o}/form`,"form"),da(n.detail,s,`${o}/detail`,"detail"),n.mobile!==void 0){let d=be(n.mobile,`${o}/mobile`);et(d,It.mobile,`${o}/mobile`),ei(d.enabled,`${o}/mobile/enabled`)}Tl(n,t,o)}function ni(e,t){let o=e.views?.find(r=>r.code===t);o||j("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let n=new Map((o.sections||[]).flatMap(r=>r.fields.map(i=>[i,r.title])));return{mutationOwner:e.mutationOwner||"native",generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([r,i])=>{let s={...i};delete s.section;let a=n.get(r);return[r,{...s,...a?{section:a}:{},list:o.list.fieldOrder.includes(r)}]}))}}function Tl(e,t,o){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&j("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${o}/views`);let n=new Set;e.views.forEach((r,i)=>{let s=`${o}/views/${i}`,a=be(r,s);et(a,["code","name","generated","list","form","detail","mobile","sections"],s);let d=ut(a.code,`${s}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(d)||n.has(d))&&j("NATIVE_DATA_VIEW_CODE_INVALID",`${s}/code`),n.add(d),ut(a.name,`${s}/name`,255),be(a.generated,`${s}/generated`),be(a.mobile,`${s}/mobile`);for(let l of["list","detail","create","update","delete"])typeof a.generated[l]!="boolean"&&j("NATIVE_DATA_VIEW_OPERATION_INVALID",`${s}/generated/${l}`);typeof a.mobile.enabled!="boolean"&&j("NATIVE_DATA_VIEW_MOBILE_INVALID",`${s}/mobile/enabled`);for(let l of["list","form","detail"]){let f=be(a[l],`${s}/${l}`),p=on(f.fieldOrder,`${s}/${l}/fieldOrder`,500,!0);for(let m of p){let A=e.fields[m];(!A||(A.hidden??A.system)===!0)&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${s}/${l}/fieldOrder`)}}if(a.sections!==void 0){(!Array.isArray(a.sections)||a.sections.length>100)&&j("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${s}/sections`);let l=new Set;a.sections.forEach((f,p)=>{let m=`${s}/sections/${p}`,A=be(f,m);et(A,["title","fields"],m),ut(A.title,`${m}/title`,255);for(let I of on(A.fields,`${m}/fields`,100,!0)){let O=e.fields[I];(!O||(O.hidden??O.system)===!0||l.has(I))&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${m}/fields`),l.add(I)}})}let c=ni(e,d);if(ti(c,t,s),a.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let l of t)Et(l,e.fields[l.code])&&ca(l,e.fields[l.code],"create")&&!a.form.fieldOrder.includes(l.code)&&j("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${s}/form/fieldOrder`)})}function ca(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 Cl(e,t,o){let n=be(e,o);et(n,It.field,o),ut(n.label,`${o}/label`,500),n.type!==t.type&&j("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${o}/type`);let r=ut(n.widget,`${o}/widget`,64);Rl[t.type].includes(r)||j("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${o}/widget`),Ll(n.section,`${o}/section`,255);for(let i of["requiredHint","system","hidden","list","searchable","sortable"])ei(n[i],`${o}/${i}`);n.searchable===!0&&!Yr(t.type)&&j("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${o}/searchable`),n.sortable===!0&&!Nn(t.type)&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/sortable`);for(let i of["readCapabilities","createCapabilities","updateCapabilities"])on(n[i],`${o}/${i}`,100,!0);if(n.maxCount!==void 0&&(!Number.isSafeInteger(n.maxCount)||Number(n.maxCount)<1||Number(n.maxCount)>100)&&j("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${o}/maxCount`),n.maxSizeMb!==void 0&&(!Number.isSafeInteger(n.maxSizeMb)||Number(n.maxSizeMb)<1||Number(n.maxSizeMb)>1024)&&j("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${o}/maxSizeMb`),n.accept!==void 0){let i=Array.isArray(n.accept)?n.accept:[n.accept];on(i,`${o}/accept`,50,!1)}for(let i of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])Dl(n,t,i,o);kl(n,t,o)}function Sl(e,t,o){if(e===void 0)return;let n=be(e,o);if(et(n,It.list,o),n.actions!==void 0){let r=be(n.actions,`${o}/actions`);et(r,["import","export"],`${o}/actions`);for(let i of["import","export"])r[i]!==void 0&&typeof r[i]!="boolean"&&j("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${o}/actions/${i}`)}if(n.fieldOrder!==void 0)for(let r of on(n.fieldOrder,`${o}/fieldOrder`,500,!0))t.has(r)||j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/fieldOrder`);n.defaultPageSize!==void 0&&(!Number.isSafeInteger(n.defaultPageSize)||Number(n.defaultPageSize)<1||Number(n.defaultPageSize)>200)&&j("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${o}/defaultPageSize`);for(let[r,i]of[["searchableFields",Yr],["filterFields",oa]]){if(n[r]===void 0)continue;let s=on(n[r],`${o}/${r}`,100,!0);for(let a of s){let d=t.get(a);(!d||!i(d.type))&&j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${o}/${r}`)}}if(n.defaultSort!==void 0){let r=be(n.defaultSort,`${o}/defaultSort`);et(r,It.defaultSort,`${o}/defaultSort`);let i=ut(r.field,`${o}/defaultSort/field`,63),s=t.get(i);!Ao(i)&&(!s||!Nn(s.type))&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${o}/defaultSort/field`),r.order!==void 0&&!["asc","desc"].includes(r.order)&&j("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${o}/defaultSort/order`)}}function da(e,t,o,n){if(e===void 0)return;let r=be(e,o);if(et(r,It[n],o),r.layout!==void 0&&!["flat","sections"].includes(r.layout)&&j("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${o}/layout`),r.fieldOrder!==void 0){let i=`${o}/fieldOrder`;(!Array.isArray(r.fieldOrder)||r.fieldOrder.length>t.size||r.fieldOrder.length>wl)&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i);let s=r.fieldOrder.map((a,d)=>ut(a,`${i}/${d}`,63));new Set(s).size!==s.length&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i),s.forEach((a,d)=>{t.has(a)||j("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${i}/${d}`)})}n==="form"&&sa(r.draftState,`${o}/draftState`)}function Dl(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}`),re(e[o])!==re(t[o])&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${o}`))}function kl(e,t,o){let n=t.file||{},r={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:Qr(e.accept)}};for(let i of["maxCount","maxSizeMb","accept"]){if(r[i]===void 0&&n[i]===void 0)continue;(r[i]===void 0||n[i]===void 0)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`);let s=i==="accept"?Qr(r[i]):r[i],a=i==="accept"?Qr(n[i]):n[i];re(s)!==re(a)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${i}`)}}function Qr(e){return(Array.isArray(e)?[...e]:[e]).sort((t,o)=>{let n=String(t),r=String(o);return n===r?0:n<r?-1:1})}function on(e,t,o,n){(!Array.isArray(e)||!n&&e.length===0||e.length>o)&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,s)=>ut(i,`${t}/${s}`,255));return new Set(r).size!==r.length&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function be(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&j("NATIVE_OBJECT_REQUIRED",t),e}function et(e,t,o){let n=new Set(t);for(let r of Object.keys(e))n.has(r)||j("NATIVE_PROPERTY_UNKNOWN",`${o}/${r}`)}function ut(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&j("NATIVE_STRING_INVALID",t),e}function Ll(e,t,o){e!==void 0&&(typeof e!="string"||e.length>o)&&j("NATIVE_STRING_INVALID",t)}function ei(e,t){e!==void 0&&typeof e!="boolean"&&j("NATIVE_BOOLEAN_REQUIRED",t)}function j(e,t){throw new We(e,t)}var wn=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.pointer=o;this.reason=n}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function la(e,t,o){if(e===void 0)return;let n=(g,y)=>{throw new wn(g,y)},r=(g,y,h)=>((!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).some(u=>!h.includes(u)))&&n(y,"object contains unsupported properties"),g),i=(g,y,h,u)=>{(!Number.isSafeInteger(g)||g<y||g>h)&&n(u,`expected integer ${y}..${h}`)},s=(g,y)=>{(typeof g!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(g))&&n(y,"invalid code")},a=(g,y,h)=>((!Array.isArray(g)||g.length>y)&&n(h,"array exceeds bound"),g),d=(g,y)=>{let h=t.find(u=>u.code===g);return h||n(y,"unknown resource"),h},c=(g,y,h)=>{let u=g.schema.fields.find(E=>E.code===y);return!u&&y!=="id"&&n(h,"unknown field"),u},l=(g,y,h=!1)=>{r(g,y,Object.keys(g||{})),Object.keys(g).length>8&&n(y,"at most eight parameters");for(let[u,E]of Object.entries(g))if(s(u,y),r(E,y,["type","values","minimum","maximum","minLength","maxLength"]),E.type==="uuid")Object.keys(E).length!==1&&n(y,"uuid has no options");else if(h&&E.type==="boolean")r(E,y,["type"]);else if(h&&E.type==="string"&&E.values===void 0)r(E,y,["type","minLength","maxLength"]),i(E.maxLength,1,256,y),E.minLength!==void 0&&i(E.minLength,0,E.maxLength,y);else if(E.type==="string"){r(E,y,["type","values"]);let w=a(E.values,100,y);(!w.length||w.some(S=>typeof S!="string"||S.length>128)||new Set(w).size!==w.length)&&n(y,"finite string values required")}else E.type==="integer"?(r(E,y,["type","minimum","maximum"]),i(E.minimum,0,1e6,y),i(E.maximum,E.minimum,E.minimum+1e3,y)):n(y,"unsupported parameter type")},f=(g,y,h,u=!1)=>{r(g,h,["from","key","value"]),!(g.from==="input"&&Object.keys(g).length===2&&Object.hasOwn(y,g.key))&&((g.from==="actor"||u&&g.from==="allocation")&&Object.keys(g).length===1||g.from==="literal"&&Object.keys(g).length===2&&Object.hasOwn(g,"value")&&(g.value===null||["string","boolean"].includes(typeof g.value)||typeof g.value=="number"&&Number.isFinite(g.value))&&JSON.stringify(g.value).length<=512||n(h,"invalid binding"))},p=(g,y,h)=>{f(g,y,h),!(g.from==="input"&&y[g.key].type==="uuid")&&(g.from==="literal"&&typeof g.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g.value)||n(h,"record and allocation identifiers require a UUID binding"))},m=(g,y,h)=>{f(g,y,h),!(g.from==="input"&&y[g.key].type==="integer"&&y[g.key].minimum>=1)&&(g.from==="literal"&&Number.isSafeInteger(g.value)&&g.value>=1||n(h,"expectedRevision requires a positive integer binding"))},A="/data/concurrency";JSON.stringify(e).length>131072&&n(A,"declaration exceeds 128 KiB");let I=r(e,A,["version","admission","reads","quotas","commands"]);I.version!==1&&n(A,"unsupported version"),r(I.admission,A,["perSecond","burst","maxInFlight"]),i(I.admission.perSecond,1,1e3,A),i(I.admission.burst,1,1e3,A),i(I.admission.maxInFlight,1,1e3,A);let O=(g,y)=>{let h=new Set;for(let u of g)s(u?.code,y),h.has(u.code)&&n(y,"duplicate code"),h.add(u.code)};O(a(I.reads,32,A),A),O(a(I.quotas,16,A),A),O(a(I.commands,32,A),A);for(let g of I.reads){let y=`${A}/reads/${g.code}`;r(g,y,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let h=d(g.resourceCode,y);l(g.parameters,y),["subject","application"].includes(g.scope)||n(y,"invalid cache scope"),g.scope==="application"&&h.dataPolicyCode&&n(y,"shared cache cannot bypass a row policy");let u=a(g.select,32,y);u.length||n(y,"select required"),u.forEach(w=>c(h,w,y));let E=a(g.dependencies,64,y);E.forEach(w=>c(h,w,y));for(let w of a(g.where||[],8,y))r(w,y,["field","value"]),c(h,w.field,y),f(w.value,g.parameters,y),g.scope==="application"&&w.value.from==="actor"&&n(y,"actor requires subject cache"),E.includes(w.field)||n(y,"filter dependency missing");u.some(w=>!E.includes(w))&&n(y,"selected field dependency missing"),i(g.limit,1,100,y),i(g.freshSeconds,1,300,y),i(g.staleSeconds,0,300,y),i(g.maxKeys,1,1e4,y),i(g.sourcePerSecond,1,20,y)}for(let g of I.quotas){let y=`${A}/quotas/${g.code}`;r(g,y,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let h=d(g.sourceResource,y),u=d(g.allocationResource,y);c(h,g.capacityField,y)?.type!=="number.integer"&&n(y,"capacity must be an integer"),(c(u,g.allocationField,y)?.type!=="uuid"||c(u,g.allocationField,y)?.nullable!==!1)&&n(y,"allocation reference must be a uuid"),u.surface?.mutationOwner!=="queued-command"&&n(y,"allocation model must be command owned"),g.reservationSeconds!==void 0&&i(g.reservationSeconds,10,86400,y)}new Set(I.quotas.map(g=>g.allocationResource)).size!==I.quotas.length&&n(A,"an allocation model has exactly one pool owner");for(let g of I.commands){let y=`${A}/commands/${g.code}`;r(g,y,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),g.mode!==void 0&&!["permit","durable"].includes(g.mode)&&n(y,"unsupported mode");let h=g.mode==="durable";if(l(g.parameters,y,h),f(g.resourceKey,g.parameters,y),o.some(u=>u.code===g.capability)||n(y,"command capability must be declared"),r(g.admission,y,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),i(g.admission.perSecond,1,I.admission.perSecond,y),i(g.admission.burst,1,I.admission.burst,y),i(g.admission.maxInFlight,1,I.admission.maxInFlight,y),i(g.admission.maxQueue,1,1e4,y),i(g.admission.maxWaitSeconds,1,3600,y),(!h||g.admission.permitSeconds!==void 0)&&i(g.admission.permitSeconds,5,60,y),i(g.deadlineSeconds,10,3600,y),h){(g.operations!==void 0||g.guards!==void 0||g.quota!==void 0)&&n(y,"backend-plan does not accept static operations, guards or quota"),r(g.intake,y,["perSecond","burst","maxInFlight"]);for(let w of["perSecond","burst","maxInFlight"])i(g.intake[w],1,1e3,y);let u=r(g.execution,y,["kind","handlerCode","timeoutMs","resources","directory"]);u.kind!=="backend-plan"&&n(y,"durable requires backend-plan"),s(u.handlerCode,y),i(u.timeoutMs,100,3e4,y);let E=a(u.resources,32,y);E.length||n(y,"execution resources required"),new Set(E.map(w=>w.resourceCode)).size!==E.length&&n(y,"duplicate execution resource");for(let w of E){r(w,y,["resourceCode","readFields","writeOperations","writeFields"]);let S=d(w.resourceCode,y);for(let C of["readFields","writeFields"]){let v=a(w[C],64,y);new Set(v).size!==v.length&&n(y,"duplicate field"),v.forEach(P=>{C==="readFields"&&tn.has(P)||c(S,P,y)})}let T=a(w.writeOperations,3,y);(new Set(T).size!==T.length||T.some(C=>!["create","update","increment"].includes(C)))&&n(y,"unsupported execution operation"),w.writeFields.some(C=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(C))&&n(y,"record metadata is platform owned"),!T.length&&w.writeFields.length&&n(y,"write fields require an operation"),T.length&&!w.writeFields.length&&n(y,"write operations require fields"),I.quotas.some(C=>C.allocationResource===w.resourceCode)&&T.length&&n(y,"allocation references remain owned by their pool command")}if(u.directory!==void 0){r(u.directory,y,["mode","fields"]),u.directory.mode!=="current-initiator"&&n(y,"only current initiator allowed");let w=a(u.directory.fields,5,y);(!w.length||new Set(w).size!==w.length||w.some(S=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(S)))&&n(y,"unsupported directory fields")}continue}(g.execution!==void 0||g.intake!==void 0)&&n(y,"execution and intake require durable mode");for(let u of a(g.guards||[],8,y)){r(u,y,["resourceCode","id","conditions"]);let E=d(u.resourceCode,y);p(u.id,g.parameters,y);for(let w of a(u.conditions,16,y)){r(w,y,["kind","field","operator","value"]);let S=c(E,w.field,y);["eq","neq","lt","lte","gt","gte"].includes(w.operator)||n(y,"unsupported guard"),w.kind==="database-now"?(S?.type!=="datetime"||!["lt","lte","gt","gte"].includes(w.operator)||w.value!==void 0)&&n(y,"database-now requires datetime and an ordering operator"):(w.kind!==void 0&&w.kind!=="value"&&n(y,"unsupported condition kind"),f(w.value,g.parameters,y))}}for(let u of a(g.operations,8,y)){r(u,y,["operation","resourceCode","id","expectedRevision","data"]);let E=d(u.resourceCode,y);E.surface?.mutationOwner!=="queued-command"&&n(y,"command mutations require command owned models");let w=I.quotas.find(S=>S.allocationResource===u.resourceCode);w&&(u.operation==="create"?g.quota?.action!=="allocate"||g.quota.pool!==w.code:Object.hasOwn(u.data||{},w.allocationField))&&n(y,"allocation references are owned by their pool command"),["create","update"].includes(u.operation)||n(y,"unsupported operation"),u.operation==="update"?(p(u.id,g.parameters,y),m(u.expectedRevision,g.parameters,y)):(u.id!==void 0||u.expectedRevision!==void 0)&&n(y,"create has no caller supplied id/revision"),r(u.data,y,Object.keys(u.data||{})),Object.keys(u.data).length>32&&n(y,"too many fields");for(let[S,T]of Object.entries(u.data))S==="id"&&n(y,"record identifiers are platform owned"),c(E,S,y),f(T,g.parameters,y,g.quota?.action==="allocate")}if(g.quota){let u=r(g.quota,y,["pool","action","units","mode","allocation"]),E=I.quotas.find(w=>w.code===u.pool);E||n(y,"unknown quota pool"),p(g.resourceKey,g.parameters,y),u.action==="allocate"?(r(u,y,["pool","action","units","mode"]),i(u.units,1,1e3,y),(!["committed","reserved"].includes(u.mode)||u.mode==="reserved"&&!E.reservationSeconds)&&n(y,"invalid allocation mode"),(g.operations.length!==1||g.operations[0].operation!=="create"||g.operations[0].resourceCode!==E.allocationResource||g.operations[0].data[E.allocationField]?.from!=="allocation")&&n(y,"allocation must atomically create its bound business record")):["confirm","release"].includes(u.action)?(r(u,y,["pool","action","allocation"]),p(u.allocation,g.parameters,y),g.operations.length&&n(y,"lifecycle owns allocation state; business reference remains immutable")):n(y,"invalid quota action")}else g.operations.length||n(y,"operations required")}let b=I.commands.filter(g=>g.mode==="durable").map(g=>g.execution.handlerCode);return new Set(b).size!==b.length&&n(A,"handler code must be unique"),JSON.parse(JSON.stringify(I))}var rn=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"},ii=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],ua=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Oo=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),yo=e=>Array.isArray(e)?e.filter(Oo):[],tt=(e,t)=>{throw new rn(e,t)},oi=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),ri=(e,t)=>e<t?-1:e>t?1:0;function si(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Oo(e)||Object.keys(e).some(r=>!ii.includes(r))||ii.some(r=>!Object.prototype.hasOwnProperty.call(e,r)))return tt(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let o=r=>{let i=e[r];if(!Array.isArray(i)||i.length>64)return tt(`${t}/${r}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let s=new Set;return i.map((a,d)=>{let c=`${t}/${r}/${d}`;if(!Oo(a)||Object.keys(a).some(f=>f!=="from"&&f!=="to")||!oi(a.from)||!oi(a.to)||a.from===a.to)return tt(c,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let l=JSON.stringify([a.from,a.to]);return s.has(l)?tt(c,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(s.add(l),{from:a.from,to:a.to})}).sort((a,d)=>ri(a.from,d.from)||ri(a.to,d.to))},n=r=>{let i=e[r];return!Array.isArray(i)||i.length<1||i.length>16||i.some(s=>!oi(s))||new Set(i).size!==i.length?tt(`${t}/${r}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...i].sort(ri)};return{parentTransitions:o("parentTransitions"),childTransitions:o("childTransitions"),fulfilledChildStatuses:n("fulfilledChildStatuses"),lockedParentStatuses:n("lockedParentStatuses")}}function fa(e,t,o="/config/data/resources"){yo(e).forEach((n,r)=>{let i=`${o}/${r}/decimalReservationLifecycle`,s=si(n.decimalReservationLifecycle,i);if(!s)return;let a=yo(t).map(f=>f.platformAccess?.decimalReservation).filter(f=>Oo(f)&&f.resourceCode===n.code),d=a.find(f=>f.mode==="reserve");if(!d)return tt(i,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(ua.some(f=>typeof d[f]!="string")||a.some(f=>ua.some(p=>f[p]!==d[p])))return tt(i,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let c=yo(n.schema?.fields).find(f=>f.code===d.statusFieldCode);if(c?.type!=="option.single")return tt(i,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let l=new Set(yo(c.options).map(f=>f.value));for(let f of ii)if((f==="parentTransitions"||f==="childTransitions"?s[f].flatMap(m=>[m.from,m.to]):s[f]).some(m=>!l.has(m)))return tt(`${i}/${f}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(a.some(f=>f.mode==="reserve"&&Array.isArray(f.eligibleParentStatuses)&&f.eligibleParentStatuses.some(p=>s.lockedParentStatuses.includes(String(p)))))return tt(`${i}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as vl}from"crypto";var ai=new Set(["option.single","user.single","department.single","resource-ref.single"]),Pl=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),ma=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),$l=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Fl=new Set([...ai,...ma,"signature","address","location","json"]);function ag(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=>Vl(n,o.has(n.code))).sort((n,r)=>n.code.localeCompare(r.code))}function Vl(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:jl(e),index:xl(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 dg(e,t){if(t.type==="subtable")return null;let o=Re(t.code),n=ga(e,t),r=[n?` DEFAULT ${n}`:"",Ul(o,t),Wl(o,t)].join("");return`${o} ${t.storage}${r}`}function cg(e,t){return ga(e,t)}function Wl(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 lg(e){return e.type==="serial-number"||go(e.type)&&e.type!=="subtable"}function ug(e,t){return t.filter(o=>o.type==="serial-number").map(o=>{let n=ho(e,o.code),r=o.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${n} AS bigint MINVALUE ${r} START WITH ${r} CACHE 1`})}function fg(e,t){let o=bo(e);return t.filter(n=>n.type==="serial-number").map(n=>`ALTER SEQUENCE ${ho(e,n.code)} OWNED BY ${o}.${Re(n.code)}`)}function pg(e,t){return t.filter(o=>o.type==="serial-number").map(o=>`GRANT USAGE, SELECT ON SEQUENCE ${ho(e,o.code)} TO "openxiangda_data_api"`)}function mg(e,t){let o=bo(e),n=[];for(let r of t){if(r.type==="subtable")continue;let i=Re(r.code),s=Re(yt("idx",e,r.code,r.index));switch(r.index){case"btree":n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} (${i})`);break;case"btree-snapshot-expressions":{let a=Re(yt("idx",e,r.code,"snapshot-value")),d=Re(yt("idx",e,r.code,"snapshot-label"));n.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${o} ((${i} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${d} ON ${o} ((${i} ->> 'label'))`);break}case"gin-jsonb-path":n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} USING GIN (${i} jsonb_path_ops)`);break;case"gist-range":n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} USING GIST (${i})`);break;case"gin-trigram":{let a=ai.has(r.type)?`((${i} ->> 'label')) gin_trgm_ops`:`${i} gin_trgm_ops`;n.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${o} USING GIN (${a})`);break}case"none":break}if(r.type==="serial-number"){let a=Re(yt("uidx",e,r.code,"serial"));n.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${a} ON ${o} (${i})`)}}return n}function gg(e,t,o,n){let r=bo(e),i=bo(t),s=Re(yt("uidx",e,"environment_id","subtable-parent")),a=Re(yt("idx",t,o,n,"subtable-child")),d=Re(yt("fk",t,o,e)),c=Re(o),l=Re(n);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${r} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${a} ON ${i} ("tenant_id", "app_code", "environment_key", ${c}, ${l}, "id")`,`DO $native_subtable$ BEGIN
1
+ import{createHash as Pc}from"node:crypto";function $c(e){if(!e||typeof e!="object")return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ar(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((o,r)=>Ar(o,`${t}[${r}]`)).join(",")}]`;if($c(e))return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort((r,i)=>r===i?0:r<i?-1:1).map(r=>`${JSON.stringify(r)}:${Ar(e[r],`${t}.${r}`)}`).join(",")}}`;let n=e instanceof Date?"Date":e?.constructor?.name||typeof e;throw new TypeError(`Value is not JSON serializable: ${t} (${n})`)}function re(e){return Ar(e,"$")}function ee(e){return Pc("sha256").update(re(e)).digest("hex")}var Sp=8,_s={type:"array",minItems:2,maxItems:8,uniqueItems:!0,items:{type:"string",maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"}};function qt(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(n=>typeof n!="string"||n.length>128||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(n)))return["WORKFLOW_V2_BINDING_ROLE_UNION_INVALID"];if(e.provider==="app_role_in_scope"){let n=e.scope,o=typeof n?.value=="string"&&n.value.length>0&&n.value.length<=255&&n.valueFrom===void 0,r=typeof n?.valueFrom=="string"&&n.valueFrom.length<=255&&/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(n.valueFrom)&&!n.valueFrom.split(".").some(i=>["__proto__","prototype","constructor"].includes(i))&&n.value===void 0;if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).some(i=>!["dimension","value","valueFrom"].includes(i))||typeof n.dimension!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(n.dimension)||!o&&!r)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"]}else if(e.scope!==void 0)return["WORKFLOW_V2_BINDING_ROLE_UNION_SCOPE_INVALID"];return[]}function Yn(e){return e.roleCodes?[...e.roleCodes]:e.roleCode?[e.roleCode]:typeof e.until=="object"&&e.until.roleCode?[e.until.roleCode]:[]}function Dp(e){return e.some(t=>Object.values(t.binding.bindings).some(n=>n.roleCodes!==void 0))}function Xn(e){if(e.selectedInputPath===void 0)return[];let t=e.selectedInputPath;return!["app_role","app_role_in_scope"].includes(e.provider||"")||e.candidateField!==void 0||e.inputPath!==void 0||e.routing!==void 0||e.roleCode===void 0&&e.roleCodes===void 0||typeof t!="string"||t.length>255||!/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(t)||t.split(".").some(n=>["__proto__","constructor","prototype"].includes(n))?["WORKFLOW_V2_ROLE_INPUT_SELECTION_INVALID"]:[]}function kp(e){return e.some(t=>Object.values(t.binding.bindings).some(n=>n.selectedInputPath!==void 0))}var Fc="platform-notify-v1",vp="platform.notify",Vc={type:"object",additionalProperties:!1,properties:{text:{type:"string",minLength:1,maxLength:2048}},required:["text"]},Wc={type:"object",additionalProperties:!1,properties:{}},Er=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Zn=e=>JSON.stringify(e,(t,n)=>Er(n)?Object.fromEntries(Object.keys(n).sort().map(o=>[o,n[o]])):n);function ie(e){return e?.kind==="action"&&e.handler?.code===Fc&&e.notification!==void 0}function Pp(e){return{...e.notification.recipients,min:1,max:50,delegatable:!1}}function Qn(e){let t=[];for(let[n,o]of Object.entries(e?.nodes||{})){if(o?.notification===void 0)continue;(!ie(o)||o.handler.version!==1||o.handler.mode!=="reconciled-effect"||o.handler.dataTransaction!==void 0||Zn(o.inputSchema)!==Zn(Vc)||Zn(o.outputSchema)!==Zn(Wc))&&t.push(`WORKFLOW_NOTIFY_PRESET_INVALID:${n}`),o.inputs?.text?.source==="literal"&&(typeof o.inputs.text.value!="string"||!o.inputs.text.value.trim())&&t.push(`WORKFLOW_NOTIFY_TEXT_INVALID:${n}`);let r=o.notification,i=r?.recipients;if(!Er(r)||Object.keys(r).some(a=>!["template","recipients"].includes(a))||r.template!=="workflow_message"||!Er(i)){t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${n}`);continue}let s=Object.keys(i);i.provider==="initiator"?s.length!==1&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${n}`):i.provider==="fixed_users"?(s.some(a=>!["provider","users"].includes(a))||!Array.isArray(i.users)||i.users.length<1||i.users.length>50||new Set(i.users).size!==i.users.length||i.users.some(a=>typeof a!="string"||!a.trim()||a.length>255))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${n}`):i.provider==="app_role"?(s.some(a=>!["provider","roleCode"].includes(a))||typeof i.roleCode!="string"||!/^[A-Za-z][A-Za-z0-9_.-]{0,127}$/.test(i.roleCode))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${n}`):i.provider==="form_field_users"?(s.some(a=>!["provider","inputPath"].includes(a))||typeof i.inputPath!="string"||!/^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)*$/.test(i.inputPath)||i.inputPath.length>256||i.inputPath.split(".").length>8||i.inputPath.split(".").some(a=>["prototype","constructor","__proto__"].includes(a)))&&t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${n}`):t.push(`WORKFLOW_NOTIFY_RECIPIENT_INVALID:${n}`)}return t}var Ir="openxiangda.workflow.step.requested.v2",Vp=[Ir,"openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2"],br=16384,xc=2048,Wp="steps",hr=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Is=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Ct=new Set(["__proto__","prototype","constructor"]),X=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),ys=e=>{try{let t=JSON.stringify(e);return t===void 0?1/0:new TextEncoder().encode(t).length}catch{return 1/0}},zt=(e,t,n=0)=>{if(n>32)return!1;if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((i,s)=>zt(i,t[s],n+1));if(!X(e)||!X(t))return!1;let o=Object.keys(e).filter(i=>e[i]!==void 0),r=Object.keys(t).filter(i=>t[i]!==void 0);return o.length===r.length&&o.every(i=>Object.hasOwn(t,i)&&zt(e[i],t[i],n+1))};function yr(e,t){let n=0,o=(r,i)=>++n>1e4||i>8?!1:r===null||typeof r=="boolean"||typeof r=="string"?!0:typeof r=="number"?Number.isFinite(r):Array.isArray(r)?r.length<=200&&r.every(s=>o(s,i+1)):X(r)&&Object.keys(r).length<=32&&Object.keys(r).every(s=>!Ct.has(s))&&Object.values(r).every(s=>o(s,i+1));return ys(e)<=t&&o(e,0)}function jc(e){return!X(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&&X(e.output)&&yr(e.output,br)&&(e.receipt===void 0||X(e.receipt)&&yr(e.receipt,xc))}function xp(e){return X(e)&&Object.keys(e).every(t=>["executionId","nodeId","handlerCode","handlerVersion","mode","dataTransaction","input","inputDigest","expectedFactRevision"].includes(t))&&typeof e.nodeId=="string"&&hr.test(e.nodeId)&&!Ct.has(e.nodeId)&&typeof e.handlerCode=="string"&&/^[a-z][a-z0-9-]{0,100}$/.test(e.handlerCode)&&e.handlerCode.endsWith(`-v${e.handlerVersion}`)&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&jc({executionId:e.executionId,handlerVersion:e.handlerVersion,inputDigest:e.inputDigest,expectedFactRevision:e.expectedFactRevision,output:e.input})}function Gt(e,t,n=br){if(!yr(t,n))return!1;let o=1e4,r=(i,s,a)=>{if(--o<0||a>8||!X(i))return!1;let d=s===null?"null":Array.isArray(s)?"array":typeof s=="number"&&Number.isSafeInteger(s)?"integer":typeof s,c=Array.isArray(i.type)?i.type:[i.type];if(!c.includes(d)&&!(d==="integer"&&c.includes("number"))||i.enum!==void 0&&(!Array.isArray(i.enum)||!i.enum.some(l=>zt(l,s)))||Object.hasOwn(i,"const")&&!zt(i.const,s))return!1;if(typeof s=="number")return Number.isFinite(s)&&(i.minimum===void 0||s>=i.minimum)&&(i.maximum===void 0||s<=i.maximum);if(typeof s=="string"){let l=Array.from(s).length;return(i.minLength===void 0||l>=i.minLength)&&(i.maxLength===void 0||l<=i.maxLength)}return Array.isArray(s)?s.length<=i.maxItems&&(i.minItems===void 0||s.length>=i.minItems)&&s.every(l=>r(i.items,l,a+1)):X(s)?!X(i.properties)||Object.keys(s).some(l=>Ct.has(l)||!Object.hasOwn(i.properties,l))||(Array.isArray(i.required)?i.required:[]).some(l=>!Object.hasOwn(s,l))||i.minProperties!==void 0&&Object.keys(s).length<i.minProperties||i.maxProperties!==void 0&&Object.keys(s).length>i.maxProperties?!1:Object.entries(s).every(([l,f])=>r(i.properties[l],f,a+1)):s===null||typeof s=="boolean"};return r(e,t,0)}function Uc(e){return typeof e=="string"&&e.length<=256&&e.split(".").length<=8&&e.split(".").every(t=>hr.test(t)&&!Ct.has(t))}function Jt(e){let t=0,n=(o,r)=>{if(!X(o)||r>6||++t>256||Object.keys(o).some(a=>!["type","title","description","properties","required","additionalProperties","items","maxItems","minItems","maxLength","minLength","minimum","maximum","enum","const","maxProperties","minProperties"].includes(a)))return!1;let i=Array.isArray(o.type)?o.type:[o.type];if(!i.length||i.length>2||i.some(a=>!["object","array","string","integer","number","boolean","null"].includes(a))||i.length>1&&(!i.includes("null")||new Set(i).size!==i.length))return!1;for(let a of["title","description"])if(o[a]!==void 0&&(typeof o[a]!="string"||o[a].length>2e3))return!1;for(let a of["minimum","maximum"])if(o[a]!==void 0&&(typeof o[a]!="number"||!Number.isFinite(o[a])))return!1;for(let[a,d]of[["maxItems",200],["minItems",200],["maxLength",16384],["minLength",16384],["maxProperties",32],["minProperties",32]])if(o[a]!==void 0&&(!Number.isSafeInteger(o[a])||o[a]<0||o[a]>d))return!1;for(let[a,d]of[["minimum","maximum"],["minItems","maxItems"],["minLength","maxLength"],["minProperties","maxProperties"]])if(o[a]!==void 0&&o[d]!==void 0&&o[a]>o[d])return!1;if(["properties","required","additionalProperties","maxProperties","minProperties"].some(a=>o[a]!==void 0)&&!i.includes("object")||["items","maxItems","minItems"].some(a=>o[a]!==void 0)&&!i.includes("array")||["maxLength","minLength"].some(a=>o[a]!==void 0)&&!i.includes("string")||["minimum","maximum"].some(a=>o[a]!==void 0)&&!i.some(a=>a==="integer"||a==="number")||o.enum!==void 0&&(!Array.isArray(o.enum)||!o.enum.length||o.enum.length>100)||i.includes("object")&&(!X(o.properties)||o.additionalProperties!==!1||Object.keys(o.properties).length>32||Object.keys(o.properties).some(a=>!Is.test(a)||Ct.has(a))||o.required!==void 0&&(!Array.isArray(o.required)||new Set(o.required).size!==o.required.length||o.required.some(a=>typeof a!="string"||!Object.hasOwn(o.properties,a)))||o.minProperties!==void 0&&o.minProperties>Object.keys(o.properties).length||o.maxProperties!==void 0&&o.maxProperties<(o.required?.length||0)||!Object.values(o.properties).every(a=>n(a,r+1)))||i.includes("array")&&(!Number.isSafeInteger(o.maxItems)||!n(o.items,r+1)))return!1;let s={...o};return delete s.enum,delete s.const,!(o.enum!==void 0&&(!o.enum.every(a=>Gt(s,a))||o.enum.some((a,d)=>o.enum.slice(0,d).some(c=>zt(a,c))))||Object.hasOwn(o,"const")&&!Gt(s,o.const))};return X(e)&&e.type==="object"&&ys(e)<=br&&n(e,0)}function _t(e){let t=Object.fromEntries(Object.values(e.nodes||{}).filter(n=>n?.kind==="action").map(n=>[n.id,n.outputSchema]));return Object.keys(t).length?{...e.inputSchema,properties:{...e.inputSchema?.properties,steps:{type:"object",additionalProperties:!1,properties:t}}}:e.inputSchema||{}}function Os(e,t){let n=e;for(let o of t.split(".")){if(!X(n?.properties)||!Object.hasOwn(n.properties,o))return;n=n.properties[o]}return X(n)?n:void 0}var As=(e,t)=>!!Os(e,t);function jp(e){return X(e)&&Object.keys(e).every(t=>["version","mode","dataTransaction","inputSchema","outputSchema"].includes(t))&&Number.isSafeInteger(e.version)&&e.version>=1&&e.version<=1e6&&["pure","reconciled-effect"].includes(e.mode)&&(e.dataTransaction===void 0||e.dataTransaction===!0&&e.mode==="reconciled-effect")&&Jt(e.inputSchema)&&Jt(e.outputSchema)}function Es(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="parallel"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.join]:e.kind==="join"?[e.next]:e.kind==="condition"?[...Array.isArray(e.branches)?e.branches.map(t=>t.target):[],e.otherwise]:e.kind==="cc"||e.kind==="action"||e.kind==="handle"?[e.next]:[]}function Or(e,t=0){return!X(e)||t>16?[]:e.op==="path"?typeof e.path=="string"?[e.path]:[]:["left","right","value"].flatMap(n=>Or(e[n],t+1)).concat(Array.isArray(e.values)?e.values.flatMap(n=>Or(n,t+1)):[])}function Mc(e){if(e.authoring===void 0)return[];let t=e.authoring;if(!X(t)||Object.keys(t).some(r=>r!=="businessSteps")||t.businessSteps!==void 0&&(!Array.isArray(t.businessSteps)||t.businessSteps.length>100))return["WORKFLOW_AUTHORING_CATALOG_INVALID"];let n=[],o=new Set;for(let r of t.businessSteps||[]){let i=r?.handler;(!X(r)||Object.keys(r).some(s=>!["title","handler","inputSchema","outputSchema"].includes(s))||typeof r.title!="string"||!r.title.trim()||r.title.length>160||!X(i)||Object.keys(i).some(s=>!["code","version","mode","dataTransaction"].includes(s))||!Number.isSafeInteger(i.version)||i.version<1||i.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(i.code||"")||!i.code.endsWith(`-v${i.version}`)||!["pure","reconciled-effect"].includes(i.mode)||i.dataTransaction!==void 0&&(i.dataTransaction!==!0||i.mode!=="reconciled-effect")||!Jt(r.inputSchema)||!Jt(r.outputSchema)||o.has(i.code))&&n.push("WORKFLOW_AUTHORING_STEP_INVALID"),i?.code&&o.add(i.code)}return n}function eo(e,t){if(!X(e)||!X(e.nodes))return["WORKFLOW_STEP_DEFINITION_INVALID"];let n=e.nodes,o=Object.entries(n).filter(([,a])=>a?.kind==="action");if(!o.length)return[];let r=[...Qn(e),...Mc(e)];Object.hasOwn(e.inputSchema?.properties||{},"steps")&&r.push("WORKFLOW_STEP_FACT_NAMESPACE_RESERVED");let i=_t(e);for(let[a,d]of o){(Object.keys(d).some(f=>!["id","kind","title","next","handler","inputSchema","outputSchema","inputs",...ie(d)?["notification"]:[]].includes(f))||d.id!==a||!hr.test(a)||Ct.has(a)||typeof d.title!="string"||!d.title.trim()||d.title.length>255||typeof d.next!="string"||!Object.hasOwn(n,d.next))&&r.push(`WORKFLOW_STEP_NODE_INVALID:${a}`);let c=d.handler;(!X(c)||Object.keys(c).some(f=>!["code","version","mode","dataTransaction"].includes(f))||!Number.isSafeInteger(c.version)||c.version<1||c.version>1e6||!/^[a-z][a-z0-9-]{0,100}$/.test(c.code||"")||!String(c.code).endsWith(`-v${c.version}`)||!["pure","reconciled-effect"].includes(c.mode)||c.dataTransaction!==void 0&&(c.dataTransaction!==!0||c.mode!=="reconciled-effect"))&&r.push(`WORKFLOW_STEP_HANDLER_INVALID:${a}`);let l=Jt(d.inputSchema);if((!l||!Jt(d.outputSchema))&&r.push(`WORKFLOW_STEP_SCHEMA_INVALID:${a}`),!X(d.inputs)||Object.keys(d.inputs).length>32){r.push(`WORKFLOW_STEP_INPUTS_INVALID:${a}`);continue}for(let f of Array.isArray(d.inputSchema?.required)?d.inputSchema.required:[])Object.hasOwn(d.inputs,f)||r.push(`WORKFLOW_STEP_INPUT_REQUIRED:${a}:${f}`);for(let[f,p]of Object.entries(d.inputs)){if(!Is.test(f)||Ct.has(f)||!Object.hasOwn(d.inputSchema?.properties||{},f)||!X(p)){r.push(`WORKFLOW_STEP_INPUT_INVALID:${a}:${f}`);continue}if(p.source==="literal")(!l||Object.keys(p).some(m=>!["source","value"].includes(m))||!Object.hasOwn(p,"value")||!Gt(d.inputSchema.properties[f],p.value))&&r.push(`WORKFLOW_STEP_LITERAL_INVALID:${a}:${f}`);else if(p.source!=="fact"||Object.keys(p).some(m=>!["source","path"].includes(m))||!Uc(p.path)||!As(i,p.path))r.push(`WORKFLOW_STEP_FACT_PATH_INVALID:${a}:${f}`);else if(l){let m=Os(i,p.path),A=d.inputSchema.properties[f],I=Array.isArray(m.type)?m.type:[m.type],O=Array.isArray(A.type)?A.type:[A.type];I.some(b=>!O.includes(b)&&!(b==="integer"&&O.includes("number")))&&r.push(`WORKFLOW_STEP_FACT_TYPE_MISMATCH:${a}:${f}`)}}}let s=(a,d)=>{let c=new Set,l=[e.startAt||""];for(;l.length&&c.size<=200;){let f=l.shift();if(!(f===d||c.has(f)||!n[f])){if(f===a)return!0;c.add(f),l.push(...Es(n[f]))}}return!1};for(let[a,d]of Object.entries(n)){if(!X(d))continue;let c=d.kind==="action"?Object.values(d.inputs||{}).flatMap(f=>f?.source==="fact"?[f.path]:[]):(Array.isArray(d.branches)?d.branches:[]).flatMap(f=>Or(f?.when)),l=t?.bindings?.[d.binding];l&&c.push(...[l.inputPath,l.departmentIdFrom,l.resourceIdFrom,l.scope?.valueFrom].filter(f=>typeof f=="string"));for(let f of c.filter(p=>typeof p=="string"&&p.startsWith("steps."))){let p=f.split(".")[1];(n[p]?.kind!=="action"||p===a||!As(i,f)||s(a,p))&&r.push(`WORKFLOW_STEP_OUTPUT_NOT_AVAILABLE:${a}:${f}`)}}if(t)for(let[,a]of o.filter(([,d])=>!ie(d))){let d=new Set,c=[a.next];for(;c.length&&d.size<=200;){let l=c.shift();if(d.has(l)||!X(n[l]))continue;d.add(l);let f=n[l];if(!(f.kind==="action"||f.kind==="end")){if(f.kind==="approval"){let p=t.bindings?.[f.binding];p&&["application_provider","initiator_select"].includes(p.provider)&&r.push(`WORKFLOW_STEP_NEXT_PROVIDER_REQUIRES_PREPARED_RESULT:${l}`);continue}c.push(...Es(f))}}}return[...new Set(r)]}function Up(e,t){let n={};for(let[o,r]of Object.entries(e.inputs)){let i=r.source==="literal"?r.value:r.path.split(".").reduce((s,a)=>X(s)&&Object.hasOwn(s,a)?s[a]:void 0,t);i!==void 0&&(n[o]=i)}if(!Gt(e.inputSchema,n))throw new Error("WORKFLOW_STEP_INPUT_SCHEMA_INVALID");return n}function bs(e,t,n){let o=Nr(e),r=[];Object.keys(o).length&&!n&&r.push("WORKFLOW_STEP_BACKEND_REQUIRED");for(let i of Object.keys(o)){let s=t.find(a=>a.code===i);(!s||s.execution||s.action||!Array.isArray(s.eventTypes)||s.eventTypes.length!==1||s.eventTypes[0]!==Ir||!X(s.filter)||Object.keys(s.filter).length!==1||!X(s.filter.workflowStep)||Object.keys(s.filter.workflowStep).length!==1||s.filter.workflowStep.handlerCode!==i||!X(s.payload)||s.payload.includeChanges!==!1||!Array.isArray(s.payload.fields)||s.payload.fields.length)&&r.push(`WORKFLOW_STEP_SUBSCRIPTION_INVALID:${i}`)}for(let i of t)(i.eventTypes?.includes(Ir)&&!o[i.code]||i.filter?.workflowStep&&!o[i.code])&&r.push(`WORKFLOW_STEP_HANDLER_NOT_DECLARED:${i.code}`);return r}function Nr(e){let t={};for(let n of e){let o=eo(n);if(o.length)throw new Error(o.join("; "));for(let r of[...Object.values(n.nodes||{}),...n.authoring?.businessSteps||[]]){if(!r.handler||ie(r))continue;let i={version:r.handler.version,mode:r.handler.mode,...r.handler.dataTransaction?{dataTransaction:!0}:{},inputSchema:r.inputSchema,outputSchema:r.outputSchema},s=t[r.handler.code];if(s&&!zt(s,i))throw new Error(`WORKFLOW_STEP_HANDLER_CONTRACT_CONFLICT:${r.handler.code}`);t[r.handler.code]=i}}return t}var wr=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Bc=e=>typeof e=="string"&&e.length<=255&&e.split(".").length<=8&&/^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z][A-Za-z0-9_-]*)*$/.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function Ht(e){if(e?.provider!=="supervisor_chain")return e&&["from","until","continuous","missing"].some(o=>e[o]!==void 0)?["WORKFLOW_SUPERVISOR_CHAIN_PROVIDER_INVALID"]:[];let t=e.from,n=e.until;return!wr(e)||Object.keys(e).some(o=>!["provider","from","until","continuous","missing","min","max","delegatable"].includes(o))||!(t==="initiator"||wr(t)&&Object.keys(t).length===1&&Bc(t.field))||!(n==="top"||wr(n)&&Object.keys(n).length===1&&(Number.isInteger(n.level)&&n.level>=1&&n.level<=20||typeof n.roleCode=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(n.roleCode)&&n.roleCode.length<=128))||e.continuous!==void 0&&typeof e.continuous!="boolean"||e.missing!==void 0&&!["skip_level","block"].includes(e.missing)?["WORKFLOW_SUPERVISOR_CHAIN_BINDING_INVALID"]:[]}function At(e,t){let n=[];for(let[o,r]of Object.entries(t?.bindings||{}))n.push(...Ht(r).map(i=>`${i}:${o}`));for(let[o,r]of Object.entries(e?.nodes||{})){let i=t?.bindings?.[r?.binding];if(!(i?.provider!=="supervisor_chain"||Ht(i).length))if(["approval","handle"].includes(r.kind)||n.push(`WORKFLOW_SUPERVISOR_CHAIN_HUMAN_REQUIRED:${o}`),i.continuous!==!1&&r.mode!=="sequence"&&n.push(`WORKFLOW_SUPERVISOR_CHAIN_SEQUENCE_REQUIRED:${o}`),i.from==="initiator")(!e.organizationContext?.department||e.organizationContext.department.source==="none")&&n.push(`WORKFLOW_SUPERVISOR_CHAIN_DEPARTMENT_CONTEXT_REQUIRED:${o}`);else{let s=_t(e);for(let d of i.from.field.split("."))s=s?.properties?.[d];let a=Array.isArray(s?.type)?s.type.filter(d=>d!=="null")[0]:s?.type;(!s||!["string","array","object"].includes(a))&&n.push(`WORKFLOW_SUPERVISOR_CHAIN_USER_FACT_REQUIRED:${o}`)}}return n}function Kp(e){let t=e.from==="initiator"?"\u7533\u8BF7\u4EBA":`\u6210\u5458\u53D8\u91CF ${e.from.field}`,n=e.until==="top"?"\u6700\u4E0A\u7EA7":"level"in e.until?`\u7B2C ${e.until.level} \u7EA7`:`\u89D2\u8272 ${e.until.roleCode}`;return`${t}\u7684\u4E3B\u7BA1\u94FE \xB7 \u81F3${n} \xB7 ${e.continuous!==!1?"\u9010\u7EA7\u529E\u7406":"\u4EC5\u7EC8\u70B9\u529E\u7406"}`}var zp=256,Gp=64,Jp=262144,Kc=/^[a-z][a-z0-9_-]{0,127}$/,qc=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/,Ns=new Set(["__proto__","prototype","constructor"]),Ze=e=>!!e&&typeof e=="object"&&!Array.isArray(e),In=(e,t)=>Object.keys(e).every(n=>t.includes(n)),St=(e,t)=>typeof e=="string"&&e.trim().length>0&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),dt=e=>typeof e=="string"&&Kc.test(e)&&!Ns.has(e),ws=e=>typeof e=="string"&&e.length<=255&&qc.test(e)&&!e.split(".").some(t=>Ns.has(t)),zc=e=>Ze(e)&&In(e,["dimension","valueFrom","value"])&&dt(e.dimension)&&(St(e.value,255)&&e.valueFrom===void 0||ws(e.valueFrom)&&e.value===void 0),hs=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)),En={type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},Rr={type:"string",minLength:1,maxLength:128},Rs={type:"object",additionalProperties:!1,required:["policyCode","title","strategy","dimensions","sources"],properties:{policyCode:En,title:Rr,strategy:{enum:["replace_then_append","replace_only"]},dimensions:{type:"object",maxProperties:8,propertyNames:En,additionalProperties:{type:"object",additionalProperties:!1,required:["title","valueFrom"],properties:{title:Rr,valueFrom:{type:"string",minLength:1,maxLength:255}}}},sources:{type:"object",minProperties:1,maxProperties:16,propertyNames:En,additionalProperties:{type:"object",additionalProperties:!1,required:["title","provider","roleCode"],properties:{title:Rr,provider:{enum:["app_role","app_role_in_scope"]},roleCode:En,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:En,value:{type:"string",minLength:1,maxLength:255},valueFrom:{type:"string",minLength:1,maxLength:255}}}}}}}};function Yt(e){if(!Ze(e)||!In(e,["policyCode","title","strategy","dimensions","sources"])||!dt(e.policyCode)||!St(e.title,128)||!["replace_then_append","replace_only"].includes(e.strategy))return["WORKFLOW_V2_ROUTING_POLICY_INVALID"];let t=[];return(!Ze(e.dimensions)||Object.keys(e.dimensions).length>8||Object.entries(e.dimensions).some(([n,o])=>!dt(n)||!Ze(o)||!In(o,["title","valueFrom"])||!St(o.title,128)||!ws(o.valueFrom)))&&t.push("WORKFLOW_V2_ROUTING_DIMENSIONS_INVALID"),(!Ze(e.sources)||Object.keys(e.sources).length<1||Object.keys(e.sources).length>16||Object.entries(e.sources).some(([n,o])=>!dt(n)||!Ze(o)||!In(o,["title","provider","roleCode","scope"])||!St(o.title,128)||!dt(o.roleCode)||!["app_role","app_role_in_scope"].includes(o.provider)||(o.provider==="app_role_in_scope"?!zc(o.scope):o.scope!==void 0)))&&t.push("WORKFLOW_V2_ROUTING_SOURCES_INVALID"),t}function Hp(e,t){if(Yt(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 n=[],o=new Set;for(let r of t){if(!Ze(r)||!In(r,["ruleCode","title","enabled","workflowCode","nodeId","matches","sourceCode","effect","priority","validFrom","validTo"])||!dt(r.ruleCode)||!St(r.title,128)||typeof r.enabled!="boolean"||!dt(r.sourceCode)||!Object.hasOwn(e.sources,r.sourceCode)||!["append","replace"].includes(r.effect)||!Number.isSafeInteger(r.priority)||r.priority<-1e3||r.priority>1e3||r.workflowCode!==void 0&&!dt(r.workflowCode)||r.nodeId!==void 0&&(!dt(r.nodeId)||r.workflowCode===void 0)||r.validFrom!==void 0&&!hs(r.validFrom)||r.validTo!==void 0&&!hs(r.validTo)||r.validFrom&&r.validTo&&Date.parse(r.validFrom)>=Date.parse(r.validTo)){n.push("WORKFLOW_V2_ROUTING_RULE_INVALID");continue}o.has(r.ruleCode)&&n.push(`WORKFLOW_V2_ROUTING_RULE_DUPLICATE:${r.ruleCode}`),o.add(r.ruleCode),(!Ze(r.matches)||Object.entries(r.matches).some(([i,s])=>!Object.hasOwn(e.dimensions,i)||!Array.isArray(s)||s.length<1||s.length>64||new Set(s).size!==s.length||s.some(a=>!St(a,255))))&&n.push(`WORKFLOW_V2_ROUTING_MATCH_INVALID:${r.ruleCode}`)}return[...new Set(n)]}function Gc(e){return JSON.stringify({policyCode:e.policyCode,strategy:e.strategy,dimensions:Object.entries(e.dimensions).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>[t,n.valueFrom]),sources:Object.entries(e.sources).sort(([t],[n])=>t<n?-1:t>n?1:0).map(([t,n])=>[t,n.provider,n.roleCode,n.scope?.dimension??null,n.scope?.valueFrom??null,n.scope?.value??null])})}function Ts(e){let t=[],n=new Map;for(let o of e)for(let[r,i]of Object.entries(o.bindings||{})){if(!Ze(i)||i.routing===void 0)continue;let s=Yt(i.routing);if(s.length){t.push(...s.map(c=>`${c}:${r}`));continue}let a=Gc(i.routing),d=n.get(i.routing.policyCode);d&&d!==a&&t.push(`WORKFLOW_V2_ROUTING_POLICY_CONFLICT:${i.routing.policyCode}`),n.set(i.routing.policyCode,a)}return[...new Set(t)]}function Yp(e,t){let n={};for(let[o,r]of Object.entries(e.dimensions)){let i=t;for(let s of r.valueFrom.split("."))i=Ze(i)&&Object.hasOwn(i,s)?i[s]:void 0;if(!(typeof i=="string"&&St(i,255)||typeof i=="number"&&Number.isFinite(i)||typeof i=="boolean"))throw new Error(`WORKFLOW_V2_ROUTING_FACT_REQUIRED:${o}`);n[o]=String(i)}return n}function Xp(e,t,n){let o=t.filter(c=>c.enabled&&(!c.validFrom||Date.parse(c.validFrom)<=n.at)&&(!c.validTo||Date.parse(c.validTo)>n.at)&&(!c.workflowCode||c.workflowCode===n.workflowCode)&&(!c.nodeId||c.nodeId===n.nodeId)&&Object.entries(c.matches).every(([l,f])=>f.includes(n.facts[l])));if(o.length>64)throw new Error("WORKFLOW_V2_ROUTING_MATCH_LIMIT_EXCEEDED");let r=(c,l)=>l.priority-c.priority||+!!c.workflowCode-+!!l.workflowCode||+!!c.nodeId-+!!l.nodeId||(c.ruleCode<l.ruleCode?-1:c.ruleCode>l.ruleCode?1:0),i=o.filter(c=>c.effect==="replace").sort(r);if(i.length>1&&i[0].priority===i[1].priority)throw new Error("WORKFLOW_V2_ROUTING_REPLACE_CONFLICT");let s=i[0],a=s&&e.strategy==="replace_only"?[]:o.filter(c=>c.effect==="append").sort(r),d=[...s?[s]:[],...a];return{matched:o.sort(r),replacement:s,applied:d,ignored:o.filter(c=>!d.includes(c))}}var Tr={type:"string",minLength:1},Jc={type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},Dt={type:"object",additionalProperties:!1,required:["provider"],allOf:[{if:{required:["roleCodes"]},then:{properties:{provider:{enum:["app_role","app_role_in_scope"]}},not:{anyOf:[{required:["roleCode"]},{required:["candidateField"]}]}}},{if:{required:["candidateField"]},then:{required:["inputPath"],properties:{provider:{const:"form_field_users"}},not:{anyOf:[{required:["roleCode"]},{required:["scope"]},{required:["routing"]}]}}},{if:{required:["selectedInputPath"]},then:{properties:{provider:{enum:["app_role","app_role_in_scope"]}},anyOf:[{required:["roleCode"]},{required:["roleCodes"]}],not:{anyOf:[{required:["candidateField"]},{required:["inputPath"]},{required:["routing"]}]}}}],properties:{provider:{enum:["fixed_users","initiator","input_users","form_field_users","department_supervisor","supervisor_chain","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"]},users:{type:"array",uniqueItems:!0,items:Tr},inputPath:{type:"string"},selectedInputPath:{type:"string",maxLength:255,pattern:"^[A-Za-z][A-Za-z0-9_-]*(?:\\.[A-Za-z][A-Za-z0-9_-]*)*$"},candidateField:Jc,from:{oneOf:[{const:"initiator"},{type:"object",additionalProperties:!1,required:["field"],properties:{field:{type:"string",maxLength:255}}}]},until:{oneOf:[{const:"top"},{type:"object",additionalProperties:!1,required:["level"],properties:{level:{type:"integer",minimum:1,maximum:20}}},{type:"object",additionalProperties:!1,required:["roleCode"],properties:{roleCode:Tr}}]},continuous:{type:"boolean"},missing:{enum:["skip_level","block"]},departmentIdFrom:{type:"string"},level:{type:"integer",minimum:1,maximum:20},fallbackToAncestorSupervisor:{type:"boolean"},roleCode:{type:"string"},roleCodes:_s,scope:{type:"object",additionalProperties:!1,required:["dimension"],properties:{dimension:Tr,valueFrom:{type:"string"},value:{type:"string"}}},relationCode:{type:"string"},resourceCode:{type:"string"},resourceIdFrom:{type:"string"},providerCode:{type:"string"},min:{type:"integer",minimum:1,maximum:200},max:{type:"integer",minimum:1,maximum:200},delegatable:{type:"boolean"},routing:Rs}};var kt={type:"object",required:["op"],properties:{op:{enum:["literal","path","eq","neq","gt","gte","lt","lte","in","contains","and","or","not","exists"]},value:{},path:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_.]{0,254}$"},left:{type:"object"},right:{type:"object"},values:{type:"array",minItems:1,items:{type:"object"}}}};var no=20,Cr=16384,yn=["fixed_users","app_role","app_role_in_scope","supervisor_chain","department_supervisor","form_field_users","input_users","initiator","previous_node_actor","business_relation"],to=Dt,Sr={type:"object",additionalProperties:!1,required:["provider","cases","otherwise"],properties:{provider:{const:"conditional"},cases:{type:"array",minItems:1,maxItems:no,items:{type:"object",additionalProperties:!1,required:["when","assignee"],properties:{label:{type:"string",minLength:1,maxLength:160},when:kt,assignee:{...to,properties:{...to.properties,provider:{enum:yn}}}}}},otherwise:{...to,properties:{...to.properties,provider:{enum:yn}}}}};var Hc=Dt,Cs=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Dr=(e,t)=>Object.keys(e).every(n=>t.includes(n)),Ss=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),oo=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(e)&&e.split(".").every(t=>!!t&&!["__proto__","prototype","constructor"].includes(t)),ro=e=>typeof e=="string"&&e.length<=128&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e);function Lt(e,t=!1){if(!Cs(e)||!yn.includes(e.provider)||!Dr(e,Object.keys(Hc.properties)))return["WORKFLOW_CONDITIONAL_LEAF_INVALID"];let n=[...Ht(e),...qt(e),...Xn(e)];return Dr(e,["provider","min","max","delegatable",...{fixed_users:["users"],app_role:["roleCode","roleCodes","selectedInputPath","routing"],app_role_in_scope:["roleCode","roleCodes","scope","selectedInputPath","routing"],supervisor_chain:["from","until","continuous","missing"],department_supervisor:["departmentIdFrom","level","fallbackToAncestorSupervisor"],form_field_users:["inputPath","candidateField"],input_users:["inputPath"],initiator:[],previous_node_actor:[],business_relation:["relationCode","resourceCode","resourceIdFrom"]}[e.provider]])||n.push("WORKFLOW_CONDITIONAL_LEAF_FIELDS_INVALID"),e.routing!==void 0&&n.push(...Yt(e.routing)),(["min","max"].some(r=>e[r]!==void 0&&(!Number.isInteger(e[r])||e[r]<1||e[r]>200))||(e.min??1)>(e.max??200)||e.delegatable!==void 0&&typeof e.delegatable!="boolean")&&n.push("WORKFLOW_CONDITIONAL_LEAF_BOUNDS_INVALID"),e.provider==="fixed_users"&&(!Array.isArray(e.users)||!t&&!e.users.length||e.users.length>200||new Set(e.users).size!==e.users.length||e.users.some(r=>!Ss(r,255)))&&n.push("WORKFLOW_CONDITIONAL_USERS_INVALID"),["app_role","app_role_in_scope"].includes(e.provider)&&e.roleCodes===void 0&&!(t&&e.roleCode===void 0)&&!ro(e.roleCode)&&n.push("WORKFLOW_CONDITIONAL_ROLE_INVALID"),e.provider==="app_role_in_scope"&&(!Cs(e.scope)||!Dr(e.scope,["dimension","value","valueFrom"])||!ro(e.scope.dimension)||!(Ss(e.scope.value,255)&&e.scope.valueFrom===void 0||oo(e.scope.valueFrom)&&e.scope.value===void 0))&&n.push("WORKFLOW_CONDITIONAL_SCOPE_INVALID"),["input_users","form_field_users"].includes(e.provider)&&!oo(e.inputPath)&&n.push("WORKFLOW_CONDITIONAL_INPUT_PATH_INVALID"),e.provider==="business_relation"&&(!ro(e.relationCode)||!ro(e.resourceCode)||!oo(e.resourceIdFrom))&&n.push("WORKFLOW_CONDITIONAL_RELATION_INVALID"),e.provider==="department_supervisor"&&(!oo(e.departmentIdFrom)||e.level!==void 0&&(!Number.isInteger(e.level)||e.level<1||e.level>20)||e.fallbackToAncestorSupervisor!==void 0&&typeof e.fallbackToAncestorSupervisor!="boolean")&&n.push("WORKFLOW_DEPARTMENT_SUPERVISOR_INVALID"),n}var Ds={department_supervisor:["departmentIdFrom","level","fallbackToAncestorSupervisor","min","max"],supervisor_chain:["from","until","continuous","missing","min","max"],form_field_users:["inputPath","min","max"],input_users:["inputPath","min","max"],app_role_in_scope:["roleCode","scope","min","max"]},vt=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function ks(e){let t=4096,n=(o,r)=>--t<0||r>12?!1:o===null||typeof o=="boolean"?!0:typeof o=="string"?o.length<=2048:typeof o=="number"?Number.isFinite(o):Array.isArray(o)?o.length<=200&&o.every(i=>n(i,r+1)):vt(o)&&Object.keys(o).every(i=>!["__proto__","prototype","constructor"].includes(i)&&!Object.getOwnPropertyDescriptor(o,i)?.get&&n(o[i],r+1));try{return n(e,0)&&new TextEncoder().encode(JSON.stringify(e)).length<=32768}catch{return!1}}var Pt=e=>{let t=n=>Array.isArray(n)?n.map(t):vt(n)?Object.fromEntries(Object.keys(n).filter(o=>n[o]!==void 0).sort().map(o=>[o,t(n[o])])):n;return JSON.stringify(t(e))},Yc=(e,t)=>Array.isArray(t.values)?t.values.some(n=>Pt(n)===Pt(e)):Number.isSafeInteger(e)&&e>=t.minimum&&e<=t.maximum;function kr(e){if(!ks(e)||!vt(e)||Object.keys(e).some(t=>!["code","title","entry","parameters"].includes(t))||typeof e.code!="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(e.code)||typeof e.title!="string"||!e.title.trim()||e.title.length>160||!vt(e.entry)||!Ds[e.entry.provider]||Lt(e.entry).length||!vt(e.parameters)||!Object.keys(e.parameters).length||Object.keys(e.parameters).length>8)return["WORKFLOW_PEOPLE_SOURCE_TEMPLATE_INVALID"];for(let[t,n]of Object.entries(e.parameters)){if(!Ds[e.entry.provider].includes(t)||!vt(n))return["WORKFLOW_PEOPLE_SOURCE_PARAMETER_INVALID"];if(Object.hasOwn(n,"values")){if(Object.keys(n).length!==1||!Array.isArray(n.values)||!n.values.length||n.values.length>32||new Set(n.values.map(Pt)).size!==n.values.length)return["WORKFLOW_PEOPLE_SOURCE_PARAMETER_INVALID"];for(let o of n.values){let r={...e.entry,[t]:o};if(Lt(r).length||t==="scope"&&o?.dimension!==e.entry.scope?.dimension||t==="min"&&o<(e.entry.min??1)||t==="max"&&o>(e.entry.max??200))return["WORKFLOW_PEOPLE_SOURCE_PARAMETER_CEILING"]}}else if(Object.keys(n).some(o=>!["minimum","maximum"].includes(o))||!["level","min","max"].includes(t)||!Number.isSafeInteger(n.minimum)||!Number.isSafeInteger(n.maximum)||n.minimum<1||n.maximum<n.minimum||n.maximum>(t==="level"?20:200)||t==="min"&&n.minimum<(e.entry.min??1)||t==="max"&&n.maximum>(e.entry.max??200))return["WORKFLOW_PEOPLE_SOURCE_PARAMETER_CEILING"]}return[]}function Ls(e){let t=e.authoring?.peopleSources;if(t===void 0)return[];if(!Array.isArray(t)||t.length>32)return["WORKFLOW_PEOPLE_SOURCE_TEMPLATE_LIMIT"];let n=t.flatMap(kr);if(n.length)return[...new Set(n)];if(new Set(t.map(s=>s.code)).size!==t.length)return["WORKFLOW_PEOPLE_SOURCE_TEMPLATE_LIMIT"];let o=_t(e),r=s=>{if(typeof s!="string"||s.split(".").some(d=>!d||["__proto__","prototype","constructor"].includes(d)))return;let a=o;for(let d of s.split("."))a=vt(a?.properties)&&Object.hasOwn(a.properties,d)?a.properties[d]:void 0;return a},i=[];for(let s of t){let a=kr(s);if(a.length){i.push(...a);continue}let d=[s.entry,...Object.entries(s.parameters).flatMap(([c,l])=>l.values?.map(f=>({...s.entry,[c]:f}))||[])];for(let c of d){for(let l of[c.inputPath,c.departmentIdFrom,c.scope?.valueFrom,...typeof c.from=="object"?[c.from.field]:[]].filter(f=>f!==void 0))r(l)||i.push("WORKFLOW_PEOPLE_SOURCE_FACT_UNAVAILABLE");if(c.provider==="supervisor_chain"){let l={...e,nodes:{probe:{id:"probe",kind:"approval",mode:c.continuous===!1?"single":"sequence",binding:"probe"}}};i.push(...At(l,{bindings:{probe:c}}))}}}return[...new Set(i)]}function Xc(e,t,n=!0){if(!ks(e)||kr(t).length||e.provider!==t.entry.provider)return!1;let o=r=>Object.fromEntries(Object.entries(r).filter(([i])=>!Object.hasOwn(t.parameters,i)));return Pt(o(e))!==Pt(o(t.entry))?!1:!n||!Lt(e).length&&Object.entries(t.parameters).every(([r,i])=>Pt(e[r])===Pt(t.entry[r])||Yc(e[r],i))}function io(e,t=[]){return Array.isArray(t)&&t.length<=32&&t.some(n=>Xc(e,n))}function vs(e,t,n={}){let o=1024,r=()=>{throw new Error("WORKFLOW_V2_EXPRESSION_TYPE_INVALID")},i=d=>d===null||["string","number","boolean"].includes(typeof d),s=d=>n.strict?typeof d=="boolean"?d:r():!!d,a=(d,c=0,l=!1)=>{if(--o<0||c>32)throw new Error("WORKFLOW_V2_EXPRESSION_LIMIT");let f=p=>a(p,c+1);switch(d?.op){case"literal":return n.strict&&typeof d.value=="number"&&!Number.isFinite(d.value)&&r(),d.value;case"path":{if(!/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(d.path||"")||d.path.split(".").some(m=>["__proto__","prototype","constructor"].includes(m)))throw new Error("WORKFLOW_V2_EXPRESSION_PATH_INVALID");let p=d.path.split(".").reduce((m,A)=>!m||typeof m!="object"||Array.isArray(m)||!Object.hasOwn(m,A)?void 0:m[A],t);if(n.strict){if(p===void 0&&(!l||n.requiredForPath?.(d.path)))throw new Error("WORKFLOW_V2_EXPRESSION_FACT_MISSING");let m=n.schemaForPath?.(d.path);(!m||p!==void 0&&!Gt(m,p))&&r()}return n.onPathRead?.(d.path,p),p}case"eq":case"neq":{let p=f(d.left),m=f(d.right);return n.strict&&(!i(p)||!i(m)||p!==null&&m!==null&&typeof p!=typeof m)&&r(),d.op==="eq"?p===m:p!==m}case"gt":case"gte":case"lt":case"lte":{let p=f(d.left),m=f(d.right);if(p===void 0||m===void 0)return!1;n.strict&&(typeof p!=typeof m||!["string","number"].includes(typeof p)||typeof p=="number"&&(!Number.isFinite(p)||!Number.isFinite(m)))&&r();let A=p===m?0:p>m?1:-1;return d.op==="gt"?A>0:d.op==="gte"?A>=0:d.op==="lt"?A<0:A<=0}case"in":{let p=f(d.left),m=f(d.right);return n.strict&&(!i(p)||!Array.isArray(m)||m.some(A=>!i(A)||typeof A!=typeof p))&&r(),Array.isArray(m)&&m.includes(p)}case"contains":{let p=f(d.left),m=f(d.right);return n.strict&&!(typeof p=="string"&&typeof m=="string"||Array.isArray(p)&&i(m)&&p.every(A=>i(A)&&typeof A==typeof m))&&r(),Array.isArray(p)?p.includes(m):typeof p=="string"&&p.includes(String(m))}case"and":return d.values.every(p=>s(f(p)));case"or":return d.values.some(p=>s(f(p)));case"not":return!s(f(d.value));case"exists":{let p=a(d.value,c+1,n.strict&&d.value.op==="path");return p!=null}default:throw new Error("WORKFLOW_V2_EXPRESSION_OPERATOR_INVALID")}};return a(e)}var ct=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),Ke=(e,t)=>Object.keys(e).every(n=>t.includes(n)),Zc=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t&&!/[\u0000-\u001f\u007f]/.test(e),Vs=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_.]{0,254}$/.test(e)&&e.split(".").every(t=>!!t&&!["__proto__","prototype","constructor"].includes(t));function Qc(e){let t=4096,n=(o,r)=>--t<0||r>24?!1:o===null||["string","boolean"].includes(typeof o)?!0:typeof o=="number"?Number.isFinite(o):Array.isArray(o)?o.length<=200&&o.every(i=>n(i,r+1)):ct(o)&&Object.keys(o).every(i=>!["__proto__","prototype","constructor"].includes(i)&&Object.getOwnPropertyDescriptor(o,i)?.get===void 0&&n(o[i],r+1));try{return n(e,0)&&new TextEncoder().encode(JSON.stringify(e)).length<=Cr}catch{return!1}}var Ps=e=>{let t=n=>Array.isArray(n)?n.map(t):ct(n)?Object.fromEntries(Object.keys(n).sort().map(o=>[o,t(n[o])])):n;return JSON.stringify(t(e))};function ae(e,t={}){if(e.provider!=="conditional")return[e];if(De(e,typeof t=="number"?{}:t).length)throw new Error("WORKFLOW_CONDITIONAL_BINDING_INVALID");return[...e.cases.map(n=>n.assignee),e.otherwise]}function Xt(e,t,n={}){let o=[];for(let[r,i]of Object.entries(t.bindings)){if(i.provider!=="conditional")continue;let s=De(i,n);if(s.length){o.push(...s.map(a=>`${a}:${r}`));continue}for(let a of Object.values(e.nodes))!("binding"in a)||a.binding!==r||o.push(...Zt(i,{definition:e,nodeId:a.id,frozenDefault:i,releasedSources:{},standardProviders:[]},n).map(d=>`${d}:${r}:${a.id}`))}return[...new Set(o)]}function co(e,t={}){return{bindings:Object.fromEntries(Object.entries(e.bindings).flatMap(([n,o])=>o.provider==="conditional"?ae(o,t).map((r,i)=>[`${n}/leaves/${i}`,r]):[[n,o]]))}}function Ws(e,t=0,n={remaining:1024}){if(--n.remaining<0||t>20)return["WORKFLOW_CONDITIONAL_EXPRESSION_LIMIT"];if(!ct(e))return["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"];let o=r=>Ws(r,t+1,n);return e.op==="literal"?Ke(e,["op","value"])&&Object.hasOwn(e,"value")?[]:["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"]:e.op==="path"?Ke(e,["op","path"])&&Vs(e.path)?[]:["WORKFLOW_CONDITIONAL_PATH_INVALID"]:["and","or"].includes(e.op)?Ke(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=128?e.values.flatMap(o):["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"]:e.op==="exists"?Ke(e,["op","value"])&&ct(e.value)&&e.value.op==="path"?o(e.value):["WORKFLOW_CONDITIONAL_EXISTS_PATH_REQUIRED"]:e.op==="not"?Ke(e,["op","value"])?o(e.value):["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"]:["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&Ke(e,["op","left","right"])?[...o(e.left),...o(e.right)]:["WORKFLOW_CONDITIONAL_EXPRESSION_INVALID"]}function De(e,t={}){if(!Qc(e))return["WORKFLOW_CONDITIONAL_BINDING_LIMIT"];if(!ct(e)||e.provider!=="conditional"||!Ke(e,["provider","cases","otherwise"])||!Array.isArray(e.cases)||e.cases.length<1||e.cases.length>no)return["WORKFLOW_CONDITIONAL_BINDING_INVALID"];let n=[];for(let[o,r]of e.cases.entries()){if(!ct(r)||!Ke(r,["label","when","assignee"])||r.label!==void 0&&!Zc(r.label,160)){n.push(`WORKFLOW_CONDITIONAL_CASE_INVALID:${o}`);continue}n.push(...Ws(r.when).map(i=>`${i}:${o}`),...Lt(r.assignee,t.allowIncomplete).map(i=>`${i}:${o}`))}return n.push(...Lt(e.otherwise,t.allowIncomplete).map(o=>`${o}:otherwise`)),[...new Set(n)]}function el(e){switch(e.kind){case"approval":return[e.onApprove,e.onReject];case"parallel":return[...e.branches.map(t=>t.target),e.join];case"condition":return[...e.branches.map(t=>t.target),e.otherwise];case"handle":case"cc":case"action":case"join":return[e.next];default:return[]}}function $s(e,t,n){let o=new Set,r=[e.startAt];for(;r.length&&o.size<200;){let i=r.shift(),s=e.nodes[i];if(!(i===n||o.has(i)||!s)){if(i===t)return!0;o.add(i),r.push(...el(s))}}return!1}function so(e,t,n){if(!Vs(n)||Object.keys(e.nodes).length>200||!e.nodes[t]||!$s(e,t))return;let o=e.inputSchema,r=n.split("."),i=!0;if(r[0]==="steps"){let s=r[1],a=e.nodes[s];if(a?.kind!=="action"||s===t||$s(e,t,s)||(o=a.outputSchema,r=r.slice(2),!r.length))return}for(let s of r)if(i&&=Array.isArray(o?.required)&&o.required.includes(s),o=ct(o?.properties)&&Object.hasOwn(o.properties,s)?o.properties[s]:void 0,!ct(o))return;return{schema:o,required:i}}var Fs=e=>[...new Set((Array.isArray(e.type)?e.type:[e.type]).map(t=>t==="integer"?"number":typeof t=="string"?t:"unknown"))];function ao(e,t,n,o,r=!1){let i=c=>ao(c,t,n,o),s=()=>{o.push("WORKFLOW_CONDITIONAL_OPERAND_TYPE_INVALID")},a=c=>c.types.every(l=>["string","number","boolean","null"].includes(l)),d=c=>c.types.length===1&&c.types[0]==="boolean";switch(e.op){case"path":{let c=so(t,n,e.path);return c?(!r&&!c.required&&o.push(`WORKFLOW_CONDITIONAL_FACT_OPTIONAL:${e.path}`),{types:Fs(c.schema),...ct(c.schema.items)?{itemTypes:Fs(c.schema.items)}:{}}):(o.push(`WORKFLOW_CONDITIONAL_FACT_UNAVAILABLE:${e.path}`),{types:["unknown"]})}case"literal":{let c=e.value;return{types:[c===null?"null":Array.isArray(c)?"array":typeof c],...Array.isArray(c)?{itemTypes:[...new Set(c.map(l=>l===null?"null":typeof l))]}:{}}}case"exists":return ao(e.value,t,n,o,!0),{types:["boolean"]};case"not":return d(i(e.value))||s(),{types:["boolean"]};case"and":case"or":for(let c of e.values)d(i(c))||s();return{types:["boolean"]};default:{let c=i(e.left),l=i(e.right);if(["eq","neq"].includes(e.op))(!a(c)||!a(l)||!c.types.some(f=>l.types.includes(f)))&&s();else if(["gt","gte","lt","lte"].includes(e.op))(c.types.length!==1||l.types.length!==1||c.types[0]!==l.types[0]||!["number","string"].includes(c.types[0]))&&s();else{let f=e.op==="in"?l:c,p=e.op==="in"?c:l;!(e.op==="contains"&&c.types.length===1&&l.types.length===1&&c.types[0]==="string"&&l.types[0]==="string")&&!(f.types.length===1&&f.types[0]==="array"&&a(p)&&f.itemTypes&&f.itemTypes.every(A=>["string","number","boolean","null"].includes(A)&&p.types.includes(A)))&&s()}return{types:["boolean"]}}}}function tl(e,t){return t.standardProviders.includes(e.provider)?e.provider==="fixed_users"?Ke(e,["provider","users"]):e.provider==="app_role"?Ke(e,["provider","roleCode","roleCodes"]):e.provider==="app_role_in_scope"&&Ke(e,["provider","roleCode","roleCodes","scope"])&&!!e.scope&&!!t.scopeDimensions?.includes(e.scope.dimension):!1}function Zt(e,t,n={}){let o=De(e,n);if(o.length)return o;let r=e,i=t.definition.nodes[t.nodeId];if(!i||i.kind!=="approval"&&i.kind!=="handle")return["WORKFLOW_CONDITIONAL_HUMAN_REQUIRED"];let s=[],a=t.frozenDefault?ae(t.frozenDefault,n):[],d=Object.values(t.releasedSources);for(let[c,l]of[...r.cases.map(f=>f.assignee),r.otherwise].entries())!tl(l,t)&&![...a,...d].some(f=>Ps(f)===Ps(l))&&!io(l,t.peopleSourceTemplates)&&s.push(`WORKFLOW_CONDITIONAL_LEAF_UNRELEASED:${c}`),s.push(...Lr(l,t.definition,t.nodeId).map(f=>f.startsWith("WORKFLOW_CONDITIONAL_LEAF_FACT_UNAVAILABLE:")?`WORKFLOW_CONDITIONAL_LEAF_FACT_UNAVAILABLE:${c}:${f.slice(43)}`:f));for(let[c,l]of r.cases.entries()){let f=[],p=ao(l.when,t.definition,t.nodeId,f);(p.types.length!==1||p.types[0]!=="boolean")&&f.push("WORKFLOW_CONDITIONAL_BOOLEAN_REQUIRED"),s.push(...f.map(m=>`${m}:${c}`))}return[...new Set(s)]}function Nm(e,t,n,o){let r=De(e);if(r.length)throw new Error(r[0]);let i=t.nodes[n];if(!i||!["approval","handle"].includes(i.kind))throw new Error("WORKFLOW_CONDITIONAL_HUMAN_REQUIRED");for(let d of e.cases){let c=[],l=ao(d.when,t,n,c);if((l.types.length!==1||l.types[0]!=="boolean")&&c.push("WORKFLOW_CONDITIONAL_BOOLEAN_REQUIRED"),c.length)throw new Error(c[0])}let s=[],a={strict:!0,schemaForPath:d=>so(t,n,d)?.schema,requiredForPath:d=>so(t,n,d)?.required===!0,onPathRead:(d,c)=>{s.push({path:d,present:c!==void 0,...c!==void 0?{value:c}:{}})}};for(let[d,c]of e.cases.entries()){let l=vs(c.when,o,a);if(typeof l!="boolean")throw new Error("WORKFLOW_CONDITIONAL_BOOLEAN_REQUIRED");if(l)return{assignee:c.assignee,matched:d,...c.label!==void 0?{label:c.label}:{},factReads:s}}return{assignee:e.otherwise,matched:"otherwise",factReads:s}}function Lr(e,t,n){let o=t.nodes[n];if(!o||!("binding"in o))return["WORKFLOW_CONDITIONAL_HUMAN_REQUIRED"];let r=[];if(e.provider==="supervisor_chain"){let s=`$people-validation:${n}`;r.push(...At({...t,nodes:{...t.nodes,[n]:{...o,binding:s}}},{bindings:{[s]:e}}))}let i=[e.inputPath,e.departmentIdFrom,e.selectedInputPath,e.resourceIdFrom,e.scope?.valueFrom,...typeof e.from=="object"?[e.from.field]:[],...Object.values(e.routing?.dimensions||{}).map(s=>s.valueFrom),...Object.values(e.routing?.sources||{}).map(s=>s.scope?.valueFrom)].filter(s=>typeof s=="string");for(let s of i)so(t,n,s)||r.push(`WORKFLOW_CONDITIONAL_LEAF_FACT_UNAVAILABLE:${s}`);return[...new Set(r)]}var Cm=200,nl=["text.short","uuid","option.single","resource-ref.single"],vr=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,js=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Us=new Set(["__proto__","prototype","constructor"]),Pr=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[Object.prototype,null].includes(Object.getPrototypeOf(e)),xs=(e,t)=>Object.keys(e).every(n=>t.includes(n)),Qt=(e,t)=>typeof e=="string"&&e.length>0&&e.trim()===e&&e.length<=t,$t=class extends Error{constructor(n,o){super(`${n}: ${o}`);this.code=n;this.pointer=o}code;pointer};function me(e,t){throw new $t(e,t)}function lo(e,t,n){if(e===void 0)return;["user.single","user.multiple"].includes(t)||me("DATA_USER_CANDIDATES_FIELD_TYPE_INVALID",n),(!Pr(e)||!xs(e,["kind","roleCode","scope","pageSize"])||e.kind!=="app-role"||!Qt(e.roleCode,128)||!vr.test(String(e.roleCode)))&&me("DATA_USER_CANDIDATES_SOURCE_INVALID",n),e.pageSize!==void 0&&(!Number.isSafeInteger(e.pageSize)||Number(e.pageSize)<1||Number(e.pageSize)>50)&&me("DATA_USER_CANDIDATES_PAGE_SIZE_INVALID",`${n}/pageSize`);let o;if(e.scope!==void 0){let r=e.scope;(!Pr(r)||!xs(r,["dimensionCode","operation","field","value","creation"])||!Qt(r.dimensionCode,128)||!vr.test(String(r.dimensionCode))||!Qt(r.operation,64)||!vr.test(String(r.operation))||Object.hasOwn(r,"field")===Object.hasOwn(r,"value"))&&me("DATA_USER_CANDIDATES_SCOPE_INVALID",`${n}/scope`),r.creation!==void 0&&(r.creation!=="prospective"||!Object.hasOwn(r,"field"))&&me("DATA_USER_CANDIDATES_SCOPE_INVALID",`${n}/scope/creation`),Object.hasOwn(r,"field")?((!Qt(r.field,63)||!js.test(String(r.field))||Us.has(String(r.field)))&&me("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${n}/scope/field`),o={dimensionCode:String(r.dimensionCode),operation:String(r.operation),field:String(r.field),...r.creation==="prospective"?{creation:"prospective"}:{}}):(Qt(r.value,255)||me("DATA_USER_CANDIDATES_SCOPE_VALUE_INVALID",`${n}/scope/value`),o={dimensionCode:String(r.dimensionCode),operation:String(r.operation),value:String(r.value)})}return{kind:"app-role",roleCode:String(e.roleCode),...o?{scope:o}:{},...e.pageSize===void 0?{}:{pageSize:Number(e.pageSize)}}}function $r(e){return e.some(t=>t.schema.fields.some(n=>{let o=n.userCandidates?.scope;return o?.creation==="prospective"||!!(o?.field&&t.schema.fields.find(r=>r.code===o.field)?.type==="resource-ref.single")}))}function Ms(e,t,n,o){for(let[r,i]of e.entries()){let s=`${o}/${r}/userCandidates`,a=lo(i.userCandidates,i.type,s);if(a&&(t.has(a.roleCode)||me("DATA_USER_CANDIDATES_ROLE_UNDECLARED",`${s}/roleCode`),a.scope&&!n.has(a.scope.dimensionCode)&&me("DATA_USER_CANDIDATES_DIMENSION_UNDECLARED",`${s}/scope/dimensionCode`),a.scope?.field)){let d=e.find(c=>c.code===a.scope.field);(!d||!nl.some(c=>c===d.type))&&me("DATA_USER_CANDIDATES_SCOPE_FIELD_INVALID",`${s}/scope/field`)}}}function ol(e,t,n,o){let r=e.subject.factProjection,i=typeof t.inputPath=="string"&&Object.entries(r).some(([c,l])=>(t.inputPath===c||t.inputPath.startsWith(`${c}.`))&&n.get(l)?.userCandidates!==void 0);if(t.candidateField===void 0&&!i)return;(t.provider!=="form_field_users"||!t.candidateField||!js.test(t.candidateField)||Us.has(t.candidateField)||!t.inputPath||r[t.inputPath]!==t.candidateField)&&me("WORKFLOW_USER_CANDIDATES_FIELD_BINDING_REQUIRED",o),(t.roleCode!==void 0||t.scope!==void 0||t.routing!==void 0)&&me("WORKFLOW_USER_CANDIDATES_SOURCE_OVERRIDE_FORBIDDEN",o);let s=n.get(t.candidateField),a=s&&lo(s.userCandidates,s.type,`${o}/candidateField`);a||me("WORKFLOW_USER_CANDIDATES_FIELD_UNDECLARED",`${o}/candidateField`);let d;if(a.scope?.field){let c=Object.entries(r).filter(([,l])=>l===a.scope.field).map(([l])=>l);c.length!==1&&me("WORKFLOW_USER_CANDIDATES_SCOPE_PROJECTION_REQUIRED",o),d=c[0]}return{fieldCode:s.code,inputPath:t.inputPath,source:a,...d?{scopeInputPath:d}:{}}}function Bs(e,t,n,o,r=new Map){for(let[i,s]of Object.entries(co(t).bindings))ol(e,s,n,`${o}/${i}`);for(let[i,s]of Object.entries(e.taskPages||{})){let a=new Set(s.fields.filter(d=>d.readonly!==!0).map(d=>d.code));for(let d of s.fields){let c=n.get(d.code)?.userCandidates?.scope;if(a.has(d.code)&&c?.field&&a.has(c.field)&&me("WORKFLOW_USER_CANDIDATES_SCOPE_WRITE_FORBIDDEN",`${o}/taskPages/${i}/${d.code}`),!a.has(d.code)||!d.subtable)continue;let l=n.get(d.code)?.subtable?.resourceCode,f=l?r.get(l):void 0;d.subtable.fields.some(p=>p.readonly!==!0&&f?.get(p.code)?.userCandidates)&&me("WORKFLOW_USER_CANDIDATES_OWNED_FIELD_UNSUPPORTED",`${o}/taskPages/${i}/${d.code}`)}}}function Sm(e,t){if(!e.scope)return;let n=e.scope.field?t[e.scope.field]:e.scope.value,o=Pr(n)?n.value:n;return Qt(o,255)||me("DATA_USER_CANDIDATES_SCOPE_VALUE_REQUIRED",e.scope.field||"scope"),String(o)}var uo=200,Vr=205;function Wr(e,t=[]){return e.some(n=>n.schema.fields.length>100)||t.some(n=>Object.values(n.definition.taskPages||{}).some(o=>(o.fields?.length??0)>64)||[n.launch?.submission?.create,n.launch?.submission?.existing].some(o=>Object.keys(o?.inputs||{}).length>64))}var lt=500,Fr=500,en=1e3,Ks=2*en+16,km=2*1024*1024,Lm=2*1024*1024;function On(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=1&&e<=en}function fo(e){if(e.ownedRowLimit===void 0)return Fr;if(!On(e.ownedRowLimit))throw new Error("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID");return e.ownedRowLimit}function xr(e){return e.some(t=>(t.schema.ownedRowLimit??Fr)>Fr)}function jr(e){return e.some(t=>{let n=t.schema.fields.filter(o=>o.type==="subtable").map(o=>o.subtable?.maxRows??20);return n.some(o=>o>100)||n.reduce((o,r)=>o+r,0)>400})}function vm(e){try{return new TextEncoder().encode(JSON.stringify(e)).byteLength}catch{return 1/0}}var Hs=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Br=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,rl=["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 Kr(e){return e.some(t=>t.schema.fields.some(n=>(n.type==="datetime"||n.type==="datetime-range")&&n.timePrecision==="minute"))}function qr(e){return e.some(t=>t.schema.fields.some(n=>n.type==="subtable"&&(n.subtable?.minRows??0)>0))}var il=new Set(rl),Ys=new Set(["option.multiple","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","subtable"]),qs=new Set(["option.single","option.multiple","cascade.single","cascade.multiple"]),zs=new Set(["resource-ref.single","resource-ref.multiple"]),zr=[{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}],tn=new Map(zr.map(e=>[e.code,e])),We=class extends Error{constructor(n,o){super(n);this.code=n;this.pointer=o;this.name="NativeDataFieldContractV2Error"}code;pointer};function go(e){return Ys.has(e)}function Et(e,t={}){return e.type!=="serial-number"&&t.system!==!0&&e.nullable===!1&&(!go(e.type)||t.requiredHint===!0)}function bn(e,t,n=500){Array.isArray(e)||L("NATIVE_ARRAY_REQUIRED",t),e.length===0&&L("NATIVE_DATA_FIELDS_REQUIRED",t),e.length>n&&L("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let o=new Set;return e.map((r,i)=>{let s=`${t}/${i}`,a=xe(r,s);qe(a,["code","type","nullable","indexed","options","source","userCandidates","maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","timePrecision","file","serial","subtable"],s);let d=ze(a.code,`${s}/code`,63);Hs.test(d)||L("NATIVE_FIELD_CODE_INVALID",`${s}/code`),o.has(d)&&L("NATIVE_DATA_FIELD_DUPLICATE",`${s}/code`),o.add(d);let c=ze(a.type,`${s}/type`,32);il.has(c)||L("NATIVE_DATA_FIELD_TYPE_INVALID",`${s}/type`);let l=c,f=Mr(a.nullable,`${s}/nullable`),p=Mr(a.indexed,`${s}/indexed`);f===!0&&Ys.has(l)&&L("NATIVE_DATA_MULTI_FIELD_NULLABLE_INVALID",`${s}/nullable`);let m=dl(a.options,l,s),A=cl(a.source,l,s),I=lo(a.userCandidates,l,`${s}/userCandidates`),O=ll(a,l,s),b=Mr(a.exactDecimal,`${s}/exactDecimal`);b!==void 0&&l!=="number.decimal"&&L("NATIVE_DATA_FIELD_EXACT_DECIMAL_TYPE_INVALID",`${s}/exactDecimal`);let g=sl(a.rangeBoundary,l,s),y=ul(a.file,l,s),h=fl(a.serial,l,s),u=pl(a.subtable,l,s);return{code:d,type:l,...f===void 0?{}:{nullable:f},...p===void 0?{}:{indexed:p},...m?{options:m}:{},...A?{source:A}:{},...I?{userCandidates:I}:{},...O,...b===void 0?{}:{exactDecimal:b},...g?{rangeBoundary:g}:{},...y?{file:y}:{},...h?{serial:h}:{},...u?{subtable:u}:{}}})}function sl(e,t,n){let o=`${n}/rangeBoundary`;if(!(t==="date-range"||t==="datetime-range")){e!==void 0&&L("NATIVE_DATA_FIELD_RANGE_BOUNDARY_TYPE_INVALID",o);return}return e!=="closed"&&e!=="half-open"&&L("NATIVE_DATA_FIELD_RANGE_BOUNDARY_REQUIRED",o),e}function Xs(e,t){Array.isArray(e)||L("NATIVE_ARRAY_REQUIRED",t);let n=new Map;e.forEach((o,r)=>{let i=`${t}/${r}`,s=xe(o,i),a=ze(s.code,`${i}/code`,64);(!Br.test(a)||n.has(a))&&L("NATIVE_RESOURCE_CODE_INVALID",`${i}/code`);let d=xe(s.schema,`${i}/schema`);d.ownedRowLimit!==void 0&&!On(d.ownedRowLimit)&&L("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${i}/schema/ownedRowLimit`),n.set(a,{pointer:i,ownedRowLimit:fo(d),fields:bn(d.fields,`${i}/schema/fields`)})});for(let[o,r]of n){let i=new Map(r.fields.map(a=>[a.code,a]));r.fields.filter(a=>a.type==="subtable").reduce((a,d)=>a+(d.subtable?.maxRows??20),0)>r.ownedRowLimit&&L("NATIVE_DATA_FIELD_SUBTABLE_AGGREGATE_MAX_ROWS_EXCEEDED",`${r.pointer}/schema/fields`),r.fields.forEach((a,d)=>{let c=`${r.pointer}/schema/fields/${d}`;if(a.source&&al(a.source,i,n,`${c}/source`),a.subtable){let l=n.get(a.subtable.resourceCode);(!l||a.subtable.resourceCode===o)&&L("NATIVE_DATA_FIELD_SUBTABLE_TARGET_MISSING",`${c}/subtable/resourceCode`);let f=l.fields.find(m=>m.code===a.subtable?.foreignKey);(!f||f.type!=="uuid"||f.nullable!==!1)&&L("NATIVE_DATA_FIELD_SUBTABLE_FOREIGN_KEY_INVALID",`${c}/subtable/foreignKey`);let p=l.fields.find(m=>m.code===a.subtable?.orderField);(!p||p.type!=="number.integer"||p.nullable!==!1)&&L("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${c}/subtable/orderField`)}})}}function Zs(e,t,n){if(e===void 0)return[];(!Array.isArray(e)||e.length>20)&&L("NATIVE_DATA_RESOURCE_INVARIANTS_INVALID",n);let o=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,s)=>{let a=`${n}/${s}`,d=xe(i,a);qe(d,["code","message","expression"],a);let c=ze(d.code,`${a}/code`,128);(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(c)||r.has(c))&&L("NATIVE_DATA_RESOURCE_INVARIANT_CODE_INVALID",`${a}/code`),r.add(c);let l=mo(d.message,`${a}/message`,500);l!==void 0&&l.length===0&&L("NATIVE_DATA_RESOURCE_INVARIANT_MESSAGE_INVALID",`${a}/message`);let f=xe(d.expression,`${a}/expression`);if(f.kind==="nonBlankTextWhenOption"){qe(f,["kind","optionField","optionValue","textField"],`${a}/expression`);let g=Qe(f.optionField,`${a}/expression/optionField`),y=Qe(f.textField,`${a}/expression/textField`),h=ze(f.optionValue,`${a}/expression/optionValue`,128),u=o.get(g),E=o.get(y);return(!u||!E)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${a}/expression`),(u.type!=="option.single"||!["text.short","text.long"].includes(E.type)||!u.options?.some(w=>w.value===h))&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${a}/expression`),{code:c,...l===void 0?{}:{message:l},expression:{kind:"nonBlankTextWhenOption",optionField:g,optionValue:h,textField:y}}}qe(f,["leftField","operator","rightField"],`${a}/expression`);let p=Qe(f.leftField,`${a}/expression/leftField`),m=Qe(f.rightField,`${a}/expression/rightField`),A=o.get(p),I=o.get(m);(!A||!I)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_UNKNOWN",`${a}/expression`),A.type===I.type||["number.integer","number.decimal"].includes(A.type)&&["number.integer","number.decimal"].includes(I.type)||L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${a}/expression`);let b=String(f.operator);return["eq","neq","gt","gte","lt","lte"].includes(b)||L("NATIVE_DATA_RESOURCE_INVARIANT_OPERATOR_INVALID",`${a}/expression/operator`),!["eq","neq"].includes(b)&&!["number.integer","number.decimal","date","time","datetime","text.short","text.long","text.rich","serial-number","uuid"].includes(A.type)&&L("NATIVE_DATA_RESOURCE_INVARIANT_FIELD_TYPES_INVALID",`${a}/expression`),{code:c,...l===void 0?{}:{message:l},expression:{leftField:p,operator:b,rightField:m}}})}function al(e,t,n,o){let r=n.get(e.resourceCode);r||L("NATIVE_DATA_FIELD_SOURCE_TARGET_MISSING",`${o}/resourceCode`);let i=new Map(r.fields.map(a=>[a.code,a])),s=i.get(e.labelField);(!s||!["text.short","text.long"].includes(s.type))&&L("NATIVE_DATA_FIELD_SOURCE_LABEL_INVALID",`${o}/labelField`);for(let a of["searchFields","descriptionFields","snapshotFields"])for(let d of e[a]||[])i.has(d)||L("NATIVE_DATA_FIELD_SOURCE_FIELD_MISSING",`${o}/${a}`);for(let[a,d]of(e.filterWhere||[]).entries())i.has(d.field)||L("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${o}/filterWhere/${a}/field`);for(let[a,d]of(e.filters||[]).entries())i.has(d.field)||L("NATIVE_DATA_FIELD_SOURCE_FILTER_FIELD_MISSING",`${o}/filters/${a}/field`),"binding"in d&&!t.has(d.binding.field)&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_FIELD_MISSING",`${o}/filters/${a}/binding/field`)}function dl(e,t,n){let o=`${n}/options`;if(e===void 0){qs.has(t)&&L("NATIVE_DATA_FIELD_OPTIONS_REQUIRED",o);return}(!qs.has(t)||!Array.isArray(e))&&L("NATIVE_DATA_FIELD_OPTIONS_TYPE_INVALID",o),(e.length<1||e.length>100)&&L("NATIVE_DATA_FIELD_OPTIONS_INVALID",o);let r=0,i=(s,a,d)=>{d>5&&L("NATIVE_DATA_FIELD_OPTIONS_DEPTH_EXCEEDED",a);let c=new Set;return s.map((l,f)=>{r+=1,r>1e3&&L("NATIVE_DATA_FIELD_OPTIONS_COUNT_EXCEEDED",o);let p=`${a}/${f}`,m=xe(l,p);qe(m,["label","value","description","color","children"],p);let A=ze(m.label,`${p}/label`,500),I=ze(m.value,`${p}/value`,500);c.has(I)&&L("NATIVE_DATA_FIELD_OPTION_VALUE_DUPLICATE",`${p}/value`),c.add(I);let O=mo(m.description,`${p}/description`,2e3),b=mo(m.color,`${p}/color`,64),g;return m.children!==void 0&&((!t.startsWith("cascade.")||!Array.isArray(m.children))&&L("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),(m.children.length<1||m.children.length>100)&&L("NATIVE_DATA_FIELD_OPTION_CHILDREN_INVALID",`${p}/children`),g=i(m.children,`${p}/children`,d+1)),{label:A,value:I,...O===void 0?{}:{description:O},...b===void 0?{}:{color:b},...g?{children:g}:{}}})};return i(e,o,1)}function cl(e,t,n){let o=`${n}/source`;if(e===void 0){zs.has(t)&&L("NATIVE_DATA_FIELD_SOURCE_REQUIRED",o);return}zs.has(t)||L("NATIVE_DATA_FIELD_SOURCE_TYPE_INVALID",o);let r=xe(e,o);qe(r,["kind","resourceCode","labelField","searchFields","descriptionFields","snapshotFields","filters","filterWhere","pageSize","loadMode","clearOnBindingChange"],o),r.kind!=="resource"&&L("NATIVE_DATA_FIELD_SOURCE_KIND_INVALID",`${o}/kind`);let i=ze(r.resourceCode,`${o}/resourceCode`,64);Br.test(i)||L("NATIVE_RESOURCE_CODE_INVALID",`${o}/resourceCode`);let s=Qe(r.labelField,`${o}/labelField`),a=Ur(r.searchFields,`${o}/searchFields`,10),d=Ur(r.descriptionFields,`${o}/descriptionFields`,10),c=Ur(r.snapshotFields,`${o}/snapshotFields`,50),l=Ft(r.pageSize,`${o}/pageSize`,1,100),f;r.loadMode!==void 0&&(["search","all"].includes(String(r.loadMode))||L("NATIVE_DATA_FIELD_SOURCE_LOAD_MODE_INVALID",`${o}/loadMode`),f=r.loadMode);let p=Gs(r.filters,`${o}/filters`),m=Gs(r.filterWhere,`${o}/filterWhere`,!1);return r.clearOnBindingChange!==void 0&&typeof r.clearOnBindingChange!="boolean"&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_RESET_INVALID",`${o}/clearOnBindingChange`),{kind:"resource",resourceCode:i,labelField:s,...a?{searchFields:a}:{},...d?{descriptionFields:d}:{},...c?{snapshotFields:c}:{},...p?{filters:p}:{},...m?{filterWhere:m}:{},...l===void 0?{}:{pageSize:l},...f?{loadMode:f}:{},...r.clearOnBindingChange===void 0?{}:{clearOnBindingChange:r.clearOnBindingChange}}}function Gs(e,t,n=!0){if(e!==void 0)return(!Array.isArray(e)||e.length>20)&&L("NATIVE_DATA_FIELD_SOURCE_FILTERS_INVALID",t),e.map((o,r)=>{let i=`${t}/${r}`,s=xe(o,i),a=Object.prototype.hasOwnProperty.call(s,"value"),d=Object.prototype.hasOwnProperty.call(s,"binding");qe(s,a?["field","operator","value"]:["field","operator","binding"],i),(a===d||d&&!n)&&L("NATIVE_DATA_FIELD_SOURCE_FILTER_VALUE_INVALID",i);let c=Qe(s.field,`${i}/field`);["eq","in"].includes(String(s.operator))||L("NATIVE_DATA_FIELD_SOURCE_FILTER_OPERATOR_INVALID",`${i}/operator`);let l=s.operator;if(a)return{field:c,operator:l,value:s.value};let f=xe(s.binding,`${i}/binding`);return qe(f,["kind","field"],`${i}/binding`),f.kind!=="field"&&L("NATIVE_DATA_FIELD_SOURCE_BINDING_KIND_INVALID",`${i}/binding/kind`),{field:c,operator:l,binding:{kind:"field",field:Qe(f.field,`${i}/binding/field`)}}})}function ll(e,t,n){let o={};if(e.maxLength!==void 0&&(["text.short","text.long","text.rich"].includes(t)||L("NATIVE_DATA_FIELD_MAX_LENGTH_TYPE_INVALID",`${n}/maxLength`),o.maxLength=po(e.maxLength,`${n}/maxLength`,1,1e6)),(e.precision!==void 0||e.scale!==void 0)&&((t!=="number.decimal"||e.precision===void 0)&&L("NATIVE_DATA_FIELD_DECIMAL_CONFIG_INVALID",n),o.precision=po(e.precision,`${n}/precision`,1,1e3),o.scale=e.scale===void 0?0:po(e.scale,`${n}/scale`,0,o.precision)),e.min!==void 0||e.max!==void 0){["number.integer","number.decimal"].includes(t)||L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_TYPE_INVALID",n);let r=Js(e.min,`${n}/min`),i=Js(e.max,`${n}/max`);t==="number.integer"&&[r,i].some(s=>s!==void 0&&!Number.isSafeInteger(s))&&L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",n),r!==void 0&&i!==void 0&&r>i&&L("NATIVE_DATA_FIELD_NUMERIC_BOUNDS_INVALID",n),r!==void 0&&(o.min=r),i!==void 0&&(o.max=i)}return e.timePrecision!==void 0&&((!["time","datetime","datetime-range"].includes(t)||!["minute","second"].includes(e.timePrecision))&&L("NATIVE_DATA_FIELD_TIME_PRECISION_INVALID",`${n}/timePrecision`),o.timePrecision=e.timePrecision),o}function ul(e,t,n){if(e===void 0)return;let o=`${n}/file`;["file","image","signature"].includes(t)||L("NATIVE_DATA_FIELD_FILE_TYPE_INVALID",o);let r=xe(e,o);qe(r,["maxCount","maxSizeMb","accept"],o);let i=Ft(r.maxCount,`${o}/maxCount`,1,100);t==="signature"&&i!==void 0&&i!==1&&L("NATIVE_DATA_FIELD_SIGNATURE_COUNT_INVALID",`${o}/maxCount`);let s=Ft(r.maxSizeMb,`${o}/maxSizeMb`,1,1024),a;return r.accept!==void 0&&((!Array.isArray(r.accept)||r.accept.length>50)&&L("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${o}/accept`),a=r.accept.map((d,c)=>ze(d,`${o}/accept/${c}`,255)),new Set(a).size!==a.length&&L("NATIVE_DATA_FIELD_FILE_ACCEPT_INVALID",`${o}/accept`)),{...i===void 0?{}:{maxCount:i},...s===void 0?{}:{maxSizeMb:s},...a===void 0?{}:{accept:a}}}function fl(e,t,n){let o=`${n}/serial`;if(e===void 0){t==="serial-number"&&L("NATIVE_DATA_FIELD_SERIAL_REQUIRED",o);return}t!=="serial-number"&&L("NATIVE_DATA_FIELD_SERIAL_TYPE_INVALID",o);let r=xe(e,o);qe(r,["prefix","digits","start"],o);let i=mo(r.prefix,`${o}/prefix`,64),s=Ft(r.digits,`${o}/digits`,1,32),a=Ft(r.start,`${o}/start`,0,Number.MAX_SAFE_INTEGER);return{...i===void 0?{}:{prefix:i},...s===void 0?{}:{digits:s},...a===void 0?{}:{start:a}}}function pl(e,t,n){let o=`${n}/subtable`;if(e===void 0){t==="subtable"&&L("NATIVE_DATA_FIELD_SUBTABLE_REQUIRED",o);return}t!=="subtable"&&L("NATIVE_DATA_FIELD_SUBTABLE_TYPE_INVALID",o);let r=xe(e,o);qe(r,["resourceCode","foreignKey","orderField","minRows","maxRows"],o);let i=ze(r.resourceCode,`${o}/resourceCode`,64);Br.test(i)||L("NATIVE_RESOURCE_CODE_INVALID",`${o}/resourceCode`);let s=Qe(r.foreignKey,`${o}/foreignKey`),a=Qe(r.orderField,`${o}/orderField`);a===s&&L("NATIVE_DATA_FIELD_SUBTABLE_ORDER_FIELD_INVALID",`${o}/orderField`);let d=Ft(r.maxRows,`${o}/maxRows`,1,lt),c=Ft(r.minRows,`${o}/minRows`,0,lt);return(c??0)>(d??20)&&L("NATIVE_DATA_FIELD_SUBTABLE_MIN_ROWS_INVALID",`${o}/minRows`),{resourceCode:i,foreignKey:s,orderField:a,...c===void 0?{}:{minRows:c},...d===void 0?{}:{maxRows:d}}}function Ur(e,t,n){if(e===void 0)return;(!Array.isArray(e)||e.length>n)&&L("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t);let o=e.map((r,i)=>Qe(r,`${t}/${i}`));return new Set(o).size!==o.length&&L("NATIVE_DATA_FIELD_SOURCE_FIELDS_INVALID",t),o}function Qe(e,t){let n=ze(e,t,63);return Hs.test(n)||L("NATIVE_FIELD_CODE_INVALID",t),n}function xe(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&L("NATIVE_OBJECT_REQUIRED",t),e}function qe(e,t,n){let o=new Set(t);for(let r of Object.keys(e))o.has(r)||L("NATIVE_PROPERTY_UNKNOWN",`${n}/${r}`)}function ze(e,t,n){return(typeof e!="string"||e.length===0||e.length>n)&&L("NATIVE_STRING_INVALID",t),e}function mo(e,t,n){if(e!==void 0)return(typeof e!="string"||e.length>n)&&L("NATIVE_STRING_INVALID",t),e}function Mr(e,t){if(e!==void 0)return typeof e!="boolean"&&L("NATIVE_BOOLEAN_REQUIRED",t),e}function Ft(e,t,n,o){if(e!==void 0)return po(e,t,n,o)}function Js(e,t){if(e!==void 0)return(typeof e!="number"||!Number.isFinite(e))&&L("NATIVE_NUMBER_REQUIRED",t),e}function po(e,t,n,o){return(!Number.isSafeInteger(e)||Number(e)<n||Number(e)>o)&&L("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function L(e,t){throw new We(e,t)}var _o=["created_by","updated_by","created_at","updated_at"];function Vt(e){return _o.includes(e)}function Qs(e){return _o.some(t=>Object.prototype.hasOwnProperty.call(e.fieldPolicies||{},t))}var ml=zr.map(e=>e.code);function Ao(e){return ml.includes(e)}var gl=["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"],_l=new Set(gl);function jm(e){return _l.has(String(e))}var Gr=["eq","neq","contains","startsWith","endsWith","in","isEmpty","isNotEmpty"],hn=["eq","neq","gt","gte","lt","lte","between","in","isEmpty"],Al=["eq","neq","in","isEmpty"],Eo=["eq","neq","in","isEmpty","isNotEmpty"],nn=["has","hasAny","hasAll","isEmpty","isNotEmpty"],ea=["overlaps","contains","containedBy","isEmpty"],Jr=["jsonContains","isEmpty","isNotEmpty"],Hr=["isEmpty","isNotEmpty"],El={"text.short":Gr,"text.long":Gr,"text.rich":Gr,"number.integer":hn,"number.decimal":hn,boolean:Al,date:hn,time:hn,datetime:hn,"date-range":ea,"datetime-range":ea,"option.single":Eo,"option.multiple":nn,"cascade.single":nn,"cascade.multiple":nn,"user.single":Eo,"user.multiple":nn,"department.single":Eo,"department.multiple":nn,"resource-ref.single":Eo,"resource-ref.multiple":nn,file:Hr,image:Hr,signature:Hr,address:Jr,location:Jr,uuid:["eq","neq","in","isEmpty"],json:Jr,"serial-number":["eq","neq","in","contains","startsWith"],subtable:[]},Il=new Set(["text.short","text.long","text.rich","option.single","user.single","department.single","resource-ref.single","serial-number"]),yl=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image","signature","address","location","json","subtable"]);function na(e){return El[e]}function Um(e,t){return na(e).includes(t)}function Yr(e){return Il.has(e)}function Nn(e){return!yl.has(e)}function oa(e){return na(e).length>0}var ta=new Set(["number.integer","number.decimal"]),ra=new Set(["text.short","text.long","number.integer","number.decimal","date","time","datetime","serial-number"]),Ol=new Set([...ra,"boolean","uuid"]),bl=new Set(["option.single","user.single","department.single","resource-ref.single"]);function Mm(e,t){return t==="sum"||t==="avg"?ta.has(e)?{valueExpression:"column",numericResult:!0}:null:t==="min"||t==="max"?ra.has(e)?{valueExpression:"column",numericResult:ta.has(e)}:null:bl.has(e)?{valueExpression:"snapshot-value",numericResult:!0}:Ol.has(e)?{valueExpression:"column",numericResult:!0}:null}var Zr=["version","maxBytes","fields"];function sa(e,t){if(e===void 0)return;let n=Xr(e,t);ia(n,Zr,t);let o=Io(n.version,`${t}/version`,1,1e6),r=Io(n.maxBytes,`${t}/maxBytes`,2,196608);(!o||!r)&&we("NATIVE_DATA_DRAFT_STATE_SCHEMA_INVALID",t);let i=Xr(n.fields,`${t}/fields`),s=Object.entries(i);(!s.length||s.length>50)&&we("NATIVE_DATA_DRAFT_STATE_FIELDS_INVALID",`${t}/fields`);for(let[a,d]of s){let c=`${t}/fields/${a}`;/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(a)||we("NATIVE_DATA_DRAFT_STATE_FIELD_CODE_INVALID",c);let l=Xr(d,c),f=aa(l.type,`${c}/type`,32),p=f==="string"?["type","required","maxLength","enum"]:f==="json.object"?["type","required","maxBytes"]:["type","required"];if(["string","number","integer","boolean","json.object"].includes(f)||we("NATIVE_DATA_DRAFT_STATE_FIELD_TYPE_INVALID",`${c}/type`),ia(l,p,c),Nl(l.required,`${c}/required`),f==="string"){let m=Io(l.maxLength,`${c}/maxLength`,1,196608);m||we("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c),l.enum!==void 0&&hl(l.enum,`${c}/enum`,100,!1).some(I=>I.length>m)&&we("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",`${c}/enum`)}else if(f==="json.object"){let m=Io(l.maxBytes,`${c}/maxBytes`,2,65536);(!m||m>r)&&we("NATIVE_DATA_DRAFT_STATE_FIELD_INVALID",c)}}}function hl(e,t,n,o){(!Array.isArray(e)||!o&&e.length===0||e.length>n)&&we("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,s)=>aa(i,`${t}/${s}`,255));return new Set(r).size!==r.length&&we("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function Xr(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&we("NATIVE_OBJECT_REQUIRED",t),e}function ia(e,t,n){let o=new Set(t);for(let r of Object.keys(e))o.has(r)||we("NATIVE_PROPERTY_UNKNOWN",`${n}/${r}`)}function aa(e,t,n){return(typeof e!="string"||e.length===0||e.length>n)&&we("NATIVE_STRING_INVALID",t),e}function Nl(e,t){e!==void 0&&typeof e!="boolean"&&we("NATIVE_BOOLEAN_REQUIRED",t)}function Io(e,t,n,o){return(!Number.isSafeInteger(e)||Number(e)<n||Number(e)>o)&&we("NATIVE_INTEGER_INVALID",t),Number(e)}function we(e,t){throw new We(e,t)}var wl=500,It={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:Zr,mobile:["enabled"]},Rl={"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 ti(e,t,n){if(e===void 0)return;let o=be(e,n);et(o,It.surface,n);let r=o.mutationOwner===void 0?"native":ut(o.mutationOwner,`${n}/mutationOwner`,16);["native","action","readonly","workflow","queued-command"].includes(r)||j("NATIVE_DATA_SURFACE_MUTATION_OWNER_INVALID",`${n}/mutationOwner`);let i=o.generated===void 0?{}:be(o.generated,`${n}/generated`);et(i,It.generated,`${n}/generated`);for(let d of It.generated)ei(i[d],`${n}/generated/${d}`);if(r!=="native")for(let d of["create","update","delete"])i[d]===!0&&j("NATIVE_DATA_SURFACE_MUTATION_OWNER_CONFLICT",`${n}/generated/${d}`);let s=new Map(t.map(d=>[d.code,d])),a=be(o.fields,`${n}/fields`);for(let d of Object.keys(a))s.has(d)||j("NATIVE_DATA_SURFACE_FIELD_MISSING",`${n}/fields/${d}`);for(let d of t)Object.prototype.hasOwnProperty.call(a,d.code)||j("NATIVE_DATA_SURFACE_FIELD_REQUIRED",`${n}/fields/${d.code}`),Cl(a[d.code],d,`${n}/fields/${d.code}`);for(let d of["create","update"]){let c=i[d]??r==="native",l=t.some(f=>{let p=be(a[f.code],`${n}/fields/${f.code}`);return ca(f,p,d)});c&&!l&&j("NATIVE_DATA_SURFACE_WRITABLE_FIELDS_REQUIRED",`${n}/generated/${d}`)}if(Sl(o.list,s,`${n}/list`),da(o.form,s,`${n}/form`,"form"),da(o.detail,s,`${n}/detail`,"detail"),o.mobile!==void 0){let d=be(o.mobile,`${n}/mobile`);et(d,It.mobile,`${n}/mobile`),ei(d.enabled,`${n}/mobile/enabled`)}Tl(o,t,n)}function ni(e,t){let n=e.views?.find(r=>r.code===t);n||j("NATIVE_DATA_VIEW_NOT_FOUND",`/surface/views/${t}`);let o=new Map((n.sections||[]).flatMap(r=>r.fields.map(i=>[i,r.title])));return{mutationOwner:e.mutationOwner||"native",generated:n.generated,list:n.list,form:n.form,detail:n.detail,mobile:n.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([r,i])=>{let s={...i};delete s.section;let a=o.get(r);return[r,{...s,...a?{section:a}:{},list:n.list.fieldOrder.includes(r)}]}))}}function Tl(e,t,n){if(e.views===void 0)return;(!Array.isArray(e.views)||e.views.length>20)&&j("NATIVE_DATA_VIEWS_LIMIT_INVALID",`${n}/views`);let o=new Set;e.views.forEach((r,i)=>{let s=`${n}/views/${i}`,a=be(r,s);et(a,["code","name","generated","list","form","detail","mobile","sections"],s);let d=ut(a.code,`${s}/code`,64);(!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(d)||o.has(d))&&j("NATIVE_DATA_VIEW_CODE_INVALID",`${s}/code`),o.add(d),ut(a.name,`${s}/name`,255),be(a.generated,`${s}/generated`),be(a.mobile,`${s}/mobile`);for(let l of["list","detail","create","update","delete"])typeof a.generated[l]!="boolean"&&j("NATIVE_DATA_VIEW_OPERATION_INVALID",`${s}/generated/${l}`);typeof a.mobile.enabled!="boolean"&&j("NATIVE_DATA_VIEW_MOBILE_INVALID",`${s}/mobile/enabled`);for(let l of["list","form","detail"]){let f=be(a[l],`${s}/${l}`),p=on(f.fieldOrder,`${s}/${l}/fieldOrder`,500,!0);for(let m of p){let A=e.fields[m];(!A||(A.hidden??A.system)===!0)&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${s}/${l}/fieldOrder`)}}if(a.sections!==void 0){(!Array.isArray(a.sections)||a.sections.length>100)&&j("NATIVE_DATA_VIEW_SECTIONS_INVALID",`${s}/sections`);let l=new Set;a.sections.forEach((f,p)=>{let m=`${s}/sections/${p}`,A=be(f,m);et(A,["title","fields"],m),ut(A.title,`${m}/title`,255);for(let I of on(A.fields,`${m}/fields`,100,!0)){let O=e.fields[I];(!O||(O.hidden??O.system)===!0||l.has(I))&&j("NATIVE_DATA_VIEW_FIELD_INVALID",`${m}/fields`),l.add(I)}})}let c=ni(e,d);if(ti(c,t,s),a.generated.create!==!1&&(e.mutationOwner||"native")==="native")for(let l of t)Et(l,e.fields[l.code])&&ca(l,e.fields[l.code],"create")&&!a.form.fieldOrder.includes(l.code)&&j("NATIVE_DATA_VIEW_CREATE_REQUIRED_FIELD_MISSING",`${s}/form/fieldOrder`)})}function ca(e,t,n){if(e.type==="serial-number"||t.system===!0)return!1;let o=t[`${n}Capabilities`];return Array.isArray(o)&&o.length>0}function Cl(e,t,n){let o=be(e,n);et(o,It.field,n),ut(o.label,`${n}/label`,500),o.type!==t.type&&j("NATIVE_DATA_SURFACE_FIELD_TYPE_MISMATCH",`${n}/type`);let r=ut(o.widget,`${n}/widget`,64);Rl[t.type].includes(r)||j("NATIVE_DATA_SURFACE_WIDGET_INCOMPATIBLE",`${n}/widget`),Ll(o.section,`${n}/section`,255);for(let i of["requiredHint","system","hidden","list","searchable","sortable"])ei(o[i],`${n}/${i}`);o.searchable===!0&&!Yr(t.type)&&j("NATIVE_DATA_SURFACE_SEARCH_UNSUPPORTED",`${n}/searchable`),o.sortable===!0&&!Nn(t.type)&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${n}/sortable`);for(let i of["readCapabilities","createCapabilities","updateCapabilities"])on(o[i],`${n}/${i}`,100,!0);if(o.maxCount!==void 0&&(!Number.isSafeInteger(o.maxCount)||Number(o.maxCount)<1||Number(o.maxCount)>100)&&j("NATIVE_DATA_SURFACE_MAX_COUNT_INVALID",`${n}/maxCount`),o.maxSizeMb!==void 0&&(!Number.isSafeInteger(o.maxSizeMb)||Number(o.maxSizeMb)<1||Number(o.maxSizeMb)>1024)&&j("NATIVE_DATA_SURFACE_MAX_SIZE_INVALID",`${n}/maxSizeMb`),o.accept!==void 0){let i=Array.isArray(o.accept)?o.accept:[o.accept];on(i,`${n}/accept`,50,!1)}for(let i of["maxLength","precision","scale","exactDecimal","min","max","rangeBoundary","options","source","userCandidates","timePrecision","serial","subtable"])Dl(o,t,i,n);kl(o,t,n)}function Sl(e,t,n){if(e===void 0)return;let o=be(e,n);if(et(o,It.list,n),o.actions!==void 0){let r=be(o.actions,`${n}/actions`);et(r,["import","export"],`${n}/actions`);for(let i of["import","export"])r[i]!==void 0&&typeof r[i]!="boolean"&&j("NATIVE_DATA_SURFACE_LIST_ACTION_INVALID",`${n}/actions/${i}`)}if(o.fieldOrder!==void 0)for(let r of on(o.fieldOrder,`${n}/fieldOrder`,500,!0))t.has(r)||j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${n}/fieldOrder`);o.defaultPageSize!==void 0&&(!Number.isSafeInteger(o.defaultPageSize)||Number(o.defaultPageSize)<1||Number(o.defaultPageSize)>200)&&j("NATIVE_DATA_SURFACE_PAGE_SIZE_INVALID",`${n}/defaultPageSize`);for(let[r,i]of[["searchableFields",Yr],["filterFields",oa]]){if(o[r]===void 0)continue;let s=on(o[r],`${n}/${r}`,100,!0);for(let a of s){let d=t.get(a);(!d||!i(d.type))&&j("NATIVE_DATA_SURFACE_LIST_FIELD_INVALID",`${n}/${r}`)}}if(o.defaultSort!==void 0){let r=be(o.defaultSort,`${n}/defaultSort`);et(r,It.defaultSort,`${n}/defaultSort`);let i=ut(r.field,`${n}/defaultSort/field`,63),s=t.get(i);!Ao(i)&&(!s||!Nn(s.type))&&j("NATIVE_DATA_SURFACE_SORT_UNSUPPORTED",`${n}/defaultSort/field`),r.order!==void 0&&!["asc","desc"].includes(r.order)&&j("NATIVE_DATA_SURFACE_SORT_ORDER_INVALID",`${n}/defaultSort/order`)}}function da(e,t,n,o){if(e===void 0)return;let r=be(e,n);if(et(r,It[o],n),r.layout!==void 0&&!["flat","sections"].includes(r.layout)&&j("NATIVE_DATA_SURFACE_LAYOUT_INVALID",`${n}/layout`),r.fieldOrder!==void 0){let i=`${n}/fieldOrder`;(!Array.isArray(r.fieldOrder)||r.fieldOrder.length>t.size||r.fieldOrder.length>wl)&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i);let s=r.fieldOrder.map((a,d)=>ut(a,`${i}/${d}`,63));new Set(s).size!==s.length&&j("NATIVE_DATA_SURFACE_FIELD_ORDER_INVALID",i),s.forEach((a,d)=>{t.has(a)||j("NATIVE_DATA_SURFACE_FIELD_ORDER_FIELD_MISSING",`${i}/${d}`)})}o==="form"&&sa(r.draftState,`${n}/draftState`)}function Dl(e,t,n,o){e[n]===void 0&&t[n]===void 0||((e[n]===void 0||t[n]===void 0)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${n}`),re(e[n])!==re(t[n])&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${o}/${n}`))}function kl(e,t,n){let o=t.file||{},r={...e.maxCount===void 0?{}:{maxCount:e.maxCount},...e.maxSizeMb===void 0?{}:{maxSizeMb:e.maxSizeMb},...e.accept===void 0?{}:{accept:Qr(e.accept)}};for(let i of["maxCount","maxSizeMb","accept"]){if(r[i]===void 0&&o[i]===void 0)continue;(r[i]===void 0||o[i]===void 0)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${i}`);let s=i==="accept"?Qr(r[i]):r[i],a=i==="accept"?Qr(o[i]):o[i];re(s)!==re(a)&&j("NATIVE_DATA_SURFACE_FIELD_PROJECTION_MISMATCH",`${n}/${i}`)}}function Qr(e){return(Array.isArray(e)?[...e]:[e]).sort((t,n)=>{let o=String(t),r=String(n);return o===r?0:o<r?-1:1})}function on(e,t,n,o){(!Array.isArray(e)||!o&&e.length===0||e.length>n)&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t);let r=e.map((i,s)=>ut(i,`${t}/${s}`,255));return new Set(r).size!==r.length&&j("NATIVE_DATA_SURFACE_STRING_ARRAY_INVALID",t),r}function be(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&j("NATIVE_OBJECT_REQUIRED",t),e}function et(e,t,n){let o=new Set(t);for(let r of Object.keys(e))o.has(r)||j("NATIVE_PROPERTY_UNKNOWN",`${n}/${r}`)}function ut(e,t,n){return(typeof e!="string"||e.length===0||e.length>n)&&j("NATIVE_STRING_INVALID",t),e}function Ll(e,t,n){e!==void 0&&(typeof e!="string"||e.length>n)&&j("NATIVE_STRING_INVALID",t)}function ei(e,t){e!==void 0&&typeof e!="boolean"&&j("NATIVE_BOOLEAN_REQUIRED",t)}function j(e,t){throw new We(e,t)}var wn=class extends Error{constructor(n,o){super(`${n}: ${o}`);this.pointer=n;this.reason=o}pointer;reason;code="NATIVE_MANAGED_CONCURRENCY_INVALID"};function la(e,t,n){if(e===void 0)return;let o=(g,y)=>{throw new wn(g,y)},r=(g,y,h)=>((!g||typeof g!="object"||Array.isArray(g)||Object.keys(g).some(u=>!h.includes(u)))&&o(y,"object contains unsupported properties"),g),i=(g,y,h,u)=>{(!Number.isSafeInteger(g)||g<y||g>h)&&o(u,`expected integer ${y}..${h}`)},s=(g,y)=>{(typeof g!="string"||!/^[a-z][a-z0-9_-]{0,63}$/.test(g))&&o(y,"invalid code")},a=(g,y,h)=>((!Array.isArray(g)||g.length>y)&&o(h,"array exceeds bound"),g),d=(g,y)=>{let h=t.find(u=>u.code===g);return h||o(y,"unknown resource"),h},c=(g,y,h)=>{let u=g.schema.fields.find(E=>E.code===y);return!u&&y!=="id"&&o(h,"unknown field"),u},l=(g,y,h=!1)=>{r(g,y,Object.keys(g||{})),Object.keys(g).length>8&&o(y,"at most eight parameters");for(let[u,E]of Object.entries(g))if(s(u,y),r(E,y,["type","values","minimum","maximum","minLength","maxLength"]),E.type==="uuid")Object.keys(E).length!==1&&o(y,"uuid has no options");else if(h&&E.type==="boolean")r(E,y,["type"]);else if(h&&E.type==="string"&&E.values===void 0)r(E,y,["type","minLength","maxLength"]),i(E.maxLength,1,256,y),E.minLength!==void 0&&i(E.minLength,0,E.maxLength,y);else if(E.type==="string"){r(E,y,["type","values"]);let w=a(E.values,100,y);(!w.length||w.some(S=>typeof S!="string"||S.length>128)||new Set(w).size!==w.length)&&o(y,"finite string values required")}else E.type==="integer"?(r(E,y,["type","minimum","maximum"]),i(E.minimum,0,1e6,y),i(E.maximum,E.minimum,E.minimum+1e3,y)):o(y,"unsupported parameter type")},f=(g,y,h,u=!1)=>{r(g,h,["from","key","value"]),!(g.from==="input"&&Object.keys(g).length===2&&Object.hasOwn(y,g.key))&&((g.from==="actor"||u&&g.from==="allocation")&&Object.keys(g).length===1||g.from==="literal"&&Object.keys(g).length===2&&Object.hasOwn(g,"value")&&(g.value===null||["string","boolean"].includes(typeof g.value)||typeof g.value=="number"&&Number.isFinite(g.value))&&JSON.stringify(g.value).length<=512||o(h,"invalid binding"))},p=(g,y,h)=>{f(g,y,h),!(g.from==="input"&&y[g.key].type==="uuid")&&(g.from==="literal"&&typeof g.value=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(g.value)||o(h,"record and allocation identifiers require a UUID binding"))},m=(g,y,h)=>{f(g,y,h),!(g.from==="input"&&y[g.key].type==="integer"&&y[g.key].minimum>=1)&&(g.from==="literal"&&Number.isSafeInteger(g.value)&&g.value>=1||o(h,"expectedRevision requires a positive integer binding"))},A="/data/concurrency";JSON.stringify(e).length>131072&&o(A,"declaration exceeds 128 KiB");let I=r(e,A,["version","admission","reads","quotas","commands"]);I.version!==1&&o(A,"unsupported version"),r(I.admission,A,["perSecond","burst","maxInFlight"]),i(I.admission.perSecond,1,1e3,A),i(I.admission.burst,1,1e3,A),i(I.admission.maxInFlight,1,1e3,A);let O=(g,y)=>{let h=new Set;for(let u of g)s(u?.code,y),h.has(u.code)&&o(y,"duplicate code"),h.add(u.code)};O(a(I.reads,32,A),A),O(a(I.quotas,16,A),A),O(a(I.commands,32,A),A);for(let g of I.reads){let y=`${A}/reads/${g.code}`;r(g,y,["code","resourceCode","parameters","select","where","limit","scope","freshSeconds","staleSeconds","maxKeys","sourcePerSecond","dependencies"]);let h=d(g.resourceCode,y);l(g.parameters,y),["subject","application"].includes(g.scope)||o(y,"invalid cache scope"),g.scope==="application"&&h.dataPolicyCode&&o(y,"shared cache cannot bypass a row policy");let u=a(g.select,32,y);u.length||o(y,"select required"),u.forEach(w=>c(h,w,y));let E=a(g.dependencies,64,y);E.forEach(w=>c(h,w,y));for(let w of a(g.where||[],8,y))r(w,y,["field","value"]),c(h,w.field,y),f(w.value,g.parameters,y),g.scope==="application"&&w.value.from==="actor"&&o(y,"actor requires subject cache"),E.includes(w.field)||o(y,"filter dependency missing");u.some(w=>!E.includes(w))&&o(y,"selected field dependency missing"),i(g.limit,1,100,y),i(g.freshSeconds,1,300,y),i(g.staleSeconds,0,300,y),i(g.maxKeys,1,1e4,y),i(g.sourcePerSecond,1,20,y)}for(let g of I.quotas){let y=`${A}/quotas/${g.code}`;r(g,y,["code","sourceResource","capacityField","allocationResource","allocationField","reservationSeconds"]);let h=d(g.sourceResource,y),u=d(g.allocationResource,y);c(h,g.capacityField,y)?.type!=="number.integer"&&o(y,"capacity must be an integer"),(c(u,g.allocationField,y)?.type!=="uuid"||c(u,g.allocationField,y)?.nullable!==!1)&&o(y,"allocation reference must be a uuid"),u.surface?.mutationOwner!=="queued-command"&&o(y,"allocation model must be command owned"),g.reservationSeconds!==void 0&&i(g.reservationSeconds,10,86400,y)}new Set(I.quotas.map(g=>g.allocationResource)).size!==I.quotas.length&&o(A,"an allocation model has exactly one pool owner");for(let g of I.commands){let y=`${A}/commands/${g.code}`;r(g,y,["code","mode","intake","execution","capability","parameters","resourceKey","admission","deadlineSeconds","guards","operations","quota"]),g.mode!==void 0&&!["permit","durable"].includes(g.mode)&&o(y,"unsupported mode");let h=g.mode==="durable";if(l(g.parameters,y,h),f(g.resourceKey,g.parameters,y),n.some(u=>u.code===g.capability)||o(y,"command capability must be declared"),r(g.admission,y,["perSecond","burst","maxInFlight","maxQueue","maxWaitSeconds","permitSeconds"]),i(g.admission.perSecond,1,I.admission.perSecond,y),i(g.admission.burst,1,I.admission.burst,y),i(g.admission.maxInFlight,1,I.admission.maxInFlight,y),i(g.admission.maxQueue,1,1e4,y),i(g.admission.maxWaitSeconds,1,3600,y),(!h||g.admission.permitSeconds!==void 0)&&i(g.admission.permitSeconds,5,60,y),i(g.deadlineSeconds,10,3600,y),h){(g.operations!==void 0||g.guards!==void 0||g.quota!==void 0)&&o(y,"backend-plan does not accept static operations, guards or quota"),r(g.intake,y,["perSecond","burst","maxInFlight"]);for(let w of["perSecond","burst","maxInFlight"])i(g.intake[w],1,1e3,y);let u=r(g.execution,y,["kind","handlerCode","timeoutMs","resources","directory"]);u.kind!=="backend-plan"&&o(y,"durable requires backend-plan"),s(u.handlerCode,y),i(u.timeoutMs,100,3e4,y);let E=a(u.resources,32,y);E.length||o(y,"execution resources required"),new Set(E.map(w=>w.resourceCode)).size!==E.length&&o(y,"duplicate execution resource");for(let w of E){r(w,y,["resourceCode","readFields","writeOperations","writeFields"]);let S=d(w.resourceCode,y);for(let C of["readFields","writeFields"]){let v=a(w[C],64,y);new Set(v).size!==v.length&&o(y,"duplicate field"),v.forEach(P=>{C==="readFields"&&tn.has(P)||c(S,P,y)})}let T=a(w.writeOperations,3,y);(new Set(T).size!==T.length||T.some(C=>!["create","update","increment"].includes(C)))&&o(y,"unsupported execution operation"),w.writeFields.some(C=>["id","revision","created_by","updated_by","created_at","updated_at"].includes(C))&&o(y,"record metadata is platform owned"),!T.length&&w.writeFields.length&&o(y,"write fields require an operation"),T.length&&!w.writeFields.length&&o(y,"write operations require fields"),I.quotas.some(C=>C.allocationResource===w.resourceCode)&&T.length&&o(y,"allocation references remain owned by their pool command")}if(u.directory!==void 0){r(u.directory,y,["mode","fields"]),u.directory.mode!=="current-initiator"&&o(y,"only current initiator allowed");let w=a(u.directory.fields,5,y);(!w.length||new Set(w).size!==w.length||w.some(S=>!["displayName","employeeNumber","primaryDepartment","departments","phone"].includes(S)))&&o(y,"unsupported directory fields")}continue}(g.execution!==void 0||g.intake!==void 0)&&o(y,"execution and intake require durable mode");for(let u of a(g.guards||[],8,y)){r(u,y,["resourceCode","id","conditions"]);let E=d(u.resourceCode,y);p(u.id,g.parameters,y);for(let w of a(u.conditions,16,y)){r(w,y,["kind","field","operator","value"]);let S=c(E,w.field,y);["eq","neq","lt","lte","gt","gte"].includes(w.operator)||o(y,"unsupported guard"),w.kind==="database-now"?(S?.type!=="datetime"||!["lt","lte","gt","gte"].includes(w.operator)||w.value!==void 0)&&o(y,"database-now requires datetime and an ordering operator"):(w.kind!==void 0&&w.kind!=="value"&&o(y,"unsupported condition kind"),f(w.value,g.parameters,y))}}for(let u of a(g.operations,8,y)){r(u,y,["operation","resourceCode","id","expectedRevision","data"]);let E=d(u.resourceCode,y);E.surface?.mutationOwner!=="queued-command"&&o(y,"command mutations require command owned models");let w=I.quotas.find(S=>S.allocationResource===u.resourceCode);w&&(u.operation==="create"?g.quota?.action!=="allocate"||g.quota.pool!==w.code:Object.hasOwn(u.data||{},w.allocationField))&&o(y,"allocation references are owned by their pool command"),["create","update"].includes(u.operation)||o(y,"unsupported operation"),u.operation==="update"?(p(u.id,g.parameters,y),m(u.expectedRevision,g.parameters,y)):(u.id!==void 0||u.expectedRevision!==void 0)&&o(y,"create has no caller supplied id/revision"),r(u.data,y,Object.keys(u.data||{})),Object.keys(u.data).length>32&&o(y,"too many fields");for(let[S,T]of Object.entries(u.data))S==="id"&&o(y,"record identifiers are platform owned"),c(E,S,y),f(T,g.parameters,y,g.quota?.action==="allocate")}if(g.quota){let u=r(g.quota,y,["pool","action","units","mode","allocation"]),E=I.quotas.find(w=>w.code===u.pool);E||o(y,"unknown quota pool"),p(g.resourceKey,g.parameters,y),u.action==="allocate"?(r(u,y,["pool","action","units","mode"]),i(u.units,1,1e3,y),(!["committed","reserved"].includes(u.mode)||u.mode==="reserved"&&!E.reservationSeconds)&&o(y,"invalid allocation mode"),(g.operations.length!==1||g.operations[0].operation!=="create"||g.operations[0].resourceCode!==E.allocationResource||g.operations[0].data[E.allocationField]?.from!=="allocation")&&o(y,"allocation must atomically create its bound business record")):["confirm","release"].includes(u.action)?(r(u,y,["pool","action","allocation"]),p(u.allocation,g.parameters,y),g.operations.length&&o(y,"lifecycle owns allocation state; business reference remains immutable")):o(y,"invalid quota action")}else g.operations.length||o(y,"operations required")}let b=I.commands.filter(g=>g.mode==="durable").map(g=>g.execution.handlerCode);return new Set(b).size!==b.length&&o(A,"handler code must be unique"),JSON.parse(JSON.stringify(I))}var rn=class extends Error{constructor(n,o){super(`\u91D1\u989D\u751F\u547D\u5468\u671F\u58F0\u660E\u65E0\u6548\uFF1A${o}\uFF08${n}\uFF09`);this.pointer=n;this.reason=o}pointer;reason;code="NATIVE_DECIMAL_LIFECYCLE_INVALID"},ii=["parentTransitions","childTransitions","fulfilledChildStatuses","lockedParentStatuses"],ua=["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue"],Oo=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),yo=e=>Array.isArray(e)?e.filter(Oo):[],tt=(e,t)=>{throw new rn(e,t)},oi=e=>typeof e=="string"&&/^[A-Za-z0-9._:-]{1,128}$/.test(e),ri=(e,t)=>e<t?-1:e>t?1:0;function si(e,t="/decimalReservationLifecycle"){if(e===void 0)return;if(!Oo(e)||Object.keys(e).some(r=>!ii.includes(r))||ii.some(r=>!Object.prototype.hasOwnProperty.call(e,r)))return tt(t,"\u5FC5\u987B\u5B8C\u6574\u58F0\u660E\u56DB\u9879\u89C4\u5219\uFF0C\u4E0D\u80FD\u5305\u542B\u672A\u77E5\u5C5E\u6027");let n=r=>{let i=e[r];if(!Array.isArray(i)||i.length>64)return tt(`${t}/${r}`,"\u72B6\u6001\u8FB9\u6700\u591A 64 \u6761");let s=new Set;return i.map((a,d)=>{let c=`${t}/${r}/${d}`;if(!Oo(a)||Object.keys(a).some(f=>f!=="from"&&f!=="to")||!oi(a.from)||!oi(a.to)||a.from===a.to)return tt(c,"\u72B6\u6001\u8FB9\u5FC5\u987B\u5305\u542B\u4E0D\u540C\u7684\u6709\u6548 from/to");let l=JSON.stringify([a.from,a.to]);return s.has(l)?tt(c,"\u72B6\u6001\u8FB9\u4E0D\u80FD\u91CD\u590D"):(s.add(l),{from:a.from,to:a.to})}).sort((a,d)=>ri(a.from,d.from)||ri(a.to,d.to))},o=r=>{let i=e[r];return!Array.isArray(i)||i.length<1||i.length>16||i.some(s=>!oi(s))||new Set(i).size!==i.length?tt(`${t}/${r}`,"\u72B6\u6001\u96C6\u5408\u5FC5\u987B\u5305\u542B 1 \u5230 16 \u4E2A\u4E0D\u91CD\u590D\u7684\u6709\u6548\u72B6\u6001"):[...i].sort(ri)};return{parentTransitions:n("parentTransitions"),childTransitions:n("childTransitions"),fulfilledChildStatuses:o("fulfilledChildStatuses"),lockedParentStatuses:o("lockedParentStatuses")}}function fa(e,t,n="/config/data/resources"){yo(e).forEach((o,r)=>{let i=`${n}/${r}/decimalReservationLifecycle`,s=si(o.decimalReservationLifecycle,i);if(!s)return;let a=yo(t).map(f=>f.platformAccess?.decimalReservation).filter(f=>Oo(f)&&f.resourceCode===o.code),d=a.find(f=>f.mode==="reserve");if(!d)return tt(i,"\u9700\u8981\u540C\u8D44\u6E90\u5DF2\u58F0\u660E\u7684 reserve \u52A8\u4F5C\u6620\u5C04");if(ua.some(f=>typeof d[f]!="string")||a.some(f=>ua.some(p=>f[p]!==d[p])))return tt(i,"\u540C\u8D44\u6E90\u989D\u5EA6\u52A8\u4F5C\u7684\u5B57\u6BB5\u6620\u5C04\u5FC5\u987B\u4E00\u81F4");let c=yo(o.schema?.fields).find(f=>f.code===d.statusFieldCode);if(c?.type!=="option.single")return tt(i,"\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u5FC5\u987B\u4E3A option.single");let l=new Set(yo(c.options).map(f=>f.value));for(let f of ii)if((f==="parentTransitions"||f==="childTransitions"?s[f].flatMap(m=>[m.from,m.to]):s[f]).some(m=>!l.has(m)))return tt(`${i}/${f}`,"\u72B6\u6001\u5FC5\u987B\u6765\u81EA\u989D\u5EA6\u72B6\u6001\u5B57\u6BB5\u7684\u9009\u9879");if(a.some(f=>f.mode==="reserve"&&Array.isArray(f.eligibleParentStatuses)&&f.eligibleParentStatuses.some(p=>s.lockedParentStatuses.includes(String(p)))))return tt(`${i}/lockedParentStatuses`,"\u9501\u5B9A\u7236\u72B6\u6001\u4E0D\u80FD\u5141\u8BB8\u65B0\u9884\u7559")})}import{createHash as vl}from"crypto";var ai=new Set(["option.single","user.single","department.single","resource-ref.single"]),Pl=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","address","location","json"]),ma=new Set(["option.multiple","cascade.single","cascade.multiple","user.multiple","department.multiple","resource-ref.multiple","file","image"]),$l=new Set(["option.single","user.single","department.single","resource-ref.single","signature","address","location"]),Fl=new Set([...ai,...ma,"signature","address","location","json"]);function ag(e,t){let n=new Set([...Array.isArray(t?.list?.searchableFields)?t.list.searchableFields:[],...Object.entries(t?.fields||{}).filter(([,o])=>o?.searchable===!0).map(([o])=>o)]);return e.map(o=>Vl(o,n.has(o.code))).sort((o,r)=>o.code.localeCompare(r.code))}function Vl(e,t=!1){let n=e.type==="date-range"||e.type==="datetime-range";if(n&&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:jl(e),index:xl(e,t),...n?{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 dg(e,t){if(t.type==="subtable")return null;let n=Re(t.code),o=ga(e,t),r=[o?` DEFAULT ${o}`:"",Ul(n,t),Wl(n,t)].join("");return`${n} ${t.storage}${r}`}function cg(e,t){return ga(e,t)}function Wl(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 n=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 ${n?"":"NOT "}upper_inc(${e})))`}function lg(e){return e.type==="serial-number"||go(e.type)&&e.type!=="subtable"}function ug(e,t){return t.filter(n=>n.type==="serial-number").map(n=>{let o=ho(e,n.code),r=n.serial?.start??1;return`CREATE SEQUENCE IF NOT EXISTS ${o} AS bigint MINVALUE ${r} START WITH ${r} CACHE 1`})}function fg(e,t){let n=bo(e);return t.filter(o=>o.type==="serial-number").map(o=>`ALTER SEQUENCE ${ho(e,o.code)} OWNED BY ${n}.${Re(o.code)}`)}function pg(e,t){return t.filter(n=>n.type==="serial-number").map(n=>`GRANT USAGE, SELECT ON SEQUENCE ${ho(e,n.code)} TO "openxiangda_data_api"`)}function mg(e,t){let n=bo(e),o=[];for(let r of t){if(r.type==="subtable")continue;let i=Re(r.code),s=Re(yt("idx",e,r.code,r.index));switch(r.index){case"btree":o.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${n} (${i})`);break;case"btree-snapshot-expressions":{let a=Re(yt("idx",e,r.code,"snapshot-value")),d=Re(yt("idx",e,r.code,"snapshot-label"));o.push(`CREATE INDEX IF NOT EXISTS ${a} ON ${n} ((${i} ->> 'value'))`,`CREATE INDEX IF NOT EXISTS ${d} ON ${n} ((${i} ->> 'label'))`);break}case"gin-jsonb-path":o.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${n} USING GIN (${i} jsonb_path_ops)`);break;case"gist-range":o.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${n} USING GIST (${i})`);break;case"gin-trigram":{let a=ai.has(r.type)?`((${i} ->> 'label')) gin_trgm_ops`:`${i} gin_trgm_ops`;o.push(`CREATE INDEX IF NOT EXISTS ${s} ON ${n} USING GIN (${a})`);break}case"none":break}if(r.type==="serial-number"){let a=Re(yt("uidx",e,r.code,"serial"));o.push(`CREATE UNIQUE INDEX IF NOT EXISTS ${a} ON ${n} (${i})`)}}return o}function gg(e,t,n,o){let r=bo(e),i=bo(t),s=Re(yt("uidx",e,"environment_id","subtable-parent")),a=Re(yt("idx",t,n,o,"subtable-child")),d=Re(yt("fk",t,n,e)),c=Re(n),l=Re(o);return[`CREATE UNIQUE INDEX IF NOT EXISTS ${s} ON ${r} ("tenant_id", "app_code", "environment_key", "id")`,`CREATE INDEX IF NOT EXISTS ${a} ON ${i} ("tenant_id", "app_code", "environment_key", ${c}, ${l}, "id")`,`DO $native_subtable$ BEGIN
2
2
  ALTER TABLE ${i}
3
3
  ADD CONSTRAINT ${d}
4
4
  FOREIGN KEY ("tenant_id", "app_code", "environment_key", ${c})
5
5
  REFERENCES ${r} ("tenant_id", "app_code", "environment_key", "id")
6
6
  ON DELETE CASCADE;
7
7
  EXCEPTION WHEN duplicate_object THEN NULL;
8
- END $native_subtable$`]}function yt(e,...t){return`${e}_${vl("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function Re(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function xl(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":ai.has(e.type)?"btree-snapshot-expressions":Pl.has(e.type)?"gin-jsonb-path":"btree":"none"}function jl(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 Fl.has(e.type),"jsonb"}}function ga(e,t){if(go(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let o=pa(t.serial?.prefix||""),n=t.serial?.digits??6;return`(${o} || lpad(nextval(${pa(ho(e,t.code))})::text, ${n}, '0'))`}function Ul(e,t){return ma.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:$l.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function bo(e){return`"app_data".${Re(e)}`}function ho(e,t){let o=yt("seq",e,t);return`"app_data".${Re(o)}`}function pa(e){return`'${e.replace(/'/g,"''")}'`}var _a=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ml=new Set([..._a,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Aa=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Bl=new Set(["__proto__","prototype","constructor"]),di=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 Rn(e,t){let o=Ia(e);if(!o)return null;let n=t.get(o[0]);if(!n)return null;let r=o.slice(1).join(".")||void 0;return{field:n,...r?{valuePath:r}:{}}}function ci(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function Ea(e,t,o){if(!e||!t||!Kl(e))return!1;let{field:n,valuePath:r}=e;if(!r)return t.valueType==="uuid"?n.type==="uuid":["text.short","text.long","serial-number"].includes(n.type);if(r==="value")return!(t.valueSourceResourceCode&&n.type.startsWith("resource-ref.")&&n.source?.resourceCode!==t.valueSourceResourceCode);let i=r.slice(9),a=o.get(n.source?.resourceCode||"")?.get(i)?.type;return t.valueType==="uuid"?a==="uuid":["text.short","text.long","serial-number"].includes(a||"")}function Ag(e,t){let o=Ia(t);if(!o)throw new di(String(t||""));let n=e;for(let r of o){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,r))return;n=n[r]}return n}function Kl(e){let{field:t,valuePath:o}=e;if(!o)return!Ml.has(t.type);if(o==="value")return _a.has(t.type);if(!o.startsWith("snapshot."))return!1;let n=o.slice(9);return Aa.test(n)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(n)}function Ia(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=>!Aa.test(o)||Bl.has(o))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var ql=new Set(["option.single","user.single","department.single","resource-ref.single"]),zl=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),Gl=new Set(["value","label","description","color"]),Jl=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Hl=new Set(["fullPath","parent.value","parent.label"]),Yl=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Xl=new Set(["longitude","latitude","accuracy"]),Zl=new Set(["address","name","province","city","district","source"]);function Ig(e){let t=new Map(e.map(o=>[o.code,new Map(o.schema.fields.map(n=>[n.code,n]))]));return e.map(o=>({...o,schema:{...o.schema,fields:o.schema.fields.map(n=>{let r=Ql(n,t);if(!Object.keys(r).length)return n;let i={...n};return Object.defineProperty(i,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(r)}),i})}}))}function yg(e,t){if(ql.has(e.type)&&Gl.has(t)||e.type==="user.single"&&Jl.has(t)||e.type==="department.single"&&Hl.has(t))return Tn(t);if(e.type==="resource-ref.single"){let o=e.queryPathTypes?.[t];return o?{parts:t.split("."),type:o}:null}if(e.type==="address"&&Yl.has(t))return Tn(t);if(e.type==="location"){if(Xl.has(t))return{parts:[t],type:"number.decimal"};if(Zl.has(t))return Tn(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Ql(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let o=t.get(e.source.resourceCode);return o?Object.fromEntries((e.source.snapshotFields||[]).flatMap(n=>{let r=o.get(n);return r?[[`snapshot.${n}`,zl.has(r.type)?r.type:"json"]]:[]})):{}}function Tn(e){return{parts:e.split("."),type:"text.short"}}var ya={sources:32,scopes:16,facts:512},Cn=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},nt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},le=(e,t)=>{throw new Cn(e,t)},sn=(e,t,o=100)=>((typeof e!="string"||e.length>o||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(e))&&le("NATIVE_DIRECTORY_ROLE_IDENTIFIER_INVALID",t),e),bg={type:"object",additionalProperties:!1,required:["code","name","source","roleFactCode","roleCode","scopes","failureMode"],properties:{code:{type:"string",minLength:1,maxLength:100},name:{type:"string",minLength:1,maxLength:255},source:{type:"string",minLength:1,maxLength:64},roleFactCode:{type:"string",minLength:1,maxLength:64},roleCode:{type:"string",minLength:1,maxLength:128},failureMode:{const:"strict"},scopes:{type:"array",maxItems:16,items:{type:"object",additionalProperties:!1,required:["dimensionCode","scopeType","operations"],properties:{dimensionCode:{type:"string",minLength:1,maxLength:100},scopeType:{type:"string",minLength:1,maxLength:64},operations:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:64}}}}}}};function Oa(e,t="/config"){let o=nt(e),n=nt(o.authz),r=nt(o.data),i=Array.isArray(n.roles)?n.roles.map(nt):[],s=new Map((Array.isArray(n.scopeDimensions)?n.scopeDimensions:[]).map(c=>{let l=nt(c);return[l.code,l]}));for(let[c,l]of i.entries())l.organizationReach!==void 0&&!["self","subtree"].includes(l.organizationReach)&&le("NATIVE_ORGANIZATION_REACH_INVALID",`${t}/authz/roles/${c}/organizationReach`),l.organizationReach!==void 0&&l.code===n.authenticatedUserRoleCode&&le("NATIVE_ORGANIZATION_BASELINE_ROLE_FORBIDDEN",`${t}/authz/authenticatedUserRoleCode`);let a=n.directoryRoleSources;a!==void 0&&(!Array.isArray(a)||a.length>ya.sources)&&le("NATIVE_DIRECTORY_ROLE_SOURCE_CAPACITY",`${t}/authz/directoryRoleSources`);let d=new Set;for(let[c,l]of(a||[]).entries()){let f=nt(l),p=`${t}/authz/directoryRoleSources/${c}`;Object.keys(f).some(O=>!["code","name","source","roleFactCode","roleCode","scopes","failureMode"].includes(O))&&le("NATIVE_DIRECTORY_ROLE_SOURCE_INVALID",p);let m=sn(f.code,`${p}/code`);d.has(m)&&le("NATIVE_DIRECTORY_ROLE_SOURCE_DUPLICATE",`${p}/code`),d.add(m),(typeof f.name!="string"||!f.name.trim()||f.name.length>255||f.failureMode!=="strict")&&le("NATIVE_DIRECTORY_ROLE_SOURCE_INVALID",p),sn(f.source,`${p}/source`,64),sn(f.roleFactCode,`${p}/roleFactCode`,64);let A=i.find(O=>O.code===f.roleCode);(!A||A.organizationReach!=="self")&&le("NATIVE_DIRECTORY_ROLE_REQUIRES_SELF",`${p}/roleCode`),(Array.isArray(n.roleMembershipSources)?n.roleMembershipSources:[]).some(O=>nt(O).roleCode===f.roleCode)&&le("NATIVE_DIRECTORY_ROLE_OWNER_CONFLICT",`${p}/roleCode`),(!Array.isArray(f.scopes)||f.scopes.length>ya.scopes)&&le("NATIVE_DIRECTORY_ROLE_SCOPES_INVALID",`${p}/scopes`);let I=new Set;for(let[O,b]of f.scopes.entries()){let g=nt(b),y=`${p}/scopes/${O}`;Object.keys(g).some(E=>!["dimensionCode","scopeType","operations"].includes(E))&&le("NATIVE_DIRECTORY_ROLE_SCOPES_INVALID",y);let h=sn(g.dimensionCode,`${y}/dimensionCode`),u=s.get(h);(!u||(u.valueType||"string")!=="string"||u.valueSource||u.resourceCode||u.hierarchyMode&&u.hierarchyMode!=="flat")&&le("NATIVE_DIRECTORY_ROLE_STRING_DIMENSION_REQUIRED",`${y}/dimensionCode`),I.has(h)&&le("NATIVE_DIRECTORY_ROLE_SCOPE_DUPLICATE",y),I.add(h),sn(g.scopeType,`${y}/scopeType`,64),(!Array.isArray(g.operations)||!g.operations.length||g.operations.length>16||new Set(g.operations).size!==g.operations.length)&&le("NATIVE_DIRECTORY_ROLE_OPERATIONS_INVALID",`${y}/operations`);for(let[E,w]of g.operations.entries())sn(w,`${y}/operations/${E}`,64)}}for(let[c,l]of(Array.isArray(r.resources)?r.resources:[]).entries()){let f=nt(l),p=f.organization;if(p===void 0)continue;let m=`${t}/data/resources/${c}/organization`;if((!p||typeof p!="object"||Array.isArray(p)||Object.keys(p).some(I=>I!=="mode")||!["none","owned","inherited-down"].includes(p.mode))&&le("NATIVE_ORGANIZATION_POLICY_INVALID",m),p.mode==="none")continue;let A=f.schema?.fields||f.fields||[];A.some(I=>I.code==="organization_id")&&le("NATIVE_ORGANIZATION_COLUMN_RESERVED",m);for(let I of A){if(I.type!=="subtable"||!I.subtable?.resourceCode)continue;let O=r.resources.find(b=>b.code===I.subtable.resourceCode);(!O||!["owned","inherited-down"].includes(O.organization?.mode))&&le("NATIVE_SUBTABLE_ORGANIZATION_POLICY_REQUIRED",m)}for(let I of i){if(I.organizationReach)continue;let O=Array.isArray(I.capabilities)?I.capabilities:[];Object.values(nt(f.capabilities)).some(b=>O.includes(b))&&le("NATIVE_ORGANIZATION_ROLE_REACH_REQUIRED",`${t}/authz/roles/${i.indexOf(I)}/organizationReach`)}(f.surface?.public||f.surface?.publicRead)&&le("NATIVE_ORGANIZATION_PUBLIC_CONTEXT_UNSUPPORTED",m)}}var wo={type:"string",minLength:1},je={type:"object",additionalProperties:!1,required:["label","value"],properties:{label:{type:"string",minLength:1,maxLength:500},value:{type:"string",minLength:1,maxLength:500},description:{type:"string",maxLength:2e3},color:{type:"string",maxLength:64}}},fi={type:"object",additionalProperties:!1,required:["label","value"],properties:{...je.properties,fullPath:{type:"string",maxLength:4e3},path:{type:"array",maxItems:20,items:je},parent:je}},li={type:"object",additionalProperties:!1,required:["label","value"],properties:{...je.properties,avatarUrl:{type:"string",maxLength:4e3},employeeNo:{type:"string",maxLength:200},title:{type:"string",maxLength:500},mobile:{type:"string",maxLength:100},email:{type:"string",maxLength:500},departments:{type:"array",maxItems:20,items:fi}}},ba={type:"object",additionalProperties:!1,required:["label","value","resourceCode"],properties:{...je.properties,resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},snapshot:{type:"object",maxProperties:50,additionalProperties:!0}}},No={type:"object",additionalProperties:!1,required:["schemaVersion","id","name","size","contentType"],properties:{schemaVersion:{const:"openxiangda.data-file-ref/v2"},id:wo,name:{type:"string",minLength:1,maxLength:1e3},size:{type:"integer",minimum:0},contentType:{type:"string",minLength:1,maxLength:500}}},eu={type:"object",additionalProperties:!1,required:["id","name","size","contentType"],properties:{id:wo,name:{type:"string",minLength:1,maxLength:1e3},size:{type:"integer",minimum:0},contentType:{type:"string",minLength:1,maxLength:500}}},ha={type:"object",additionalProperties:!1,required:["start","end"],properties:{start:wo,end:wo}},ui={type:"array",maxItems:100,items:je},tu={longitude:{type:"number",minimum:-180,maximum:180},latitude:{type:"number",minimum:-90,maximum:90},address:{type:"string",maxLength:8e3},name:{type:"string",maxLength:2e3},province:{type:"string",maxLength:500},city:{type:"string",maxLength:500},district:{type:"string",maxLength:500},accuracy:{type:"number",minimum:0},source:{enum:["browser","dingTalk"]},capturedAt:{type:"string",format:"date-time"}},nu={"text.short":{type:"string",maxLength:1e6},"text.long":{type:"string",maxLength:1e6},"text.rich":{type:"string",maxLength:1e6},"number.integer":{type:"integer"},"number.decimal":{type:"number"},boolean:{type:"boolean"},date:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},time:{type:"string",pattern:"^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d)?$"},datetime:{type:"string",format:"date-time"},"date-range":ha,"datetime-range":ha,"option.single":je,"option.multiple":ui,"cascade.single":ui,"cascade.multiple":{type:"array",maxItems:100,items:ui},"user.single":li,"user.multiple":{type:"array",maxItems:100,items:li},"department.single":fi,"department.multiple":{type:"array",maxItems:100,items:fi},"resource-ref.single":ba,"resource-ref.multiple":{type:"array",maxItems:100,items:ba},image:{type:"array",maxItems:100,items:{...No,required:[...No.required,"width","height","thumbnailUrl","previewUrl"],properties:{...No.properties,width:{type:"integer",minimum:1},height:{type:"integer",minimum:1},thumbnailUrl:{type:"string",maxLength:4e3},previewUrl:{type:"string",maxLength:4e3}}}},signature:{type:"object",additionalProperties:!1,required:["file","signedAt","hash"],properties:{file:eu,signer:li,signedAt:{type:"string",format:"date-time"},points:{type:"array",maxItems:2e4,items:{type:"object",additionalProperties:!1,required:["x","y","t"],properties:{x:{type:"number"},y:{type:"number"},t:{type:"number"}}}},hash:{type:"string",pattern:"^[0-9a-f]{64}$"}}},address:{type:"object",additionalProperties:!1,properties:{country:je,province:je,city:je,district:je,street:je,detail:{type:"string",maxLength:4e3},fullAddress:{type:"string",maxLength:8e3}}},location:{type:"object",additionalProperties:!1,required:["source","longitude","latitude"],properties:tu},uuid:{type:"string",format:"uuid"},json:{},file:{type:"array",maxItems:100,items:No},"serial-number":{type:"string",minLength:1,maxLength:255},subtable:{type:"array",maxItems:lt,items:{type:"object",additionalProperties:!0}}};function Ro(e){if(e.type==="number.decimal"&&e.exactDecimal===!0){let r=e.precision,i=e.scale;if(typeof r=="number"&&typeof i=="number"&&Number.isInteger(r)&&Number.isInteger(i)&&r>=1&&i>=0&&i<=r){let s=Math.max(1,r-i),a=i>0?`(?:\\.[0-9]{1,${i}})?`:"";return{type:"string",pattern:`^-?(?:0|[1-9][0-9]{0,${s-1}})${a}$`,maxLength:s+(i>0?i+1:0)+1}}return{type:"string",pattern:"^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$"}}let t=JSON.parse(JSON.stringify(nu[e.type]));if(e.type!=="date-range"&&e.type!=="datetime-range")return t;if(!["closed","half-open"].includes(String(e.rangeBoundary)))throw new Error("DATA_RESOURCE_FIELD_RANGE_BOUNDARY_REQUIRED");let o=e.rangeBoundary;t["x-openxiangda-range-boundary"]=o;let n=e.type==="date-range"?{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"}:{type:"string",format:"date-time"};return t.properties={start:n,end:n},t.description=o==="closed"?"Closed interval: start <= end; both start and end are included.":"Half-open interval: start < end; start is included and end is excluded.",t}function pi(e,t){if(t===void 0)return e;let o=e.views?.find(s=>s.code===t);if(!o)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let n=new Map(o.sections?.flatMap(s=>s.fields.map(a=>[a,s.title]))),{views:r,...i}=e;return{...i,generated:o.generated,list:o.list,form:o.form,detail:o.detail,mobile:o.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([s,a])=>{let{section:d,...c}=a,l=n.get(s);return[s,{...c,...l?{section:l}:{},list:o.list.fieldOrder?.includes(s)??!1}]}))}}var Ca=Object.freeze({agents:20,tasks:20,fields:20,instructions:16e3,instructionBytes:64e3,arrayItems:50,pages:10}),mi=class extends Error{constructor(o,n,r){super(`${o}: ${n}: ${r}`);this.code=o;this.pointer=n;this.name="NativeApplicationAgentContractError"}code;pointer};function z(e,t,o){throw new mi(`NATIVE_APPLICATION_AGENT_${e}`,t,o)}function gi(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&z("OBJECT_REQUIRED",t,"\u9700\u8981\u5BF9\u8C61"),e}function _i(e,t,o){for(let n of Object.keys(e))t.includes(n)||z("PROPERTY_UNSUPPORTED",`${o}/${n}`,"\u672A\u77E5\u5C5E\u6027")}function Ot(e,t,o){return(typeof e!="string"||!e.trim()||e.length>t)&&z("TEXT_INVALID",o,`\u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32\uFF0C\u6700\u591A ${t} \u5B57\u7B26`),e}function To(e,t){let o=Ot(e,100,t);return/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/.test(o)||z("CODE_INVALID",t,"\u9700\u8981\u7A33\u5B9A\u7F16\u7801"),o}function Co(e,t,o,n){if(e===void 0)return[];(!Array.isArray(e)||e.length>t)&&z("ARRAY_LIMIT",n,`\u6700\u591A ${t} \u9879`);let r=e.map((i,s)=>Ot(i,o,`${n}/${s}`));return new Set(r).size!==r.length&&z("DUPLICATE",n,"\u4E0D\u80FD\u91CD\u590D"),r}function ou(e,t="/agents/instructions/file"){let o=Ot(e,500,t),n=o.split("/");return(!/\.(md|txt)$/i.test(o)||n.some(r=>!r||r.startsWith(".")||/[\\:\p{Cc}]/u.test(r)||/^(?:\.\.?|AGENTS\.md|CLAUDE\.md|SKILL\.md|credentials.*|secrets?.*|.*\.pem|.*\.key)$/i.test(r)))&&z("INSTRUCTION_PATH_INVALID",t,"\u9700\u8981\u5DE5\u4F5C\u533A\u5185\u7684\u666E\u901A md/txt \u6587\u4EF6\uFF0C\u4E0D\u80FD\u5F15\u7528\u534F\u4F5C\u8BF4\u660E\u6216\u51ED\u636E"),o}function ru(e,t,o){if(typeof e=="string")return Ot(e,Ca.instructions,t);let n=gi(e,t);_i(n,["file"],t);let r=ou(n.file,`${t}/file`);return o||z("INSTRUCTIONS_NOT_INLINED",t,"\u6587\u4EF6\u6307\u4EE4\u5FC5\u987B\u5148\u7531\u5DE5\u4F5C\u533A\u52A0\u8F7D\u5668\u5185\u8054"),{file:r}}var So={type:"object",additionalProperties:!1,required:["label"],properties:{label:{type:"string",minLength:1,maxLength:500}}},iu=/^(option|user|department|resource-ref)\.(single|multiple)$/,su=new Set(["file","image","signature","subtable","text.rich","json","serial-number"]);function au(e,t,o){if(t.type.startsWith("user."))return{selector:{owner:t.userCandidates?"user-candidates":"directory"}};if(t.type.startsWith("department."))return{selector:{owner:"directory"}};if(t.type.startsWith("resource-ref."))return{selector:{owner:"field-source"}};if(t.type.startsWith("option.")||t.type.startsWith("cascade."))return{selector:{owner:"options"}};if(!["text.short","uuid"].includes(t.type))return{};let n=o?.dataPolicies?.find(a=>a.code===e.dataPolicyCode&&a.resourceCode===e.code),r=[...n?.rules||[]],i=n?.readExpression?[n.readExpression]:[];for(;i.length;){let a=i.shift();r.length+i.length>2e3&&z("SELECTOR_POLICY_LIMIT",`/data/resources/${e.code}`,"\u8303\u56F4\u8DEF\u7531\u8D85\u8FC7\u89C4\u5219\u9884\u7B97"),a?.allOf?i.push(...a.allOf):a?.anyOf?i.push(...a.anyOf):r.push(a)}let s=new Set(r.flatMap(a=>a&&"dimensionCode"in a&&a.field===t.code&&o?.scopeDimensions?.some(d=>d.code===a.dimensionCode&&d.valueSource)?[a.dimensionCode]:[]));return s.size===1?{selector:{owner:"scope",dimensionCode:[...s][0]}}:s.size>1?{ambiguousScope:!0}:{}}function Na(e,t=!1,o){if(o?.ambiguousScope)return;if(o?.selector?.owner==="scope")return!t&&e.nullable!==!1?{anyOf:[So,{type:"null"}]}:So;if(iu.test(e.type)){let r=e.type.endsWith(".multiple")?{type:"array",minItems:t?1:0,maxItems:50,items:So}:So;return!t&&e.nullable!==!1?{anyOf:[r,{type:"null"}]}:r}if(!["text.short","text.long","number.integer","number.decimal","boolean","date","time","datetime"].includes(e.type))return;let n=Ro(e);return e.type==="datetime"&&(n={...n,pattern:"(?:Z|[+-]\\d{2}:\\d{2})$"}),t&&["number.integer","number.decimal","date","datetime"].includes(e.type)?{oneOf:[n,{type:"object",additionalProperties:!1,minProperties:1,properties:{from:n,to:n}}]}:!t&&e.nullable!==!1?{anyOf:[n,{type:"null"}]}:n}function Ge(e,t=[]){return{type:"object",additionalProperties:!1,properties:e,...t.length?{required:t}:{}}}function wa(e,t){return[...((t.source||e.surface?.fields[t.code]?.source)?.filters||[]).flatMap(n=>"binding"in n?[n.binding.field]:[]),...t.userCandidates?.scope?.field?[t.userCandidates.scope.field]:[]]}var Ra={type:"object",additionalProperties:!1,required:["handle"],properties:{handle:{type:"string",minLength:1,maxLength:80}}},Ta={type:"object",additionalProperties:!1,properties:{columns:{type:"array",maxItems:500,items:Ge({code:{type:"string"},label:{type:"string"}},["code","label"])},items:{type:"array",maxItems:100,items:Ge({handle:{type:"string"},title:{type:"string"},fields:{type:"array",maxItems:500,items:Ge({code:{type:"string"},label:{type:"string"},value:{type:"string"}},["code","label","value"])}},["handle","fields"])},more:{type:"boolean"},total:{type:"integer",minimum:0},continuation:{type:"string",maxLength:80},summary:{type:"string"},filter_ambiguous:{type:"boolean"},field:{type:"string",maxLength:100},labels:{type:"array",maxItems:20,items:Ge({label:{type:"string"},description:{type:"string"}},["label"])}}};function du(e,t,o,n,r,i){let s=n.find(h=>h&&typeof h=="object"&&h.code===o.resource&&h.status!=="retired");(!s?.surface||!s.surface.fields||!Array.isArray(s.schema?.fields)||s.schema.fields.some(h=>!h||typeof h.code!="string"||typeof h.type!="string"))&&z("RESOURCE_UNAVAILABLE",`${r}/resource`,"\u9700\u8981\u5F53\u524D\u6A21\u578B\u53CA\u6807\u51C6\u89C6\u56FE");try{bn(s.schema.fields,`${r}/resource/schema/fields`)}catch(h){if(!(h instanceof We))throw h;z("RESOURCE_SCHEMA_INVALID",`${r}/resource`,h.message)}s.surface.views!==void 0&&!Array.isArray(s.surface.views)&&z("VIEW_UNKNOWN",`${r}/view`,"\u9700\u8981\u5DF2\u9A8C\u8BC1\u7684\u6807\u51C6\u89C6\u56FE"),!s.surface.views?.some(h=>h.code===o.view)&&!(o.view==="default"&&!s.surface.views?.length)&&z("VIEW_UNKNOWN",`${r}/view`,"\u89C6\u56FE\u4E0D\u5B58\u5728");let a=o.view==="default"&&!s.surface.views?.length?s.surface:pi(s.surface,o.view),d=new Map(s.schema.fields.map(h=>[h.code,h])),c=new Map(s.schema.fields.map(h=>[h.code,au(s,h,i)])),l=h=>[...new Set(h)].flatMap(u=>{let E=d.get(u),w=c.get(u);if(!E||!w)return[];let S=!!E.userCandidates?.scope?.field;return[{field:u,...w.selector?{selector:w.selector}:{},create:o.kind==="form"&&o.action==="create"&&!S,update:o.kind==="form"&&o.action==="update",filter:o.kind==="view"&&(o.filters??a.list?.filterFields??[]).includes(u)&&!w.ambiguousScope,output:w.ambiguousScope?"page":w.selector?"label":"value",...w.ambiguousScope?{reason:"multiple-scope-dimensions"}:S?{reason:"saved-scope-required"}:{}}]}),f={code:`${e}.agent.${t}.${o.code}`,appCode:e,name:o.name||`${s.name}${o.kind==="view"?"\u67E5\u8BE2":o.action==="create"?"\u65B0\u589E":"\u4FEE\u6539"}`.slice(0,80),description:o.description||`\u901A\u8FC7${s.name}\u7684${o.view}\u6807\u51C6\u89C6\u56FE${o.kind==="view"?"\u67E5\u8BE2":"\u586B\u5199"}\uFF0C\u9075\u5B88\u5F53\u524D\u7528\u6237\u6743\u9650`,kind:"nativeTask",resources:[s.code],limits:{timeoutMs:1e4},agent:{visibility:"task",...o.examples?.length?{examples:[...o.examples]}:{}}};if(o.kind==="view"){a.generated?.list===!1&&z("LIST_DISABLED",r,"\u8BE5\u89C6\u56FE\u672A\u751F\u6210\u5217\u8868");let h=o.filters??a.list?.filterFields??[];h.some(T=>!a.list?.filterFields?.includes(T))&&z("FILTER_WIDENING",`${r}/filters`,"\u4EFB\u52A1\u53EA\u80FD\u7F29\u5C0F\u89C6\u56FE\u7B5B\u9009\u5B57\u6BB5");let u=h.filter(T=>!c.get(T)?.ambiguousScope),E=Object.fromEntries(u.map(T=>{let C=d.get(T),v=C&&Na(C,!0,c.get(T));return v||z("FILTER_TYPE_UNSUPPORTED",`${r}/filters`,`\u5B57\u6BB5 ${T} \u6682\u4E0D\u652F\u6301\u6A21\u578B\u7B5B\u9009\u63D0\u793A`),[T,v]})),w=(a.list?.fieldOrder||[]).filter(T=>s.surface.fields[T]?.sortable);a.list?.defaultSort&&!w.includes(a.list.defaultSort.field)&&w.push(a.list.defaultSort.field);let S=Ge({...a.list?.searchableFields?.length?{keyword:{type:"string",maxLength:200}}:{},...u.length?{filters:Ge(E)}:{},...w.length?{sort:Ge({field:{enum:w},order:{enum:["asc","desc"]}},["field"])}:{},limit:{type:"integer",minimum:1,maximum:100},continue:{type:"string",minLength:1,maxLength:80},record:Ra});return{...f,operation:"query",inputSchema:{type:"object"},outputSchema:Ta,authorization:{capabilities:[s.capabilities.read]},risk:"read",confirmation:"none",idempotency:"none",concurrency:"none",sideEffects:[],limits:{...f.limits,maxRows:100},binding:{kind:"native-view",resourceCode:s.code,viewCode:o.view,filterFields:u},agent:{...f.agent,nativeTask:{contractVersion:2,agentCode:t,taskCode:o.code,hintSchema:S,coverage:l([...h,...a.list?.fieldOrder||[],...a.detail?.fieldOrder||[]])}}}}((s.surface.mutationOwner||"native")!=="native"||a.generated?.[o.action]===!1)&&z("MUTATION_NOT_NATIVE",r,"\u53EA\u80FD\u7ED1\u5B9A\u5DF2\u751F\u6210\u7684\u666E\u901A\u539F\u751F create/update");let p=o.fields;p.length||z("FIELDS_REQUIRED",`${r}/fields`,"\u9700\u8981\u81F3\u5C11\u4E00\u4E2A\u8868\u5355\u5B57\u6BB5");for(let h of p){let u=d.get(h),E=s.surface.fields[h];(!u||!a.form?.fieldOrder?.includes(h)||!E||E.system||E.hidden||Vt(h)||Ao(h)||su.has(u.type))&&z("FORM_FIELD_UNSUPPORTED",`${r}/fields`,`\u5B57\u6BB5 ${h} \u4E0D\u5C5E\u4E8E\u53EF\u7F16\u8F91\u7684\u6807\u51C6\u5355\u63A7\u4EF6\u8868\u5355`),(!Array.isArray(E[`${o.action}Capabilities`])||E[`${o.action}Capabilities`].length===0)&&z("FORM_FIELD_UNWRITABLE",`${r}/fields`,`\u5B57\u6BB5 ${h} \u672A\u63D0\u4F9B ${o.action} \u6743\u9650`),o.action==="create"&&u.userCandidates?.scope?.field&&z("CANDIDATE_CREATE_OWNER_REQUIRED",`${r}/fields`,`\u4EFB\u52A1 ${o.code} \u5B57\u6BB5 ${h} (user-candidates) \u7684\u8303\u56F4\u53D6\u81EA\u8BB0\u5F55\u5B57\u6BB5\uFF0C\u65B0\u5EFA\u9700\u901A\u8FC7\u6D41\u7A0B\u53D1\u8D77\u6216 Nest \u4E1A\u52A1\u64CD\u4F5C\u529E\u7406`)}let m=new Set(p);if(o.action==="create"){for(let h of s.schema.fields)Et(h,s.surface.fields[h.code])&&!m.has(h.code)&&z("CREATE_FIELD_REQUIRED",`${r}/fields`,`\u5FC5\u987B\u5305\u542B\u65B0\u589E\u5FC5\u586B\u5B57\u6BB5 ${h.code}`);for(let h of p)for(let u of wa(s,d.get(h)))m.has(u)||z("CREATE_BINDING_REQUIRED",`${r}/fields`,`${h} \u4F9D\u8D56 ${u}\uFF0C\u5FC5\u987B\u5305\u542B\u7ED1\u5B9A\u5B57\u6BB5`)}else for(let h of s.schema.fields)wa(s,h).some(u=>m.has(u))&&!m.has(h.code)&&z("UPDATE_DEPENDENT_REQUIRED",`${r}/fields`,`\u4FEE\u6539\u7ED1\u5B9A\u5B57\u6BB5\u65F6\u5FC5\u987B\u5305\u542B\u4F9D\u8D56\u9009\u62E9\u5668 ${h.code}`);let A=p.map(h=>d.get(h)),I=o.action==="create"?A.filter(h=>Et(h,s.surface.fields[h.code])).map(h=>h.code):[],O=Ge(Object.fromEntries(A.map(h=>[h.code,h.nullable===!1?Ro(h):{anyOf:[Ro(h),{type:"null"}]}])),I),b=Object.fromEntries(A.flatMap(h=>{let u=Na(h,!1,c.get(h.code));return u?[[h.code,u]]:[]})),g={kind:"native-form",resourceCode:s.code,viewCode:o.view,action:o.action,fields:[...p]},y=Ge({data:O,...o.action==="update"?{id:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1}}:{}},["data",...o.action==="update"?["id","expectedRevision"]:[]]);return{...f,operation:o.action,inputSchema:y,outputSchema:Ta,authorization:{capabilities:[s.capabilities[o.action]]},risk:"write",confirmation:o.confirmation||"required",idempotency:"required",concurrency:o.action==="update"?"revision":"none",sideEffects:[`${s.code}:${o.action}`],reconcile:{kind:"platform-transaction"},binding:g,agent:{...f.agent,nativeTask:{contractVersion:2,agentCode:t,taskCode:o.code,hintSchema:Ge({data:Ge(b),...o.action==="update"?{record:Ra}:{}}),coverage:l(p),form:{contractVersion:2,action:o.action,title:f.name,submitLabel:"\u63D0\u4EA4",resource:s.code,view:o.view,fields:A.map(h=>({path:h.code,label:s.surface.fields[h.code].label,fieldType:h.type,required:Et(h,s.surface.fields[h.code]),source:{resource:s.code,field:h.code},...c.get(h.code)?.selector?{selector:c.get(h.code).selector}:{}}))}}}}}function Sa(e,t,o,n={}){let r={schemaVersion:"openxiangda.application-agent-definitions/v2",appCode:e,agents:[]},i=[];if(t===void 0)return{definitions:r,capabilities:i};Array.isArray(o)||z("RESOURCES_INVALID","/data/resources","\u9700\u8981\u5DF2\u9A8C\u8BC1\u7684\u6A21\u578B\u5217\u8868"),(!Array.isArray(t)||t.length>Ca.agents)&&z("AGENT_LIMIT","/agents","\u6700\u591A 20 \u4E2A\u52A9\u624B");let s=new Set;for(let a=0;a<t.length;a++){let d=`/agents/${a}`,c=gi(t[a],d);_i(c,["code","name","purpose","instructions","starters","tasks"],d);let l=To(c.code,`${d}/code`);s.has(l)&&z("CODE_DUPLICATE",`${d}/code`,"\u52A9\u624B\u4EE3\u7801\u91CD\u590D"),s.add(l);let f=Ot(c.name,80,`${d}/name`),p=Ot(c.purpose,1e3,`${d}/purpose`),m=ru(c.instructions,`${d}/instructions`,n.allowInstructionFiles===!0),A=Co(c.starters,12,160,`${d}/starters`);(!Array.isArray(c.tasks)||c.tasks.length<1||c.tasks.length>20)&&z("TASK_LIMIT",`${d}/tasks`,"\u9700\u8981 1\u201320 \u4E2A\u4EFB\u52A1");let I=new Set,O=c.tasks.map((g,y)=>{let h=`${d}/tasks/${y}`,u=gi(g,h);["view","form"].includes(u.kind)||z("TASK_KIND_INVALID",`${h}/kind`,"\u53EA\u652F\u6301 view/form"),_i(u,["code","kind","name","description","resource","view","examples",...u.kind==="view"?["filters"]:["action","fields","confirmation"]],h);let E=To(u.code,`${h}/code`);return I.has(E)&&z("TASK_CODE_DUPLICATE",`${h}/code`,"\u4EFB\u52A1\u4EE3\u7801\u91CD\u590D"),I.add(E),To(u.resource,`${h}/resource`),To(u.view,`${h}/view`),u.name!==void 0&&Ot(u.name,80,`${h}/name`),u.description!==void 0&&Ot(u.description,1e3,`${h}/description`),Co(u.examples,12,160,`${h}/examples`),u.kind==="view"?Co(u.filters,20,100,`${h}/filters`):(["create","update"].includes(u.action)||z("FORM_ACTION_INVALID",`${h}/action`,"\u53EA\u652F\u6301 create/update"),u.confirmation!==void 0&&!["none","required"].includes(u.confirmation)&&z("CONFIRMATION_INVALID",`${h}/confirmation`,"\u786E\u8BA4\u7B56\u7565\u65E0\u6548"),Array.isArray(u.fields)||z("FIELDS_REQUIRED",`${h}/fields`,"\u9700\u8981\u5B57\u6BB5\u5217\u8868"),Co(u.fields,20,100,`${h}/fields`)),du(e,l,u,o,h,n.authz)}),b={code:l,name:f,purpose:p,instructions:typeof m=="string"?m:"",starters:A,tasks:O.map(g=>({code:g.agent.nativeTask.taskCode,capabilityCode:g.code}))};r.agents.push({...b,digest:ee({...b,capabilities:O})}),i.push(...O)}return r.agents.sort((a,d)=>a.code<d.code?-1:a.code>d.code?1:0),i.sort((a,d)=>a.code<d.code?-1:a.code>d.code?1:0),{definitions:r,capabilities:i}}function Do(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(n?.reminders===void 0)continue;let r=n.reminders;(!["approval","handle","correction"].includes(n.kind)||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length!==4||Object.keys(r).some(i=>!["afterSeconds","everySeconds","max","to"].includes(i))||!Number.isInteger(r.afterSeconds)||r.afterSeconds<1||r.afterSeconds>2592e3||!Number.isInteger(r.everySeconds)||r.everySeconds<1||r.everySeconds>2592e3||!Number.isInteger(r.max)||r.max<1||r.max>10||!Array.isArray(r.to)||r.to.length!==1||r.to[0]!=="handlers")&&t.push(`WORKFLOW_REMINDERS_INVALID:${o}`)}return t}function ot(e){return e.returnPolicy?Array.isArray(e.returnPolicy.targets)?e.returnPolicy.targets.filter(t=>typeof t?.nodeId=="string").map(t=>t.nodeId):[]:Array.isArray(e.returnTargets)?[...e.returnTargets]:[]}function Pg(e,t,o){if(t.returnPolicy)return Array.isArray(t.returnPolicy.targets)?t.returnPolicy.targets.find(n=>n.nodeId===o):void 0;if(t.returnTargets?.includes(o))return{nodeId:o,routes:e.nodes[o]?.kind==="correction"?["replay"]:["replay","resume"],defaultRoute:"replay"}}function ko(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){let r=n?.returnPolicy;if(r===void 0)continue;if(!["approval","handle"].includes(n.kind)||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(s=>s!=="targets")||!Array.isArray(r.targets)||r.targets.length>20){t.push(`WORKFLOW_RETURN_POLICY_INVALID:${o}`);continue}let i=new Set;for(let s of r.targets)(!s||typeof s!="object"||Object.keys(s).some(a=>!["nodeId","routes","defaultRoute"].includes(a))||typeof s.nodeId!="string"||s.nodeId===o||i.has(s.nodeId)||!["approval","handle","correction"].includes(e.nodes?.[s.nodeId]?.kind))&&t.push(`WORKFLOW_RETURN_TARGET_INVALID:${o}`),s?.nodeId&&i.add(s.nodeId),(!Array.isArray(s?.routes)||s.routes.length<1||s.routes.length>2||new Set(s.routes).size!==s.routes.length||s.routes.some(a=>!["replay","resume"].includes(a))||!s.routes.includes(s.defaultRoute))&&t.push(`WORKFLOW_RETURN_ROUTES_INVALID:${o}`);n.returnTargets&&(n.returnTargets.length!==i.size||n.returnTargets.some(s=>!i.has(s)))&&t.push(`WORKFLOW_RETURN_TARGETS_CONFLICT:${o}`)}return t}var cu=2,lu=8,Ai=e=>!!e&&typeof e=="object"&&!Array.isArray(e),uu=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(e),Da=(e,t)=>e===t||e.startsWith(`${t}.`)||t.startsWith(`${e}.`);function Lo(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...(Array.isArray(e.branches)?e.branches:[]).map(t=>t?.target),e.otherwise]:e.kind==="parallel"?[...(Array.isArray(e.branches)?e.branches:[]).map(t=>t?.target),e.join]:"next"in e?[e.next]:[]}function rt(e){let t=[],o=[];if(!Ai(e?.nodes))return{regions:o,errors:["WORKFLOW_PARALLEL_DOCUMENT_INVALID"]};let n=e.nodes;if(!Object.values(n).some(s=>s?.kind==="parallel"||s?.kind==="join"))return{regions:o,errors:t};if(Object.keys(n).length>200)return{regions:o,errors:["WORKFLOW_PARALLEL_NODE_LIMIT"]};let r=new Map,i=new Set;for(let s of Object.values(n)){if(s?.kind!=="parallel")continue;let a=n[s.join];if(a?.kind!=="join"||a.parallel!==s.id||i.has(s.join)){t.push(`WORKFLOW_PARALLEL_PAIR_INVALID:${s.id}`);continue}if(i.add(a.id),n[a.next]||t.push(`WORKFLOW_PARALLEL_TARGET_MISSING:${a.id}`),!Array.isArray(s.branches)||s.branches.length<cu||s.branches.length>lu){t.push(`WORKFLOW_PARALLEL_BRANCH_LIMIT:${s.id}`);continue}let d={parallelNodeId:s.id,joinNodeId:a.id,branches:[]},c=new Set,l=new Set;for(let f of s.branches){if(!Ai(f)||!uu(f.id)||typeof f.title!="string"||!f.title.trim()||f.title.length>255||c.has(f.id)){t.push(`WORKFLOW_PARALLEL_BRANCH_INVALID:${s.id}`);continue}c.add(f.id);let p=new Set,m=new Set,A=new Set,I=b=>{if(b===a.id)return;let g=n[b];if(!g){t.push(`WORKFLOW_PARALLEL_TARGET_MISSING:${s.id}:${b}`);return}if(g.kind==="end"){g.outcome!=="rejected"?t.push(`WORKFLOW_PARALLEL_BRANCH_END_INVALID:${s.id}:${f.id}:${b}`):l.add(b);return}if(g.kind==="parallel"||g.kind==="join"){t.push(`WORKFLOW_PARALLEL_NESTING_FORBIDDEN:${s.id}:${b}`);return}if(m.has(b)){t.push(`WORKFLOW_PARALLEL_CYCLE:${s.id}:${b}`);return}if(A.has(b))return;p.add(b),m.add(b);let y=Lo(g);y.length||t.push(`WORKFLOW_PARALLEL_BRANCH_DANGLING:${s.id}:${b}`);for(let h of y)I(h);m.delete(b),A.add(b)};I(f.target);let O=new Set;for(let b of p){r.get(b)?t.push(`WORKFLOW_PARALLEL_BODY_OVERLAP:${s.id}:${f.id}:${b}`):r.set(b,{parallel:s.id,branch:f.id});let y=n[b];if(y.kind==="approval"||y.kind==="handle")for(let h of e.taskPages?.[y.taskPageCode||""]?.fields||[]){let u=y.fieldPolicy?.fields?.[h.code]||y.fieldPolicy?.default||"readonly";h.readonly!==!0&&(u==="edit"||u==="edit_required")&&O.add(h.code)}}d.branches.push({id:f.id,target:f.target,nodeIds:[...p].sort(),writableFields:[...O].sort()})}l.size>1&&t.push(`WORKFLOW_PARALLEL_REJECT_END_NOT_SHARED:${s.id}`),o.push(d)}for(let s of Object.values(n))s?.kind==="join"&&!i.has(s.id)&&t.push(`WORKFLOW_PARALLEL_JOIN_ORPHAN:${s.id}`);r.has(e.startAt)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_ENTRY:${e.startAt}`);for(let[s,a]of Object.entries(n))if(Ai(a)){for(let d of Lo(a)){let c=r.get(d),l=r.get(s),f=c&&n[c.parallel],p=f?.kind==="parallel"&&s===f.id&&f.branches.some(m=>m.id===c.branch&&m.target===d);if(c&&!p&&(!l||l.parallel!==c.parallel||l.branch!==c.branch)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_ENTRY:${s}:${d}`),n[d]?.kind==="join"&&a.kind!=="parallel"){let m=n[d];(!l||l.parallel!==m.parallel)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_JOIN:${s}:${d}`)}}if(a.kind==="approval"||a.kind==="handle"){let d=r.get(s);for(let c of ot(a)){let l=r.get(c);d&&(!l||l.parallel!==d.parallel||l.branch!==d.branch)&&t.push(`WORKFLOW_PARALLEL_RETURN_CROSSES_BRANCH:${s}:${c}`),!d&&l&&t.push(`WORKFLOW_PARALLEL_RETURN_ENTERS_BRANCH:${s}:${c}`)}}}for(let s of o)for(let a of s.branches){let d=s.branches.filter(l=>l.id!==a.id);for(let l of a.writableFields)d.some(f=>f.writableFields.includes(l))&&t.push(`WORKFLOW_PARALLEL_SHARED_WRITABLE_FIELD:${s.parallelNodeId}:${l}`);let c=d.flatMap(l=>[...Object.entries(e.subject?.factProjection||{}).filter(([,f])=>l.writableFields.some(p=>Da(p,f))).map(([f])=>f),...l.nodeIds.filter(f=>n[f]?.kind==="action").map(f=>`steps.${f}`)]);for(let l of a.nodeIds){let f=n[l];if(f.kind==="action")for(let p of Object.values(f.inputs||{}))p.source==="fact"&&c.some(m=>Da(m,p.path))&&t.push(`WORKFLOW_PARALLEL_SIBLING_INPUT:${l}:${p.path}`)}}return{regions:o,errors:[...new Set(t)]}}function vo(e){return rt(e).errors}function Vg(e){if(!["running","returned"].includes(e.status))return!1;if(!e.forkVisitId&&!e.branchId)return e.currentNodeId===e.nodeId;let t=e.fork;return!!t&&e.forkVisitId===t.forkVisitId&&e.branchId===t.branchId&&t.status==="active"&&e.currentNodeId===t.parallelNodeId&&t.activation.includes(e.branchId)&&!t.arrived.includes(e.branchId)&&e.activeToken}function Po(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(n?.kind!=="handle"){n?.allowedOperations?.includes("complete")&&t.push(`WORKFLOW_HANDLE_COMMAND_ONLY:${o}`);continue}(!n.next||!e.nodes?.[n.next])&&t.push(`WORKFLOW_HANDLE_TARGET_MISSING:${o}`),(["onApprove","onReject","initiatorApprovalPolicy","completionDeadline"].some(r=>r in n)||n.emptyPolicy==="skip")&&t.push(`WORKFLOW_HANDLE_APPROVAL_POLICY_FORBIDDEN:${o}`),(!Array.isArray(n.allowedOperations)||!n.allowedOperations.includes("complete")||n.allowedOperations.some(r=>!["complete","save_form","transfer","delegate","return"].includes(r)))&&t.push(`WORKFLOW_HANDLE_OPERATIONS_INVALID:${o}`),(!Array.isArray(n.requiredOperations)||!n.requiredOperations.includes("complete"))&&t.push(`WORKFLOW_HANDLE_COMPLETE_REQUIRED:${o}`)}return t}function Ei(e,t){let o=()=>{throw Object.assign(new Error("DATA_MUTATION_GRANT_INVALID"),{code:"DATA_MUTATION_GRANT_INVALID"})};if(!Array.isArray(e)||e.length<1||e.length>32)return o();let n=new Set;return e.map(i=>!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(s=>!["resourceCode","operations","fieldCodes","maxOperations","allowRuntimeWorker"].includes(s))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.resourceCode)||i.allowRuntimeWorker!==void 0&&i.allowRuntimeWorker!==!0||n.has(i.resourceCode)||t&&!t.has(i.resourceCode)||!Array.isArray(i.operations)||i.operations.length<1||i.operations.length>4||new Set(i.operations).size!==i.operations.length||i.operations.some(s=>!["create","update","delete","increment"].includes(s))||!Array.isArray(i.fieldCodes)||i.fieldCodes.length>128||new Set(i.fieldCodes).size!==i.fieldCodes.length||i.operations.some(s=>s!=="delete")&&!i.fieldCodes.length||i.fieldCodes.some(s=>typeof s!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||t&&!t.get(i.resourceCode)?.has(s))||!Number.isSafeInteger(i.maxOperations)||i.maxOperations<1||i.maxOperations>1e3?o():(n.add(i.resourceCode),{resourceCode:i.resourceCode,operations:[...i.operations].sort(),fieldCodes:[...i.fieldCodes].sort(),maxOperations:i.maxOperations,...i.allowRuntimeWorker?{allowRuntimeWorker:!0}:{}})).sort((i,s)=>i.resourceCode.localeCompare(s.resourceCode))}var Ug=5,Mg=20,Bg=50,Kg=50,qg=100,Dn=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function an(e,t){let o=[],n=(r,i,s)=>{s>5&&Sn("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",i);let a=La(r,i),d=["allOf","anyOf"].filter(f=>f in a);if(d.length===0){o.push({rule:a,pointer:i}),o.length>50&&Sn("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",i);return}let c=d[0],l=a[c];(d.length!==1||Object.keys(a).length!==1||!Array.isArray(l)||l.length<1||l.length>20)&&Sn("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",i),l.forEach((f,p)=>n(f,`${i}/${c}/${p}`,s+1))};return n(e,t,1),o}function ka(e,t){an(e,t);let o=(n,r)=>{let i=La(n,r);if(Array.isArray(i.allOf))return Ii(i.allOf.flatMap((s,a)=>o(s,`${r}/allOf/${a}`)),r);if(Array.isArray(i.anyOf)){let s=[[]];return i.anyOf.forEach((a,d)=>{let c=o(a,`${r}/anyOf/${d}`);s=Ii(s.flatMap(l=>c.map(f=>[...l,...f])),r)}),s}return[[i]]};return Ii(o(e,t),t)}function Ii(e,t){let o=e.reduce((n,r)=>n+r.length,0);return(e.length>50||o>100)&&Sn("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function La(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&Sn("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function Sn(e,t){throw new Dn(e,t)}var Te=class extends Error{constructor(o,n){super(`${o}: ${n}`);this.code=o;this.pointer=n}code;pointer},fu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,va=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/;function pu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Te("NATIVE_PARENT_READ_INVALID",t);let o=e;if(Object.keys(o).some(n=>!["resourceCode","subtableFieldCode"].includes(n))||typeof o.resourceCode!="string"||o.resourceCode.length>64||!fu.test(o.resourceCode)||typeof o.subtableFieldCode!="string"||!va.test(o.subtableFieldCode))throw new Te("NATIVE_PARENT_READ_INVALID",t);return{resourceCode:o.resourceCode,subtableFieldCode:o.subtableFieldCode}}function Pa(e,t){return[...(Array.isArray(e.rules)?e.rules:[]).map((o,n)=>({rule:o,pointer:`${t}/rules/${n}`,base:!0})),...e.readExpression===void 0?[]:an(e.readExpression,`${t}/readExpression`).map(o=>({...o,base:!1}))]}function $o(e,t,o,n){let r=pu(o,n),i=e.find(m=>m.code===r.resourceCode),s=e.find(m=>m.code===t),d=(Array.isArray(i?.schema?.fields)?i.schema.fields:[]).find(m=>m.code===r.subtableFieldCode);if(!i||!s||i.code===s.code||d?.type!=="subtable"||d.subtable?.resourceCode!==t)throw new Te("NATIVE_PARENT_READ_BINDING_INVALID",n);if(e.flatMap(m=>(Array.isArray(m.schema?.fields)?m.schema.fields:[]).filter(A=>A.type==="subtable"&&A.subtable?.resourceCode===t).map(A=>({resource:m,field:A}))).length!==1)throw new Te("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",n);let l=d.subtable.foreignKey,p=(Array.isArray(s.schema?.fields)?s.schema.fields:[]).find(m=>m.code===l);if(typeof l!="string"||!va.test(l)||p?.type!=="uuid")throw new Te("NATIVE_PARENT_READ_FOREIGN_KEY_INVALID",n);return{...r,childResourceCode:t,foreignKey:l,...d.subtable.orderField?{orderField:d.subtable.orderField}:{}}}function $a(e,t,o="/config/authz/dataPolicies"){let n=new Map;for(let[r,i]of t.entries())for(let s of Pa(i,`${o}/${r}`)){if(s.rule.parentRead===void 0)continue;if(Object.keys(s.rule).some(l=>!["parentRead","roleCodes"].includes(l)))throw new Te("NATIVE_PARENT_READ_RULE_KEYS_INVALID",s.pointer);if(s.base&&(i.operations?.length!==1||i.operations[0]!=="read"))throw new Te("NATIVE_PARENT_READ_READ_ONLY",s.pointer);if(e.find(l=>l.code===i.resourceCode)?.dataPolicyCode!==i.code)throw new Te("NATIVE_PARENT_READ_POLICY_BINDING_INVALID",s.pointer);let d=$o(e,i.resourceCode,s.rule.parentRead,`${s.pointer}/parentRead`),c=n.get(i.resourceCode);if(c&&c!==d.resourceCode)throw new Te("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",s.pointer);n.set(i.resourceCode,d.resourceCode)}for(let[r,i]of n)if(n.has(i))throw new Te("NATIVE_PARENT_READ_MULTI_HOP_FORBIDDEN",`${o}/${t.findIndex(s=>s.resourceCode===r)}`)}function yi(e){return Pa(e,"/dataPolicy").some(t=>t.rule.parentRead!==void 0)}var Wa=e=>!!e&&typeof e=="object"&&!Array.isArray(e),xa=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(o=>t.includes(o)),Fa=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,Va=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function Oi(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function ja(e){(!Wa(e)||!xa(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!Fa(e.workflowCode)||!Fa(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)&&Oi("POLICY_INVALID")}function Hg(e){(!Wa(e)||!xa(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!Va(e.instanceId)||!Va(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&Oi("GUARD_INVALID")}function Yg(e,t,o){o?.some(n=>(n.kind==="record-match"||n.kind==="record-assert")&&n.resourceCode===e.resourceCode&&n.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&n.assertions.some(r=>r.kind==="value"&&r.field==="revision"&&r.operator==="eq"&&Number.isSafeInteger(r.value)&&Number(r.value)>0))||Oi("SOURCE_GUARD_REQUIRED")}var Xg={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 kn=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},Le=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ua=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function Ma(e){let{policy:t,resource:o,baselineRoleCode:n,baselineCapabilities:r,pointer:i}=e,s=I=>I===void 0||I===!0||Array.isArray(I)&&I.length>0&&I.every(O=>typeof O=="string"&&O.length>0&&!e.baselineDeniedCapabilities?.some(b=>Ua(b,O))&&r.some(b=>Ua(b,O))),a=(I,O="")=>{throw new kn(I,`${i}/publicRead${O}`)},d=Le(t.publicRead);(!t.publicRead||Object.keys(d).length!==1||!Object.hasOwn(d,"fields")||!Array.isArray(d.fields)||d.fields.length<1||d.fields.length>1e3||d.fields.some(I=>typeof I!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(I))||new Set(d.fields).size!==d.fields.length)&&a("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)&&a("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!n||!o||o.code!==t.resourceCode||o.dataPolicyCode!==t.code||!s([Le(o.capabilities).read]))&&a("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let c=Le(o),l=Le(c.schema).fields;(!Array.isArray(l)||!l.length)&&a("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let f=new Map(l.map(I=>[String(Le(I).code),Le(I)])),p=new Set(d.fields),m=Le(c.fieldPolicies);for(let I of p){let O=Le(f.get(I));(!f.has(I)||O.system===!0||Le(Le(c.surface).fields)[I]?.system===!0||tn.has(I))&&a("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${I}`),(O.type==="subtable"||O.subtable!==void 0)&&a("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${I}`),s(Le(m[I]).read)||a("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${I}`)}let A=[...f.keys()].filter(I=>!p.has(I));for(let I of A)s(Le(m[I]).read)&&a("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${I}`);A.length&&_o.some(I=>s(Le(m[I]).read))&&a("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var Ba=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],n_=256,vn=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"},bi=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),ge=(e,t)=>{throw new vn(e,t)},Fo=(e,t)=>e<t?-1:e>t?1:0,Ln=(e,t,o)=>{Object.keys(e).some(n=>!t.includes(n))&&ge(o,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Ka(e,t,o="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return ge(o,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let n=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,s)=>{let a=`${o}/${s}`;if(!bi(i))return ge(a,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(Ln(i,["code","fields","when"],a),typeof i.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.code)||i.code.length>20||r.has(i.code))return ge(`${a}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(r.add(i.code),!Array.isArray(i.fields)||i.fields.length<1||i.fields.length>4)return ge(`${a}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let d=new Set,c=i.fields.map((m,A)=>{let I=`${a}/fields/${A}`;if(!bi(m))return ge(I,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");Ln(m,["fieldCode","normalizer"],I);let O=n.get(m.fieldCode);if(!O||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(O.type)||d.has(m.fieldCode))return ge(`${I}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");d.add(m.fieldCode);let b=m.normalizer===void 0?"exact-v1":m.normalizer;return!Ba.includes(b)||O.type!=="text.short"&&b!=="exact-v1"?ge(`${I}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:O.code,normalizer:b}}).sort((m,A)=>Fo(m.fieldCode,A.fieldCode)),l=i.when===void 0?[]:i.when;if(!Array.isArray(l)||l.length>4)return ge(`${a}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let f=new Set,p=l.map((m,A)=>{let I=`${a}/when/${A}`;if(!bi(m))return ge(I,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let O=n.get(m.fieldCode);if(!O)return ge(`${I}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let b;if(m.operator==="empty"||m.operator==="nonempty"){if(Ln(m,["fieldCode","operator"],I),O.type!=="text.short")return ge(I,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");b={fieldCode:O.code,operator:m.operator}}else if(m.operator==="in"||m.operator==="notIn"){Ln(m,["fieldCode","operator","values"],I);let y=new Set((O.options??[]).map(h=>h.value));if(O.type!=="option.single"||!Array.isArray(m.values)||m.values.length<1||m.values.length>16||m.values.some(h=>typeof h!="string"||h.length<1||h.length>128||!y.has(h))||new Set(m.values).size!==m.values.length)return ge(I,"\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:m.operator,values:[...m.values].sort(Fo)}}else if(m.operator==="eq"||m.operator==="ne"){if(Ln(m,["fieldCode","operator","value"],I),O.type!=="boolean"||typeof m.value!="boolean")return ge(I,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");b={fieldCode:O.code,operator:m.operator,value:m.value}}else return ge(`${I}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let g=JSON.stringify(b);return f.has(g)?ge(I,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(f.add(g),b)}).sort((m,A)=>Fo(JSON.stringify(m),JSON.stringify(A)));return{code:i.code,fields:c,when:p}}).sort((i,s)=>Fo(i.code,s.code))}function qa(e,t){let o=new Set(e.filter(n=>n.type==="user.single").map(n=>n.code));return t?.some(n=>n.fields.some(r=>o.has(r.fieldCode))||n.when?.some(r=>r.operator==="eq"||r.operator==="ne"))?"1.1.0":"1.0.0"}var Vo={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},o_={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:Vo,normalizer:{enum:[...Ba]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:Vo,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:Vo,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:Vo,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var za={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Ga(e,t){let o=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},n=p=>!p||typeof p!="object"||Array.isArray(p)?o():p,r=n(e);if(Object.keys(r).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof r.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.resourceCode)||typeof r.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(r.workflowCode)||t.execution!==void 0||!Array.isArray(r.outcomes)||!r.outcomes.length||r.outcomes.length>3)return o();let i=t.resources.find(p=>p.code===r.resourceCode),s=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===r.resourceCode),a=t.workflows.find(p=>p.code===r.workflowCode);if(!i||!s||!a||a.resourceCode!==i.code)return o();let d=i.fields.find(p=>p.code===s.statusFieldCode);if(d?.type!=="option.single")return o();let c=new Set(d.options?.map(p=>p.value)),l=new Set,f=r.outcomes.map(p=>{let m=n(p),A=m.eventType;return Object.keys(m).some(I=>!["eventType","mode","eligibleChildStatuses"].includes(I))||typeof A!="string"||!Object.prototype.hasOwnProperty.call(za,A)||!t.eventTypes.includes(A)||l.has(A)||m.mode!==za[A]||!Array.isArray(m.eligibleChildStatuses)||!m.eligibleChildStatuses.length||m.eligibleChildStatuses.length>16||new Set(m.eligibleChildStatuses).size!==m.eligibleChildStatuses.length||m.eligibleChildStatuses.some(I=>typeof I!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(I)||!c.has(I))?o():(l.add(A),{eventType:A,mode:m.mode,eligibleChildStatuses:[...m.eligibleChildStatuses].sort()})}).sort((p,m)=>p.eventType.localeCompare(m.eventType));return{resourceCode:r.resourceCode,workflowCode:r.workflowCode,outcomes:f}}function Ja(e,t){let o=n=>Array.isArray(n)?n.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:o(e.data?.resources).map(n=>({code:n.code,fields:o(n.schema?.fields).map(r=>({code:r.code,type:r.type,options:o(r.options).map(i=>({value:i.value}))}))})),reservations:o(e.backend?.operations).flatMap(n=>n.platformAccess?.decimalReservation?[n.platformAccess.decimalReservation]:[]),workflows:o(e.workflows?.definitions).map(n=>({code:n.definition?.code,resourceCode:n.definition?.subject?.resourceCode}))}}var Wo=new Set(["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"]),Ha=new Set(["isEmpty","isNotEmpty"]);var wi=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n}code;pointer},U=(e,t="EVENT_WORKER_EFFECT_INVALID")=>{throw new wi(t,e)},Ue=(e,t,o)=>((!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(n=>!t.includes(n)))&&U(o),e),hi=e=>typeof e=="string"&&/^[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(e),bt=(e,t,o,n)=>((typeof e!="number"||!Number.isSafeInteger(e)||e<t||e>o)&&U(n),e),Pn=(e,t,o)=>((!Array.isArray(e)||e.length>t||e.some(n=>typeof n!="string"||!n||n.length>255)||new Set(e).size!==e.length)&&U(o),[...e].sort()),Ni=(e,t,o)=>{(typeof e!="string"||!e||e.length>t||e.trim()!==e)&&U(o)},Ti=(e,t)=>{let o;try{o=JSON.stringify(e)}catch{U(t)}(!o||Buffer.byteLength(o)>65536)&&U(t,"EVENT_WORKER_EFFECT_SIZE_EXCEEDED")};function Ya(e,t,o,n=[],r="/execution"){let i=Ue(e,["kind","version","resources","emitEventTypes","maxOperations","maxGuards","maxQueryRecords","maxIntentsPerEvent"],r);(i.kind!=="worker-effect"||i.version!==1||!Array.isArray(i.resources)||!i.resources.length||i.resources.length>16)&&U(r);let s=new Map(t.map(p=>[p.code,p])),a=new Set,d={},c=i.resources.map((p,m)=>{let A=`${r}/resources/${m}`,I=Ue(p,["resourceCode","readFields","writeOperations","writeFields"],A),O=s.get(I.resourceCode);(!O||a.has(I.resourceCode))&&U(A,"EVENT_WORKER_EFFECT_RESOURCE_INVALID"),a.add(I.resourceCode);let b=new Map((O.schema?.fields||[]).map(u=>[u.code,u])),g=Pn(I.readFields,64,`${A}/readFields`),y=Pn(I.writeFields,64,`${A}/writeFields`),h=Pn(I.writeOperations,2,`${A}/writeOperations`);return(h.some(u=>!["create","update"].includes(u))||!!h.length!=!!y.length)&&U(A),(!g.length||g.some(u=>!["id","revision","created_at"].includes(u)&&!b.has(u)))&&U(`${A}/readFields`,"EVENT_WORKER_EFFECT_FIELD_INVALID"),y.some(u=>!b.has(u)||b.get(u).type==="serial-number"||["id","revision","tenant_id","app_code","environment_key","created_at","created_by","updated_at","updated_by"].includes(u))&&U(`${A}/writeFields`,"EVENT_WORKER_EFFECT_FIELD_INVALID"),h.length&&n.includes(I.resourceCode)&&U(A,"EVENT_WORKER_EFFECT_WORKFLOW_RESOURCE_FORBIDDEN"),d[I.resourceCode]=ee(O),{resourceCode:I.resourceCode,readFields:g,writeFields:y,writeOperations:h}}).sort((p,m)=>p.resourceCode.localeCompare(m.resourceCode)),l=Pn(i.emitEventTypes,16,`${r}/emitEventTypes`);l.some(p=>!o.includes(p)||p.startsWith("openxiangda."))&&U(`${r}/emitEventTypes`,"EVENT_WORKER_EFFECT_EVENT_INVALID");let f={kind:"worker-effect",version:1,resources:c,emitEventTypes:l,resourceDigests:d,maxOperations:bt(i.maxOperations,1,8,`${r}/maxOperations`),maxGuards:bt(i.maxGuards,1,24,`${r}/maxGuards`),maxQueryRecords:bt(i.maxQueryRecords,1,500,`${r}/maxQueryRecords`),maxIntentsPerEvent:bt(i.maxIntentsPerEvent,1,100,`${r}/maxIntentsPerEvent`)};return Ti(f,r),{...f,digest:ee(f)}}function Ri(e,t,o){let n=e.resources.find(r=>r.resourceCode===t);return n||U(o,"EVENT_WORKER_EFFECT_RESOURCE_FORBIDDEN"),n}function $n(e,t,o,n=0){n>12&&U(o);let r=Ue(e,["field","operator","value","path","and","or","not"],o);if(r.field!==void 0){(!Wo.has(r.operator)||r.path!==void 0&&(typeof r.path!="string"||!/^(value|label|snapshot\.[A-Za-z][A-Za-z0-9_]{0,62}|[A-Za-z][A-Za-z0-9_]{0,62})$/.test(r.path)))&&U(o),t.includes(r.field)||U(o,"EVENT_WORKER_EFFECT_FIELD_FORBIDDEN"),(r.and!==void 0||r.or!==void 0||r.not!==void 0)&&U(o);return}if(Object.keys(r).length!==1&&U(o),r.not!==void 0)return $n(r.not,t,`${o}/not`,n+1);let s=r.and!==void 0?"and":"or",a=r[s];(!Array.isArray(a)||!a.length||a.length>100)&&U(o),a.forEach((d,c)=>$n(d,t,`${o}/${s}/${c}`,n+1))}function c_(e,t,o){let n=Ue(o,["schemaVersion","select","where","order","limit","offset"],"/query");n.schemaVersion!=="openxiangda.data-query/v2"&&U("/query");let r=Ri(e,t,"/resourceCode"),i=Pn(n.select,64,"/query/select");return(!i.length||i.some(s=>!r.readFields.includes(s)))&&U("/query/select","EVENT_WORKER_EFFECT_FIELD_FORBIDDEN"),bt(n.limit,1,e.maxQueryRecords,"/query/limit"),bt(n.offset??0,0,1e4,"/query/offset"),n.where!==void 0&&$n(n.where,r.readFields,"/query/where"),n.order!==void 0&&((!Array.isArray(n.order)||n.order.length>8)&&U("/query/order"),n.order.forEach((s,a)=>{let d=Ue(s,["field","direction"],`/query/order/${a}`);(!r.readFields.includes(d.field)||!["asc","desc"].includes(d.direction))&&U("/query/order","EVENT_WORKER_EFFECT_FIELD_FORBIDDEN")})),Ti(o,"/query"),o}function l_(e,t){let o=Ue(t,["guards","operations"],"/plan");return Ti(o,"/plan"),(!Array.isArray(o.operations)||!o.operations.length||o.operations.length>e.maxOperations||!Array.isArray(o.guards)||!o.guards.length||o.guards.length>e.maxGuards)&&U("/plan"),o.operations.forEach((n,r)=>{let i=`/plan/operations/${r}`,s=Ue(n,["operation","resourceCode","id","expectedRevision","data","eventType","subject"],i);if(s.operation==="emitEvent"){(s.resourceCode!==void 0||s.id!==void 0||s.expectedRevision!==void 0||!e.emitEventTypes.includes(s.eventType))&&U(i,"EVENT_WORKER_EFFECT_EVENT_INVALID"),s.subject!==void 0&&Ni(s.subject,255,`${i}/subject`),Ue(s.data,Object.keys(s.data||{}),`${i}/data`);return}(!["create","update"].includes(s.operation)||s.eventType!==void 0||s.subject!==void 0)&&U(i);let a=Ri(e,s.resourceCode,i);a.writeOperations.includes(s.operation)||U(i,"EVENT_WORKER_EFFECT_OPERATION_FORBIDDEN");let d=Ue(s.data,a.writeFields,`${i}/data`);Object.keys(d).length||U(`${i}/data`),s.operation==="update"?(hi(s.id)||U(`${i}/id`),bt(s.expectedRevision,1,Number.MAX_SAFE_INTEGER,`${i}/expectedRevision`)):(s.id!==void 0||s.expectedRevision!==void 0)&&U(i)}),o.guards.forEach((n,r)=>{let i=`/plan/guards/${r}`,s=n,a=s?.kind==="record-set-match"?["kind","resourceCode","errorCode","records","where"]:["kind","resourceCode","errorCode","id","assertions","lockKey","where"],d=Ue(n,a,i);["query-empty","record-match","record-assert","record-exists","record-set-match"].includes(d.kind)||U(i,"EVENT_WORKER_EFFECT_GUARD_FORBIDDEN");let c=Ri(e,d.resourceCode,i);if(Ni(d.errorCode,128,`${i}/errorCode`),d.kind==="record-set-match"){(!Array.isArray(d.records)||d.records.length>500||new Set(d.records.map(l=>l?.id)).size!==d.records.length)&&U(i),d.records.forEach(l=>{let f=Ue(l,["id","expectedRevision"],i);hi(f.id)||U(i),bt(f.expectedRevision,1,Number.MAX_SAFE_INTEGER,i)}),d.where!==void 0&&$n(d.where,c.readFields,`${i}/where`);return}if(Ni(d.lockKey,255,`${i}/lockKey`),d.kind==="query-empty"){(d.id!==void 0||d.assertions!==void 0)&&U(i),$n(d.where,c.readFields,`${i}/where`);return}if((!hi(d.id)||d.where!==void 0)&&U(i),d.kind==="record-exists"){d.assertions!==void 0&&U(i);return}(!Array.isArray(d.assertions)||!d.assertions.length||d.assertions.length>32)&&U(i),d.assertions.forEach(l=>{let f=Ue(l,["kind","field","operator","value","path","leftField","rightField"],i);["value","field","database-now"].includes(f.kind)||U(i),(f.kind==="field"?[f.leftField,f.rightField]:[f.field]).some(m=>!c.readFields.includes(m))&&U(i,"EVENT_WORKER_EFFECT_FIELD_FORBIDDEN")})}),t}function u_(e,t){return[e.schemaVersion,t,ee(e)].join(`
9
- `)}var xo=class extends Error{constructor(o,n){super(n);this.pointer=o}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Xa(e,t,o="/events/subscriptions",n){if(e.execution===void 0)return;if(e.execution?.kind==="worker-effect"){if(e.platformAccess)throw new xo(`${o}/platformAccess`,"Worker effect grants cannot be combined with other runtime capabilities");return{execution:Ya(e.execution,t,n?.emitEventTypes||[],n?.workflowResources||[],`${o}/execution`),payload:e.payload}}let r=(O,b)=>{throw new xo(`${o}${O}`,b)},i=(O,b,g)=>((!O||typeof O!="object"||Array.isArray(O)||Object.keys(O).some(y=>!g.includes(y)))&&r(b,"Invalid action object or unsupported property"),O),s=i(e.execution,"/execution",["kind","version","operations"]);(s.kind!=="native-data"||s.version!==1)&&r("/execution","Expected native-data version 1"),e.platformAccess&&r("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(O=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(O)))&&r("/eventTypes","Native data actions require declared data events");let a=e.filter?.resourceCodes;(!Array.isArray(a)||!a.length||a.length>20)&&r("/filter/resourceCodes","Native actions require explicit source resources");let d=new Map(t.map(O=>[O.code,O])),c=a.map(O=>{let b=d.get(O);return b||r("/filter/resourceCodes","Unknown source resource"),new Set((b.schema?.fields||[]).map(g=>g.code))}),l=new Set(e.payload?.fields||[]),f=e.payload?.includeChanges===!0,p=(O,b)=>{let g=i(O,b,["source","path","value"]);if(g.source==="literal"){(!Object.hasOwn(g,"value")||Object.hasOwn(g,"path"))&&r(b,"Literal binding requires only value");let E;try{E=JSON.stringify(g.value)}catch{r(b,"Literal must be JSON")}return(E===void 0||Buffer.byteLength(E)>65536)&&r(b,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(E)}}(g.source!=="event"||typeof g.path!="string"||Object.hasOwn(g,"value"))&&r(b,"Expected a literal or event binding");let y=g.path.split(".");(y.length>8||y.some(E=>!/^[A-Za-z0-9_-]+$/.test(E)||["__proto__","prototype","constructor"].includes(E)))&&r(b,"Invalid event path");let h=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(g.path),u=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(g.path);if(h||u){let E=(h||u)[1];c.some(w=>!w.has(E))&&r(b,"Source field must exist on every filtered resource"),l.add(E),u&&(f=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(g.path)||r(b,"Event path is not part of the data event contract");return{source:"event",path:g.path}};(!Array.isArray(s.operations)||s.operations.length<1||s.operations.length>16)&&r("/execution/operations","Expected 1 to 16 operations");let m={},A=s.operations.map((O,b)=>{let g=`/execution/operations/${b}`,y=i(O,g,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(y.operation)||r(g,"Unsupported Native operation");let h=d.get(y.resourceCode);h||r(g,"Unknown action target resource");let u=new Map((h.schema?.fields||[]).map(w=>[w.code,w])),E=y.data===void 0?{}:i(y.data,`${g}/data`,[...u.keys()]);return Object.keys(E).length>32&&r(g,"Maximum 32 mapped fields per operation"),y.operation==="create"&&(y.id!==void 0||y.expectedRevision!==void 0)&&r(g,"Create does not accept id or expectedRevision"),y.operation==="delete"&&y.data!==void 0&&r(g,"Delete does not accept data"),Object.keys(E).some(w=>u.get(w)?.type==="serial-number")&&r(g,"Generated fields cannot be assigned"),m[y.resourceCode]=ee(h),{operation:y.operation,resourceCode:y.resourceCode,...y.operation==="create"?{}:{id:p(y.id,`${g}/id`),expectedRevision:p(y.expectedRevision,`${g}/expectedRevision`)},...y.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(E).map(([w,S])=>[w,p(S,`${g}/data/${w}`)]))}}});(l.size>32||[...l].some(O=>c.some(b=>!b.has(O))))&&r("/payload/fields","Payload must contain at most 32 declared source fields");let I={kind:"native-data",version:1,operations:A,resourceDigests:m};return Buffer.byteLength(JSON.stringify(I))>65536&&r("/execution","Action plan exceeds 64 KiB"),{execution:{...I,digest:ee(I)},payload:{includeChanges:f,fields:[...l].sort()}}}function ht(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Qa(e,t){if(e?.instanceCommands===void 0)return[];let o=ht(e.instanceCommands);if(!o||!Object.keys(o).length||Object.keys(o).some(r=>!["withdraw","terminate"].includes(r)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let n=[];for(let[r,i]of Object.entries(o)){let s=ht(i),a=r==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!s||!Object.keys(s).length||Object.keys(s).some(d=>!a.includes(d))||Object.hasOwn(s,"reasonRequired")&&typeof s.reasonRequired!="boolean"){n.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${r}`);continue}if(r==="terminate"){let d=s.capability;(typeof d!="string"||d.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(d)||t&&(!d.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(d)))&&n.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(s,"beforeFact")){let d=s.beforeFact,c=ht(e.inputSchema),l=ht(ht(c?.properties)?.[d]),f=ht(ht(e.subject)?.factProjection)?.[d],p=t?.fields.get(f);(typeof d!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(d)||!Array.isArray(c?.required)||!c.required.includes(d)||l?.type!=="string"||l?.format!=="date-time"||typeof f!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&n.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${r}`)}}return n}function __(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 A_(e){return e?.withdraw?.reasonRequired!==!1}function Za(e){if(typeof e!="string")return null;let t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,3}))?(Z|[+-]\d{2}:\d{2})$/.exec(e);if(!t)return null;let[,o,n,r,i,s,a]=t,d=t[8],c=new Date(Date.UTC(Number(o),Number(n),0)).getUTCDate();if(Number(n)<1||Number(n)>12||Number(r)<1||Number(r)>c||Number(i)>23||Number(s)>59||Number(a)>59||d!=="Z"&&(Number(d.slice(1,3))>23||Number(d.slice(4))>59))return null;let l=Date.parse(e);return Number.isFinite(l)?l:null}function E_(e,t,o,n){let r=e?.[t];if(!r||r.beforeFact===void 0)return null;let i=r.beforeFact,s=ht(o),a=i&&s&&Object.hasOwn(s,i)?Za(s[i]):null,d=n instanceof Date?n.getTime():Za(n);return a===null||d===null||!Number.isFinite(d)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":d<a?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var ve=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Wt=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,mu=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,Ci=e=>typeof e=="string"&&e.length<=256&&mu.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function Uo(e,t){let o=ve(e),n=!0;for(let r of t.split(".")){n&&=Array.isArray(o.required)&&o.required.includes(r);let i=ve(o.properties)[r];if(!i||typeof i!="object")return null;o=ve(i)}return{schema:o,required:n}}function Fn(e){let t=new Set,o=[],n=2048,r=(i,s)=>{if(--n<0||s>20){o.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let a=ve(i);if(a.op==="path")Ci(a.path)?t.add(a.path):o.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(a.op==="literal")return;if(a.op==="and"||a.op==="or")if(!Array.isArray(a.values)||!a.values.length||a.values.length>128)o.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let d of a.values){if(n<0)break;r(d,s+1)}else a.op==="not"||a.op==="exists"?r(a.value,s+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(a.op))?(r(a.left,s+1),r(a.right,s+1)):o.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return r(e,0),{paths:[...t],errors:[...new Set(o)]}}function ed(e){if(e?.readability===void 0)return[];let t=[],o=_t(e),n=ve(e.readability);(Object.keys(n).some(a=>!["variables","logic"].includes(a))||!Object.keys(n).length)&&t.push("WORKFLOW_READABILITY_INVALID");let r=ve(n.variables);n.variables!==void 0&&(typeof n.variables!="object"||Array.isArray(n.variables)||n.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(r).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[a,d]of Object.entries(r)){let c=ve(d);(!Ci(a)||!Uo(o,a))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a}`),(!Wt(c.label,160)||Object.keys(c).some(l=>!["label","unit","description"].includes(l))||c.unit!==void 0&&!Wt(c.unit,32)||c.description!==void 0&&!Wt(c.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${a}`)}let i=n.logic===void 0?[]:n.logic;(!Array.isArray(i)||i.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let s=new Set;for(let a of Array.isArray(i)?i.slice(0,32):[]){let d=ve(a),c=String(d.code||"");e.approvedDelegation&&c==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(c)||s.has(c)||!Wt(d.title,160)||!Wt(d.description,4e3)||Object.keys(d).some(l=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(l)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${c}`),s.add(c),(!["submission","node_input","completion"].includes(String(d.phase))||d.phase==="node_input"&&!ve(e.nodes)[String(d.nodeId)]||d.phase!=="node_input"&&d.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${c}`);for(let l of["inputPaths","outputPaths"]){let f=d[l];if(!(l==="outputPaths"&&f===void 0))if(!Array.isArray(f)||f.length>32||new Set(f).size!==f.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${c}:${l}`);else for(let p of f)(!Ci(p)||!Uo(o,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${c}:${String(p)}`)}if(d.source!==void 0){let l=ve(d.source);(!Wt(l.path,256)||String(l.path).startsWith("/")||String(l.path).includes("..")||String(l.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(l.digest))||l.symbol!==void 0&&!Wt(l.symbol,160)||Object.keys(l).some(f=>!["path","symbol","digest"].includes(f)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${c}`)}}for(let a of Object.values(ve(e.nodes))){let d=ve(a),c=Array.isArray(d.branches)?d.branches:[];for(let l of c){if(!l.when)continue;let f=Fn(l.when);t.push(...f.errors.map(p=>`${p}:${d.id}`));for(let p of f.paths)Uo(o,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${d.id}:${p}`)}}return[...new Set(t)]}function Mo(e,t){let o=_t(e),n=rt(e).regions,r=[],i=new Map,s=[];for(let l of Object.values(e.nodes)){if(l.kind==="approval")for(let[f,p,m]of[["approve",l.onApprove,"\u540C\u610F"],["reject",l.onReject,"\u62D2\u7EDD"]])p&&r.push({id:`${l.id}:${f}`,from:l.id,to:p,kind:f,label:m,variablePaths:[]});if(l.kind==="approval"||l.kind==="handle")for(let f of new Set(ot(l)))e.nodes[f]?.kind==="correction"&&r.push({id:`${l.id}:return:${f}`,from:l.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(l.kind==="parallel")for(let[f,p]of(l.branches||[]).entries()){let m=p.when?Fn(p.when):{paths:[],errors:[]};for(let A of m.paths)i.has(A)||i.set(A,new Set),i.get(A).add(l.id);r.push({id:`${l.id}:parallel:${p.id}`,from:l.id,to:p.target,kind:"branch",parallelBranch:!0,label:p.title||`\u5206\u652F ${f+1}`,priority:f+1,...p.when?{expression:p.when}:{},variablePaths:m.paths})}if(l.kind==="join"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u5168\u90E8\u5206\u652F\u5B8C\u6210\u540E\u7EE7\u7EED",variablePaths:[]}),l.kind==="handle"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u529E\u7406\u5B8C\u6210",variablePaths:[]}),l.kind==="correction"&&l.next&&r.push({id:`${l.id}:resubmit`,from:l.id,to:l.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u6309\u9000\u56DE\u8BBE\u7F6E\u7EE7\u7EED",variablePaths:[]}),l.kind==="cc"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),l.kind==="action"&&l.next){let f=Object.values(l.inputs||{}).flatMap(p=>p.source==="fact"?[p.path]:[]);for(let p of f)i.has(p)||i.set(p,new Set),i.get(p).add(l.id);r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:ie(l)?"\u53D1\u9001\u540E\u7EE7\u7EED":"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(l.kind==="condition"){for(let[f,p]of(l.branches||[]).entries()){let m=Fn(p.when);for(let A of m.paths)i.has(A)||i.set(A,new Set),i.get(A).add(l.id);r.push({id:`${l.id}:branch:${f}`,from:l.id,to:p.target,kind:"branch",label:p.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:p.when,variablePaths:m.paths}),s.push(...m.errors.map(A=>({code:A,path:l.id})))}l.otherwise&&r.push({id:`${l.id}:default`,from:l.id,to:l.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let a=[...e.readability?.logic||[]];if(e.approvedDelegation){let l=e.approvedDelegation,f=l.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";a.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[l.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[l.confirmationNodeId]?.title||l.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${l.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let c=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...a.flatMap(l=>[...l.inputPaths,...l.outputPaths||[]])])].slice(0,128).map(l=>{let f=Uo(o,l),p=e.readability?.variables?.[l],m=l.split("."),A=e.subject?.factProjection[m[0]],I=m[0]==="steps"?e.nodes[m[1]]:void 0;return f||s.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:l}),{path:l,label:p?.label||String(f?.schema.title||l),type:String(f?.schema.type||"unknown"),...p,required:f?.required||!1,usedBy:[...i.get(l)||[]],source:f&&I?.handler?{kind:"step_output",nodeId:I.id,handlerCode:I.handler.code,handlerVersion:I.handler.version}:f&&A&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[A,...m.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(l=>({id:l.id,kind:l.kind,title:l.title||l.id,...l.kind==="parallel"?{parallel:{joinNodeId:l.join,branchNodeIds:n.find(f=>f.parallelNodeId===l.id)?.branches.flatMap(f=>f.nodeIds)||[],branchCount:l.branches?.length||0}}:{},...l.binding?{binding:l.binding}:{},...l.mode?{mode:l.mode}:{},...l.outcome?{outcome:l.outcome}:{},...l.kind==="cc"?{emptyPolicy:l.emptyPolicy,notify:l.notify!==!1}:{},...l.kind==="approval"?{emptyPolicy:l.emptyPolicy||"block",initiatorApprovalPolicy:l.initiatorApprovalPolicy||"manual",...l.completionDeadline?{completionDeadline:{...l.completionDeadline}}:{}}:{},...ie(l)?{presentation:"notification"}:{},...l.kind==="action"&&l.handler&&!ie(l)?{businessStep:{handler:l.handler,inputs:l.inputs||{},outputPaths:Object.keys(ve(l.outputSchema).properties||{}).map(f=>`steps.${l.id}.${f}`)}}:{}})),edges:r,variables:c,logic:a,diagnostics:s}}function gu(e,t=[]){let o=r=>{let i=t.find(s=>s.path===r)?.label;return i&&i!==r?i:void 0},n=o(e);if(n)return n;for(let r=e.lastIndexOf(".");r>0;r=e.lastIndexOf(".",r-1)){let i=o(e.slice(0,r));if(!i)continue;let s=e.slice(r+1);return s==="value"?`${i}\uFF08\u503C\uFF09`:s==="label"?`${i}\uFF08\u663E\u793A\u540D\u79F0\uFF09`:`${i}.${s}`}return e}function jo(e,t=[],o=0){if(!e||o>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return gu(e.path,t);if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(s=>`\uFF08${jo(s,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${jo(e.value,t,o+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let n={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},r=e.left.op==="path"?e.left.path:void 0,i=r&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(s=>s.path===r)?.unit:void 0;return`${jo(e.left,t,o+1)} ${n[e.op]} ${jo(e.right,t,o+1)}${i?` ${i}`:""}`}function td(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&&td(n.fields,t+1)}return o.readonly===!0})}function Vn(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"||!td(e.taskPages?.[n.taskPageCode]?.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].some(r=>r==="edit"||r==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${o}`),(n.operationPolicy?.approve?.opinion==="required"||n.operationPolicy?.approve?.commentRequired===!0)&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${o}`))}return t}function w_(e,t,o,n,r){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&Vn({nodes:{node:e},...r?{taskPages:r}:{}}).length===0&&t!=="return_review"&&!!o&&n.user_id===o&&n.status==="active"&&n.participant_kind==="primary"&&["resolution","resolution_retry"].includes(n.source||"")&&!n.source_participant_id&&!n.delegate_authorization_id}var nd=20,od=200,_u=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function Si(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{})){if(r?.kind!=="cc"||((Object.keys(r).some(d=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(d))||typeof r.title!="string"||!r.title.trim()||r.title.length>255||typeof r.binding!="string"||!r.binding.trim()||r.binding.length>255||typeof r.next!="string"||!r.next.trim()||!e.nodes?.[r.next]||!["block","skip"].includes(r.emptyPolicy)||r.notify!==void 0&&typeof r.notify!="boolean")&&o.push(`WORKFLOW_CC_NODE_INVALID:${n}`),!t))continue;let i=t.bindings?.[r.binding];if(!i){o.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${n}`);continue}_u.includes(i.provider)||o.push(`WORKFLOW_CC_PROVIDER_INVALID:${n}`);let s=i.min??1,a=i.max??20;(!Number.isSafeInteger(s)||!Number.isSafeInteger(a)||s<1||a<s||a>200||i.provider==="fixed_users"&&(!Array.isArray(i.users)||!i.users.length||i.users.length>a))&&o.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${n}`)}return[...new Set(o)]}var Nt=["complete","approve","reject","save_form","return","transfer","delegate","add_assignee"],Bo=["fixed_users","app_role","app_role_in_scope"],Au=["single","any","all","sequence"],ft=e=>!!e&&typeof e=="object"&&!Array.isArray(e),it=(e,t)=>Object.keys(e).every(o=>t.includes(o)),Wn=(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 cn(e){return e.allowedOperations||(e.kind==="handle"?["complete","save_form","return","transfer","delegate"]:Nt.filter(t=>t!=="complete")).filter(t=>t!=="save_form"||!!e.taskPageCode)}function Eu(e,t){return t?.opinion!==void 0?t.opinion==="required":t?.commentRequired??e==="reject"}function Iu(e,t){return["transfer","delegate","add_assignee","return"].includes(e)?t?.opinion!==void 0?t.opinion==="required":t?.reasonRequired!==!1:!0}var dn=["none","optional","required"];function xt(e,t){return e==="save_form"?"none":t?.opinion?t.opinion:(["complete","approve","reject"].includes(e)?Eu(e,t):Iu(e,t))?"required":"optional"}function ln(e,t){return t?.minimumOpinion??(xt(e,t)==="required"?"required":"none")}function L_(e){return e.hasTaskPage&&(e.operationModel==null||e.operationModel==="configured-v1"&&e.allowedOperations?.includes("save_form")===!0)}function id(e,t,o={},n=!1){let r=["label","commentRequired","reasonRequired","opinion"];if(!ft(e)||!Object.keys(e).length||!it(e,n?[...r,"enabled"]:[...r,"minimumOpinion"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||t==="approve"&&!e.enabled)||e.opinion!==void 0&&(!dn.includes(e.opinion)||t==="save_form")||e.minimumOpinion!==void 0&&(!dn.includes(e.minimumOpinion)||t==="save_form")||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["complete","approve","reject"].includes(t))||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t))||e.opinion!==void 0&&[e.commentRequired,e.reasonRequired].some(i=>i!==void 0&&i!==(e.opinion==="required")))return!1;if(n&&(e.opinion!==void 0||e.commentRequired!==void 0||e.reasonRequired!==void 0)){let i=e.opinion??(e.commentRequired??e.reasonRequired?"required":"optional");if(dn.indexOf(i)<dn.indexOf(ln(t,o)))return!1}return!(!n&&e.minimumOpinion!==void 0&&dn.indexOf(xt(t,e))<dn.indexOf(e.minimumOpinion))}function yu(e){if(e.provider!=="conditional")return!!e.scope;try{return ae(e).some(t=>"scope"in t&&!!t.scope)}catch{return!1}}function ki(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{})){if(!ft(r))continue;let i=r.administration,s=r.operationPolicy;if(r.kind==="approval"||r.kind==="handle"){let d=cn(r);d.includes(r.kind==="handle"?"complete":"approve")||o.push(`WORKFLOW_NODE_FORWARD_OPERATION_REQUIRED:${n}`),d.includes("save_form")&&!r.taskPageCode&&o.push(`WORKFLOW_NODE_SAVE_PAGE_REQUIRED:${n}`),r.requiredOperations!==void 0&&(!Wn(r.requiredOperations,Nt,8)||r.requiredOperations.some(c=>!d.includes(c)))&&o.push(`WORKFLOW_NODE_REQUIRED_OPERATIONS_INVALID:${n}`)}if(r.kind==="cc"){(s!==void 0||i!==void 0&&(!ft(i)||!it(i,["assigneeProviders"])))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`),i?.assigneeProviders!==void 0&&!Wn(i.assigneeProviders,Bo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`),i?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[r.binding||""]?.scope&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`);continue}if(!["approval","handle"].includes(r.kind)){(i!==void 0||s!==void 0)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${n}`);continue}if(s!==void 0&&(!ft(s)||Object.keys(s).length>8||Object.entries(s).some(([d,c])=>!Nt.includes(d)||!cn(r).includes(d)||!id(c,d)))&&o.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${n}`),i===void 0)continue;if(!ft(i)||!it(i,["modes","assigneeProviders","operations"])){o.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${n}`);continue}i.modes!==void 0&&(!Wn(i.modes,Au,4)||!i.modes.includes(r.mode))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${n}`),i.assigneeProviders!==void 0&&!Wn(i.assigneeProviders,Bo,3)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${n}`);let a=t?.bindings[r.binding||""];a&&Array.isArray(i.assigneeProviders)&&i.assigneeProviders.includes("app_role_in_scope")&&!yu(a)&&o.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${n}`),i.operations!==void 0&&(!Wn(i.operations,Nt,8)||i.operations.some(d=>!cn(r).includes(d)))&&o.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${n}`)}return o}function Di(e,t,o,n,r){let i=[];if(!e||!ft(o)||!Object.keys(o).length||!it(o,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let s=o;if(s.assignee===void 0&&s.mode!==void 0&&t?.provider==="conditional")return Di(e,t,{...s,assignee:t},n,r);!s.assignee&&t?.provider==="supervisor_chain"&&t.continuous!==!1&&(s.mode||e.mode)!=="sequence"&&i.push("WORKFLOW_SUPERVISOR_CHAIN_SEQUENCE_REQUIRED"),Object.entries(s.operations||{}).some(([d,c])=>c?.enabled===!1&&e.requiredOperations?.includes(d))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_REQUIRED_OPERATION");for(let d of["title","description"])s[d]!==void 0&&(typeof s[d]!="string"||s[d].length>(d==="title"?255:1e3)||d==="title"&&!s[d].trim())&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let a=e.administration;if(s.mode!==void 0&&(!["approval","handle"].includes(e.kind)||!a?.modes?.includes(s.mode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),s.operations!==void 0&&(!["approval","handle"].includes(e.kind)||!ft(s.operations)||!Object.keys(s.operations).length||Object.keys(s.operations).length>8||Object.entries(s.operations).some(([d,c])=>!a?.operations?.includes(d)||!cn(e).includes(d)||!id(c,d,e.operationPolicy?.[d],!0)))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),s.assignee!==void 0){let d=s.assignee,c=a?.assigneeProviders||((e.kind==="approval"||e.kind==="handle")&&t&&Bo.includes(t.provider)?[t.provider]:[]);if(d?.provider==="conditional")if(e.emptyPolicy==="skip"&&i.push("WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED"),!r||!t)i.push("WORKFLOW_V2_NODE_CONFIGURATION_CONDITIONAL_CONTEXT_REQUIRED");else{let l=r.definition.nodes[r.nodeId];if(!l||!("binding"in l)||l.kind!==e.kind||l.binding!==e.binding)i.push("WORKFLOW_V2_NODE_CONFIGURATION_CONDITIONAL_CONTEXT_INVALID");else{"emptyPolicy"in l&&l.emptyPolicy==="skip"&&i.push("WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED"),i.push(...Di(l,void 0,{...s,assignee:void 0},r.definition.taskPages));let f="administration"in l?l.administration?.assigneeProviders:void 0;i.push(...Zt(d,{...r,definition:{...r.definition,nodes:{...r.definition.nodes,[r.nodeId]:{...l,..."mode"in l?{mode:s.mode||l.mode}:{}}}},frozenDefault:t,standardProviders:f||((l.kind==="approval"||l.kind==="handle")&&Bo.includes(t.provider)?[t.provider]:[])}))}}else if(ft(d)&&(!["fixed_users","app_role","app_role_in_scope"].includes(d.provider)||!it(d,d.provider==="fixed_users"?["provider","users"]:["provider","roleCode","roleCodes"])))if(!r||!t||!["approval","handle"].includes(e.kind))i.push("WORKFLOW_V2_NODE_CONFIGURATION_CONDITIONAL_CONTEXT_REQUIRED");else{let l=r.definition.nodes[r.nodeId];!l||!("binding"in l)||l.kind!==e.kind||l.binding!==e.binding?i.push("WORKFLOW_V2_NODE_CONFIGURATION_CONDITIONAL_CONTEXT_INVALID"):(i.push(...Di(l,void 0,{...s,assignee:void 0},r.definition.taskPages)),i.push(...Zt({provider:"conditional",cases:[{when:{op:"literal",value:!1},assignee:d}],otherwise:d},{...r,definition:{...r.definition,nodes:{...r.definition.nodes,[r.nodeId]:{...l,..."mode"in l?{mode:s.mode||l.mode}:{}}}},frozenDefault:t,standardProviders:l.kind==="approval"||l.kind==="handle"?l.administration?.assigneeProviders||[]:[]})))}else if(t?.selectedInputPath&&!["app_role","app_role_in_scope"].includes(d?.provider||"")&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"),!ft(d)||!["approval","handle","cc"].includes(e.kind)||!c.includes(d.provider)||d.provider==="app_role_in_scope"&&!t?.scope)i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY");else if(d.provider==="fixed_users"){let l=e.kind==="cc"?t?.min??1:e.emptyPolicy==="skip"?0:1,f=e.kind==="cc"?Math.min(t?.max??20,200):200;(!it(d,["provider","users"])||!Array.isArray(d.users)||d.users.length<l||d.users.length>f||new Set(d.users).size!==d.users.length||d.users.some(p=>typeof p!="string"||!p.trim()||p.length>255))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID")}else d.roleCodes!==void 0?(!it(d,["provider","roleCodes"])||qt({...d,...d.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!it(d,["provider","roleCode"])||typeof d.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(d.roleCode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return i.push(...Vn({nodes:{node:{...e,operationPolicy:rd(e,s).operationPolicy}},...n?{taskPages:n}:{}})),e.completionDeadline&&rd(e,s).operationPolicy.approve?.commentRequired===!0&&i.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),i}function rd(e,t){let o=Object.fromEntries(cn(e).flatMap(n=>{let r=n,i=t?.operations?.[r],s={...e.operationPolicy?.[r],...i?.label!==void 0?{label:i.label}:{},...i?.commentRequired!==void 0?{commentRequired:i.commentRequired}:{},...i?.reasonRequired!==void 0?{reasonRequired:i.reasonRequired}:{},...i?.opinion!==void 0?{opinion:i.opinion}:{}};return i?.opinion===void 0&&(i?.commentRequired!==void 0||i?.reasonRequired!==void 0)&&s.opinion!==void 0&&(s.opinion=i.commentRequired??i.reasonRequired?"required":"optional"),s.opinion!==void 0&&(["complete","approve","reject"].includes(r)&&(s.commentRequired=s.opinion==="required"),["transfer","delegate","add_assignee","return"].includes(r)&&(s.reasonRequired=s.opinion==="required")),Object.keys(s).length?[[r,s]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:cn(e).filter(n=>t?.operations?.[n]?.enabled!==!1),operationPolicy:o,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}function Ou(e){return e?e.provider==="fixed_users"?!it(e,["provider","users"]):e.provider==="app_role"||e.provider==="app_role_in_scope"?!it(e,["provider","roleCode","roleCodes"]):!0:!1}function v_(e,t){return Ou(t)?structuredClone(t):{...structuredClone(t),...e.selectedInputPath!==void 0?{selectedInputPath:e.selectedInputPath}:{},...e.min!==void 0?{min:e.min}:{},...e.max!==void 0?{max:e.max}:{},...e.delegatable!==void 0?{delegatable:e.delegatable}:{},...e.routing?{routing:structuredClone(e.routing)}:{},...t.provider==="app_role_in_scope"&&e.scope?{scope:structuredClone(e.scope)}:{}}}var sd=["supervisor_chain","fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function Li(e,t){let o=[];for(let[n,r]of Object.entries(e?.nodes||{}))r.kind==="cc"||r.emptyPolicy===void 0||(r.kind!=="approval"||!["block","skip"].includes(r.emptyPolicy)?o.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${n}`):r.emptyPolicy==="skip"&&t&&!sd.includes(t.bindings?.[r.binding||""]?.provider)&&o.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${n}`));return o}function $_(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&sd.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 ad(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 dd(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||dd(o.subtable.fields,t+1)))}function V_(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 cd(e){let t=[];for(let[o,n]of Object.entries(e?.nodes||{})){if(!n||typeof n!="object"||n.completionDeadline===void 0)continue;let r=n.completionDeadline;if(n.kind!=="approval"||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length!==2||Object.keys(r).some(s=>!["afterSeconds","action"].includes(s))||r.action!=="approve"||!Number.isInteger(r.afterSeconds)||r.afterSeconds<1||r.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${o}`);continue}n.allowedOperations&&!n.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${o}`);let i=n.taskPageCode?e.taskPages?.[n.taskPageCode]:void 0;(n.taskPageCode&&(!i||dd(i.fields))||[n.fieldPolicy?.default,...Object.values(n.fieldPolicy?.fields||{})].includes("edit_required")||n.operationPolicy?.approve?.opinion==="required"||n.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${o}`)}return t}var bu="openxiangda.workflow-rejection-notification/v1",x_=4096;function ld(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function un(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function vi(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function ud(e){let t=e?.rejectionNotification;return t===void 0?[]:!ld(t)||!vi(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!un(t.title,160)||!un(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:un(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function j_(e){if(!ld(e)||e.schemaVersion!==bu||e.recipient!=="record_last_modifier"||!un(e.title,160)||!un(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!vi(e,[...t,"userId"])||!un(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!vi(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 fd(e,t){let o=e.commandHandlers;if(o===void 0)return[];if(!o||typeof o!="object"||Array.isArray(o)||!Object.keys(o).length||Object.keys(o).some(r=>!["approve","reject","withdraw","resubmit"].includes(r)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let n=[];o.resubmit&&!Object.values(e.nodes||{}).some(r=>r.kind==="correction")&&n.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[r,i]of Object.entries(o)){if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(a=>!["operationCode","transitionPolicy","derivedSubjectFields"].includes(a))||i.transitionPolicy!==void 0&&(r!=="approve"||i.transitionPolicy!=="workflow")||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.operationCode||"")){n.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(i.derivedSubjectFields!==void 0){let a=i.derivedSubjectFields,d=new Set(Object.values(e.subject?.factProjection||{}));(r!=="resubmit"||!Array.isArray(a)||a.length<1||a.length>32||new Set(a).size!==a.length||a.some(c=>typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!d.has(c)||tn.has(c)||["createdBy","updatedBy","createdAt","updatedAt"].includes(c)||Object.values(e.taskPages||{}).some(l=>l.fields?.some(f=>f.code===c&&f.readonly!==!0))))&&n.push("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID")}if(!t)continue;let s=t.find(a=>a.code===i.operationCode);if(!s){n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(s.method!=="POST"||s.browser?.exposure!=="authenticated"||s.browser.behavior!=="controlled"||s.browser.idempotency!=="required"||s.browser.fileIntent||s.browser.subject?.resourceCode!==e.subject?.resourceCode||s.browser.subject?.inputField!=="recordId"||!s.platformAccess?.workflow?.codes?.includes(e.code)||!s.platformAccess.workflow.businessCommands?.includes(r))&&n.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(r=>Object.hasOwn(o,r))&&Object.values(e.nodes||{}).some(r=>r.kind==="approval"&&(r.emptyPolicy==="skip"||r.initiatorApprovalPolicy==="auto_approve"))&&n.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(n)]}var B_={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};function K_(e,t,o){if(!(t==="resubmit"&&o===!1))return e.commandHandlers?.[t]}var hu=["fixed_users","initiator","app_role","app_role_in_scope"],Nu=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Pi(e,t){let o=e?.launchPreflight;if(o===void 0)return[];if(!Nu(o)||Object.keys(o).join(",")!=="requiredApprovalNodes"||!Array.isArray(o.requiredApprovalNodes)||o.requiredApprovalNodes.length<1||o.requiredApprovalNodes.length>20||new Set(o.requiredApprovalNodes).size!==o.requiredApprovalNodes.length||o.requiredApprovalNodes.some(r=>typeof r!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(r)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let n=[];for(let r of o.requiredApprovalNodes){let i=e.nodes?.[r];if(!i||i.kind!=="approval"){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${r}`);continue}if(!t)continue;let s=t.bindings?.[i.binding||""];if(!s||s.provider==="conditional"&&ke(s).length){n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${r}`);continue}ae(s).some(a=>!hu.includes(a.provider)||a.candidateField!==void 0)&&n.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${r}`)}return n}var $i=e=>!!e&&typeof e=="object"&&!Array.isArray(e),wu=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,md=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,pd=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,J_=500,H_=262144;function gd(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!$i(t)||Object.keys(t).some(d=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(d))||!md.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!wu.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let o=[],n=e.nodes?.[t.confirmationNodeId];(!n||n.kind!=="approval"||n.mode!=="single"||n.emptyPolicy==="skip"||n.initiatorApprovalPolicy==="auto_approve"||n.completionDeadline||n.administration?.assigneeProviders?.length||n.administration?.modes?.some(d=>d!=="single")||n.allowedOperations?.some(d=>["transfer","delegate","add_assignee","admin_override"].includes(d)))&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let r=e.inputSchema?.properties?.[t.requestsField];(!r||r.type!=="array"||!Number.isSafeInteger(r.maxItems)||r.maxItems<1||r.maxItems>t.maxRequests||!r.items||r.items.type!=="object"||r.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&o.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(d=>d.kind==="end"&&d.outcome==="approved")||o.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let s=[e.startAt],a=new Set;for(;s.length;){let d=s.pop();if(d===t.confirmationNodeId||a.has(d))continue;a.add(d);let c=e.nodes?.[d];c&&(c.kind==="end"&&c.outcome==="approved"&&o.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),c.kind==="approval"&&s.push(c.onApprove,c.onReject),c.kind==="condition"&&s.push(c.otherwise,...(c.branches||[]).map(l=>l.target)),(c.kind==="cc"||c.kind==="action")&&s.push(c.next))}return[...new Set(o)]}function Y_(e,t){let o=t?.data?.[e.requestsField],n=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(o)||!o.length||o.length>e.maxRequests||o.length>500||new TextEncoder().encode(JSON.stringify(o)).byteLength>262144)&&n();let r=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],i=(d,c)=>typeof d=="string"&&d.trim().length>0&&d.length<=c,s=d=>{if(typeof d!="string")return!1;let c=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(d);if(!c)return!1;let[,l,f,p,m,A,I,O,b]=c,g=Number(l),y=Number(f),h=Number(p),E=[31,g%4===0&&(g%100!==0||g%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return y>=1&&y<=12&&h>=1&&h<=E[y-1]&&Number(m)<=23&&Number(A)<=59&&Number(I)<=59&&(O===void 0||Number(O)<=23&&Number(b)<=59)&&Number.isFinite(Date.parse(d))},a=o.map(d=>$i(d)?((Object.keys(d).some(c=>!r.includes(c))||!i(d.delegatorRoleSubjectKey,255)||!pd.test(d.delegatorRoleSubjectKey)||!i(d.delegateRoleSubjectKey,255)||!pd.test(d.delegateRoleSubjectKey)||!Number.isSafeInteger(d.delegatorRoleSubjectRevision)||d.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(d.expectedDelegateRevision)||d.expectedDelegateRevision<1||!$i(d.delegate)||Object.keys(d.delegate).some(c=>!["value","label"].includes(c))||!i(d.delegate.value,255)||!i(d.delegate.label,200)||!(d.workflowCode===null||i(d.workflowCode,128)&&md.test(d.workflowCode))||!(d.nodeId===null||i(d.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(d.nodeId)&&d.workflowCode)||!s(d.validFrom)||!s(d.validTo)||Date.parse(d.validFrom)>=Date.parse(d.validTo)||!i(d.reason,4e3)||d.key!==void 0&&!i(d.key,128))&&n(),{...d,delegate:{value:d.delegate.value,label:d.delegate.label},validFrom:new Date(d.validFrom).toISOString(),validTo:new Date(d.validTo).toISOString()}):n());return e.confirmer==="delegate"&&new Set(a.map(d=>d.delegate.value)).size!==1&&n(),a}var Ru=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function _d(e){let t=e?.nodes||{},o=Object.values(t).filter(a=>a?.kind==="correction");if(!o.length)return[];let n=[],r=a=>a?.kind==="approval"?[a.onApprove,a.onReject]:a?.kind==="parallel"?(Array.isArray(a.branches)?a.branches:[]).map(d=>d.target):a?.kind==="condition"?[...(Array.isArray(a.branches)?a.branches:[]).map(d=>d.target),a.otherwise]:a?.kind==="action"||a?.kind==="cc"||a?.kind==="handle"||a?.kind==="join"?[a.next]:[],i=new Set,s=[e.startAt];for(;s.length;){let a=s.pop();i.has(a)||(i.add(a),s.push(...r(t[a])))}for(let a of o){(!Ru(a)||Object.keys(a).some(c=>!["id","kind","title","taskPageCode","next","reminders"].includes(c))||typeof a.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(a.id)||["__proto__","prototype","constructor"].includes(a.id)||t[a.id]!==a||typeof a.title!="string"||!a.title.trim()||a.title.length>255||typeof a.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(a.taskPageCode))&&n.push("WORKFLOW_CORRECTION_NODE_INVALID"),(a.next!==e.startAt||t[a.next]?.kind==="correction")&&n.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(i.has(a.id)||Object.values(t).some(c=>r(c).includes(a.id)))&&n.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(c=>(c?.kind==="approval"||c?.kind==="handle")&&i.has(c.id)&&ot(c).includes(a.id))||n.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let d=e.taskPages?.[a.taskPageCode];!d||!Array.isArray(d.fields)?n.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):d.fields.some(c=>c?.subtable&&Object.values(e.subject?.factProjection||{}).some(l=>l===c.code||l.startsWith(`${c.code}.`)))&&n.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(n)]}var Ko=class extends Error{constructor(o){super(o);this.code=o}code},eA=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function Ad(e,t,o){let n=i=>{throw new Ko(i)};t.length>100&&n("DATE_TRIGGER_PROJECTION_LIMIT");let r=new Set;for(let i of t){let s=i.filter?.resourceCodes||[];if(Array.isArray(s)||n("DATE_TRIGGER_PROJECTION_INVALID"),s.length&&!s.includes(e))continue;let a=i.payload?.fields||[];(!Array.isArray(a)||a.length>32)&&n("DATE_TRIGGER_PROJECTION_LIMIT");for(let d of a)(typeof d!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(d)||["__proto__","constructor","prototype"].includes(d))&&n("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),r.add(d)}if(r.size>64&&n("DATE_TRIGGER_PROJECTION_LIMIT"),o!==void 0){let i=o?.schema?.fields??o?.fields;Array.isArray(i)||n("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let s=new Map(i.map(a=>[a.code,a]));for(let a of r){let d=s.get(a);d||n("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),d.type==="subtable"&&n("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),o.fieldPolicies?.[a]?.mask==="omit"&&n("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...r].sort()}function tA(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 Ko("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var Tu=200,Vi=1024*1024,Cu=65536,yd=lt,Ed=en,jt=new Set(["__proto__","prototype","constructor"]),Od=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,jn=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Id=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,he=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),pt=(e,t)=>he(e)&&Object.keys(e).every(o=>t.includes(o)&&!jt.has(o)),qo=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},bd=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function Rt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((n,r)=>Rt(n,t[r]));if(!he(e)||!he(t))return!1;let o=Object.keys(e);return o.length===Object.keys(t).length&&o.every(n=>Object.hasOwn(t,n)&&Rt(e[n],t[n]))}function Fi(e,t){let o=t.split(".");if(!(o.some(n=>!Od.test(n)||jt.has(n))||o.length>12))return o.reduce((n,r)=>he(n)&&Object.hasOwn(n,r)?n[r]:void 0,e)}function wt(e,t){switch(e.op){case"literal":return e.value;case"path":return Fi({values:t},e.path);case"and":return e.values.every(o=>!!wt(o,t));case"or":return e.values.some(o=>!!wt(o,t));case"not":return!wt(e.value,t);case"exists":return!bd(wt(e.value,t));default:{let o=wt(e.left,t),n=wt(e.right,t);return e.op==="eq"?Rt(o,n):e.op==="neq"?!Rt(o,n):e.op==="in"?Array.isArray(n)&&n.some(r=>Rt(r,o)):e.op==="contains"?Array.isArray(o)?o.some(r=>Rt(r,n)):typeof o=="string"&&typeof n=="string"&&o.includes(n):typeof o!="number"||typeof n!="number"||!Number.isFinite(o)||!Number.isFinite(n)?!1:e.op==="gt"?o>n:e.op==="gte"?o>=n:e.op==="lt"?o<n:o<=n}}}function xn(e,t,o=0,n={nodes:0}){if(o>8||++n.nodes>64||!he(e))return!1;if(e.op==="literal")return pt(e,["op","value"])&&Object.hasOwn(e,"value")&&qo(e.value)<=4096&&Un(e.value);if(e.op==="path"){if(!pt(e,["op","path"])||typeof e.path!="string")return!1;let r=e.path.split(".");return r[0]==="values"&&r.length>=2&&r.length<=8&&t.has(r[1])&&r.every(i=>jn.test(i)&&!jt.has(i))}return["not","exists"].includes(e.op)?pt(e,["op","value"])&&xn(e.value,t,o+1,n):["and","or"].includes(e.op)?pt(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(r=>xn(r,t,o+1,n)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&pt(e,["op","left","right"])&&xn(e.left,t,o+1,n)&&xn(e.right,t,o+1,n)}function zo(e,t,o,n=Ed){let r=[],i=e.taskPages;if(i!==void 0&&(!he(i)||Object.keys(i).length===0||Object.keys(i).length>16||qo(i)>Cu))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[s,a]of Object.entries(i||{})){let d=`taskPages.${s}`;if(!Od.test(s)||jt.has(s)||!pt(a,["title","fields"])||typeof a.title!="string"||!a.title.trim()||a.title.length>160||!Array.isArray(a.fields)||!a.fields.length||a.fields.length>Tu){r.push(`WORKFLOW_TASK_PAGE_INVALID:${d}`);continue}let c=new Set(a.fields.map(p=>p?.code));c.size!==a.fields.length&&r.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${d}`);let l=0,f=new Set;for(let p of a.fields){if(!pt(p,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!jn.test(p.code)||jt.has(p.code)||["readonly","required"].some(m=>p[m]!==void 0&&typeof p[m]!="boolean")||p.readonly&&(p.required||p.requiredWhen)){r.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${d}`);continue}for(let m of["visibleWhen","requiredWhen"])p[m]!==void 0&&!xn(p[m],c)&&r.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${d}.${p.code}.${m}`);if(t){let m=t.get(p.code);if((!m||m.system||m.hidden||m.type==="serial-number"||!p.readonly&&m.widget==="readonly"||!p.readonly&&m.type==="subtable"&&!p.subtable||p.subtable&&m.type!=="subtable")&&r.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${d}.${p.code}`),p.subtable&&m?.subtable){let A=m.subtable;l+=A.maxRows??20,(f.has(A.resourceCode)||!Number.isSafeInteger(A.maxRows??20)||(A.maxRows??20)<1||(A.maxRows??20)>yd||!jn.test(A.foreignKey)||!jn.test(A.orderField)||A.foreignKey===A.orderField)&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`),f.add(A.resourceCode);let I=o?.get(A.resourceCode);o&&(!I||!["uuid","resource-ref.single"].includes(I.get(A.foreignKey)?.type||"")||I.get(A.orderField)?.type!=="number.integer")&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`);for(let O of Array.isArray(p.subtable.fields)?p.subtable.fields:[]){if(!O||typeof O.code!="string")continue;let b=I?.get(O.code);(O.code===A.foreignKey||O.code===A.orderField||I&&(!b||b.system||b.hidden||b.type==="subtable"||!O.readonly&&(b.widget==="readonly"||b.type==="serial-number")))&&r.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${d}.${p.code}.${O.code}`)}}else p.subtable&&t&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`)}p.subtable&&(p.readonly||!pt(p.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(m=>p.subtable?.[m]!==void 0&&typeof p.subtable[m]!="boolean")||!Array.isArray(p.subtable.fields)||p.subtable.fields.some(m=>m?.subtable)?r.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${d}.${p.code}`):r.push(...zo({taskPages:{child:{title:"\u5B50\u884C",fields:p.subtable.fields}}},o?.get(t?.get(p.code)?.subtable?.resourceCode||"")).map(m=>`${m}:${d}.${p.code}`)))}(l>Math.min(n,Ed)||l<0||!Number.isSafeInteger(l)||!Number.isSafeInteger(n)||n<1)&&r.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${d}`)}for(let[s,a]of Object.entries(e.nodes||{}))he(a)&&a.taskPageCode!==void 0&&(!["approval","handle","correction"].includes(a.kind)||typeof a.taskPageCode!="string"||!he(i)||!Object.hasOwn(i,a.taskPageCode)?r.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${s}`):Array.isArray(i[a.taskPageCode]?.fields)&&i[a.taskPageCode].fields.some(d=>d&&(a.fieldPolicy?.fields?.[d.code]||a.fieldPolicy?.default)==="hidden")&&r.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${s}`));return r}function hd(e,t){return e.fields.map(o=>({code:o.code,visible:o.visibleWhen===void 0||!!wt(o.visibleWhen,t),readonly:o.readonly===!0,required:o.required===!0||o.requiredWhen!==void 0&&!!wt(o.requiredWhen,t)}))}var st=class extends Error{constructor(o,n){super(o);this.code=o;this.field=n}code;field;rowIndex;childField};function rA(e,t){return t.map(o=>({key:String(o.id),id:String(o.id),revision:Number(o.revision),state:"persisted",values:Object.fromEntries(hd({title:"\u5B50\u884C",fields:e.fields},o).filter(n=>n.visible&&!n.readonly).map(n=>[n.code,o[n.code]??null]))}))}function iA(e,t,o,n,r,i=!0,s=0){let a=e.subtable,d=m=>{throw new st(m,e.code)};if(!a||!Number.isSafeInteger(t)||t<1||t>yd||!Number.isSafeInteger(s)||s<0||s>t||!Array.isArray(n)||n.length>2*t||qo(n)>Vi||!Un(n))return d("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(o.map(m=>[String(m.id),m])),l=new Set,f=new Set,p=[];for(let m of n){if(!pt(m,["key","state","id","revision","values"])||typeof m.key!="string"||!Id.test(m.key)||l.has(m.key)||!["created","persisted","deleted"].includes(m.state)||!he(m.values))return d("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(l.add(m.key),m.state==="created"){if(!a.create||m.id!==void 0||m.revision!==void 0||c.has(m.key))return d("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof m.id!="string"||m.id!==m.key||!Id.test(m.id)||f.has(m.id)||!Number.isSafeInteger(m.revision)||m.revision<1||!c.has(m.id))return d("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(f.add(m.id),i&&Number(c.get(m.id).revision)!==m.revision)return d("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(m.state==="deleted"){if(!a.delete||Object.keys(m.values).length)return d("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{Su({title:e.code,fields:a.fields},m.id?c.get(m.id):{},m.values,r)}catch(A){if(!(A instanceof st))throw A;let I=new st(A.code,e.code);throw I.rowIndex=p.length,A.field!==void 0&&(I.childField=A.field),I}p.push(m)}if(f.size!==c.size)return d("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return d("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(r&&p.length<s)return d("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!a.reorder){let m=o.filter(I=>p.some(O=>O.id===String(I.id))).map(I=>String(I.id)),A=p.filter(I=>I.state==="persisted").map(I=>I.id);if(!Rt(m,A)||p.some((I,O)=>I.state==="created"&&p.slice(O+1).some(b=>b.state==="persisted")))return d("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return n}function Un(e,t={members:0},o=0){return++t.members>5e4||o>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=Vi:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(n=>Un(n,t,o+1)):he(e)&&Object.entries(e).every(([n,r])=>!jt.has(n)&&Un(r,t,o+1))}function Su(e,t,o,n){if(!he(o)||qo(o)>Vi||!Un(o))throw new st("WORKFLOW_TASK_FORM_VALUES_INVALID");let r={...t,...o},i=new Map(hd(e,r).map(s=>[s.code,s]));for(let s of Object.keys(o)){let a=i.get(s);if(!a||a.readonly||!a.visible)throw new st("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",s)}if(n)for(let s of i.values()){let a=r[s.code],d=e.fields.find(c=>c.code===s.code)?.subtable&&Array.isArray(a)?a.every(c=>he(c)&&c.state==="deleted"):bd(a);if(s.visible&&!s.readonly&&s.required&&d)throw new st("WORKFLOW_TASK_FORM_REQUIRED",s.code)}return r}function sA(e,t,o){let n=JSON.parse(JSON.stringify(t));for(let[s,a]of Object.entries(e.subject?.factProjection||{})){let d=s.split(".");if(!d.length||d.length>12||s.length>128||d[0]==="steps"||d.some(l=>!jn.test(l)||jt.has(l)))throw new st("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(o,a))throw new st("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",a);let c=n;for(let l of d.slice(0,-1))c=c[l]=he(c[l])?c[l]:{};c[d.at(-1)]=o[a]===void 0?void 0:JSON.parse(JSON.stringify(o[a]))}let r=new Set,i=Object.values(e.nodes||{}).filter(s=>s.kind==="action");for(let s=0;s<=i.length;s++){let a=!1;for(let d of i)he(n.steps)&&Object.hasOwn(n.steps,d.id)&&Object.values(d.inputs||{}).some(c=>c.source==="fact"&&!Rt(Fi(t,c.path),Fi(n,c.path)))&&(delete n.steps[d.id],r.add(d.id),a=!0);if(!a)break}return{facts:n,invalidatedNodeIds:[...r].sort()}}function aA(e,t,o){let n=e.nodes||{};for(let r of o){let i=new Set,s=new Map,a=d=>{if(d===r)return!0;if(s.has(d))return s.get(d);if(i.has(d)||i.size>200)return!1;let c=n[d];if(!he(c)||c.kind==="end")return!1;i.add(d);let l=c.kind==="approval"?[c.onApprove]:c.kind==="condition"?[...(c.branches||[]).map(p=>p.target),c.otherwise]:[c.next],f=l.length>0&&l.every(p=>typeof p=="string"&&a(p));return i.delete(d),s.set(d,f),f};if(!a(t))return!1}return!0}var Wi="^[A-Za-z][A-Za-z0-9_]{0,62}$",Nd="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",lA={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:Nd},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:Wi},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:Wi}}}}}}};function Go(e){let t=n=>!!(n&&typeof n=="object"&&!Array.isArray(n)),o=n=>typeof n=="string"&&new RegExp(Wi).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(Nd).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(n=>!t(n)||Object.keys(n).some(r=>!["fieldCode","fieldCodes"].includes(r))||!o(n.fieldCode)||!Array.isArray(n.fieldCodes)||n.fieldCodes.length<1||n.fieldCodes.length>200||new Set(n.fieldCodes).size!==n.fieldCodes.length||n.fieldCodes.some(r=>!o(r)))||new Set(e.subtables.map(n=>n.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function uA(e){return Go(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 wd(e,t,o){Go(e);let n=a=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${a}`)},r=t.get(e.resourceCode);r||n("RESOURCE_MISSING");let i=new Set,s=0;for(let a of e.subtables){let d=r.get(a.fieldCode),c=d?.subtable,l=t.get(c?.resourceCode);(d?.type!=="subtable"||!l||c.resourceCode===e.resourceCode||i.has(c.resourceCode))&&n("RELATION_INVALID"),i.add(c.resourceCode);let f=c.maxRows??20;(!Number.isSafeInteger(f)||f<1||f>lt)&&n("BUDGET_EXCEEDED"),s+=f;for(let p of a.fieldCodes){let m=l.get(p);(!m||["serial-number","subtable"].includes(m.type)||[c.foreignKey,c.orderField].includes(p))&&n("FIELD_INVALID"),["file","image","signature","text.rich"].includes(m.type)&&!o.some(A=>A.resourceCode===c.resourceCode&&A.fieldCodes.includes(p)&&A.intents.includes("create"))&&n("FILE_ACCESS_REQUIRED")}}s>en&&n("BUDGET_EXCEEDED")}import*as er from"crypto";var Rd="native-4",xi="2.0.0-alpha.5",Td={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-role-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.high-density-artifact-capacity":"1.0.0","application.extended-configuration-bytes":"1.0.0","application.development-configuration":"2.0.0","authz.native-batch-explain":"1.0.0","authz.organizations":"1.0.0","authz.directory-roles":"1.0.0","data.organizations":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data.rich-text":"1.0.0","data-api-v2":"1.1.0","data.service-mutations":"1.0.0","data.extended-owned-subtable-capacity":"1.0.0","data.aggregate-owned-subtable-capacity":"1.0.0","data.extended-field-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.field-source-contexts":"1.0.0","application.source-agents":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.selected-departments":"1.0.0","directory.current-classes":"1.0.0","data.transaction-time-values":"1.0.0","data.record-set-assertions":"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.worker-effects":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.approval-business-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.parent-read-policy":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.conditional-assignment":"1.0.0","workflow.role-union":"1.0.0","workflow.role-input-selection":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.correction-derived-subject-facts":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.platform-notify":"1.0.0","workflow.reminders":"1.0.0","workflow.supervisor-chain":"1.0.0","workflow.return-policy":"1.0.0","workflow.handling-nodes":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","workflow.step-data-transaction":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","notification-hub-v2.event-tasks":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var q=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:512,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function Cd(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 ji(e){return(e.authz?.roles?.length||0)>256}function Ui(e){let t=(Array.isArray(e.agents)?e.agents:[]).reduce((o,n)=>o+(Array.isArray(n?.tasks)?n.tasks.length:0),0)+(e.data?.resources||[]).filter(o=>o.status!=="retired").reduce((o,n)=>o+Cd(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 _e=Object.freeze({legacyConfigBytes:4194304,configBytes:8388608,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4}),fn=Object.freeze({nodes:5e5});function Mi(e){return Buffer.byteLength(re(e),"utf8")>_e.legacyConfigBytes}function Sd(e,t){let o=0,n=[[e][Symbol.iterator]()];for(;n.length;){let r=n[n.length-1].next();if(r.done){n.pop();continue}if(++o>t)return!0;if(Array.isArray(r.value))n.push(r.value.values());else if(r.value&&typeof r.value=="object"){let i=r.value;n.push((function*(){for(let s of Object.keys(i))i[s]!==void 0&&(yield i[s])})())}}return!1}function Jo(e){return Sd(e,_e.legacyNodes)}function Ho(e){return Sd(e,_e.extendedNodes)}var Mn=["openxiangda.workflow.task.reminded.v2","openxiangda.workflow.node.notified.v2","openxiangda.workflow.node.skipped.v2","openxiangda.workflow.step.requested.v2","openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"];function Bi(e){let t=e.flatMap(n=>Object.values(n.definition.nodes)),o=t.some(n=>n.kind==="action"&&!ie(n));return Mn.filter(n=>n==="openxiangda.workflow.task.reminded.v2"?t.some(r=>r.reminders):n==="openxiangda.workflow.node.notified.v2"?t.some(ie):n==="openxiangda.workflow.node.skipped.v2"?t.some(r=>r.kind==="approval"&&r.emptyPolicy==="skip"):n.startsWith("openxiangda.workflow.step.")?o:!0)}var Du="openxiangda.config-bundle/v3",Gd="openxiangda.contract-bundle/v3",Dd="openxiangda.native-configuration-projection/v1",Bn=Rd,ku=/^[a-f0-9]{64}$/,Lu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,vu=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Pu=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,$u=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Fu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Vu=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,kd=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,Wu=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,xu=/^[A-Z][A-Z0-9_]*$/,ju=/^[a-z][a-z0-9-]{2,63}$/,Uu=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Mu=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Bu=16,Ku=2*1024,qu=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"]),zu=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Gu=new Set(["complete","save_form","approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Ju=_e.configBytes,Hu=_e.contractBytes,Yu=_e.depth,qi=_e.stringBytes,Xu="openxiangda.event-handler-manifest/v2",Jd="openxiangda.application-route-manifest/v3",Ld=64,Hd=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),zi=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Zu=new Set(Mn),Gi=class extends Error{code;pointer;identifiers;constructor(t,o,n={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=o,this.identifiers=Object.fromEntries(Object.entries(n).slice(0,8).map(([r,i])=>[r,String(i).slice(0,128)]))}};function wE(e){let t=k(e.appCode,"/appCode",128);Lu.test(t)||_("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let o=Hi(e.expectedConfigDigest,"/expectedConfigDigest"),n=Hi(e.expectedContractDigest,"/expectedContractDigest"),r=Kd(e.configBytes,Ju,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),i=Kd(e.contractBytes,Hu,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");qd(r,o,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),qd(i,n,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let s=Bd(r,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),a=Bd(i,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Yo(s,"/config",fn.nodes),Yo(a,"/contracts",fn.nodes),Ho(s)||Yo(a,"/contracts",_e.extendedNodes),Jo(s)||Yo(a,"/contracts",_e.legacyNodes);let d=s,c=a;nf(d,t),of(c,t,o);let l=rf(d,o,c.generatorVersion);qf(l,c,d),re(l)!==re(c)&&_("NATIVE_CONTRACT_CLOSURE_MISMATCH",Yi(l,c,"/contracts"));let f={authz:{appCode:t,...d.authz,perspectives:d.perspectives,capabilityCatalog:l.capabilities},data:{appCode:t,resources:d.data.resources,resourceContracts:l.resources,...l.concurrency?{concurrency:l.concurrency}:{},...l.subjectReadSurfaces?{subjectReadSurfaces:l.subjectReadSurfaces}:{}},events:{appCode:t,...d.events,consumers:l.eventConsumers,producers:l.eventProducers,handlerManifest:l.eventHandlerManifest,eventTypes:l.eventTypes,capturePlans:ef({resources:d.data.resources,dataPolicies:d.authz.dataPolicies,subscriptions:l.eventConsumers,capturePolicies:d.events.capturePolicies})},workflows:{appCode:t,...d.workflows,contracts:l.workflows},runtime:{appCode:t,requirements:d.runtime,backend:d.backend,frontend:d.frontend},contracts:l},p={authz:pn(f.authz),data:pn(f.data),events:pn(f.events),workflows:pn(f.workflows),runtime:pn(f.runtime),contracts:pn(f.contracts)},m={configDigest:o,contractDigest:n,generatorVersion:c.generatorVersion},A=Qu(d),I={schemaVersion:Dd,compilerContractVersion:Bn,appCode:t,source:m,projections:p,requiredPlatformCapabilities:A,aggregateDigest:ee({schemaVersion:Dd,compilerContractVersion:Bn,appCode:t,source:m,requiredPlatformCapabilities:A,projectionDigests:Object.fromEntries(Object.entries(p).map(([O,b])=>[O,b.digest]))})};return ac(I)}function vd(e,t){let o=e.subject,n=t.find(i=>i.code===o?.resourceCode),r=new Set(Object.values(o?.factProjection||{}));return!!n?.schema?.fields?.some(i=>i.type==="subtable"&&r.has(i.code))}function Qu(e){let t=e.authz.roles,o=e.data.resources,n=e.backend.operations,r=n.filter(u=>u.platformAccess?.directory?.mode==="current-initiator"&&u.platformAccess.directory.fields.includes("phone")),i=(e.data.concurrency?.commands||[]).filter(u=>u.execution?.directory?.mode==="current-initiator"&&u.execution.directory.fields.includes("phone")),s=t.some(u=>u.capabilities.some(E=>E.endsWith(":directory:read")))||o.some(u=>u.schema.fields.some(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type)))||n.some(u=>u.platformAccess?.directory||u.platformAccess?.selectedDepartments||u.platformAccess?.directoryClasses),a=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),d=n.some(u=>u.platformAccess?.managedFiles||u.platformAccess?.managedFileCopies)||e.events.subscriptions.some(u=>u.platformAccess?.managedFileCopies),c=e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)||n.some(u=>u.platformAccess?.notification)||e.events.subscriptions.some(u=>u.platformAccess?.notification),l=(u,E,w=!1)=>{let S=o.find(T=>T.code===u.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(u.definition.taskPages||{}).some(T=>T.fields.some(C=>{if(C.readonly)return!1;let v=S.find(H=>H.code===C.code);if(!w&&v&&E.includes(v.type))return!0;if(!C.subtable||!v?.subtable)return!1;let P=o.find(H=>H.code===v.subtable.resourceCode)?.schema.fields||[];return C.subtable.fields.some(H=>!H.readonly&&P.some(ne=>ne.code===H.code&&E.includes(ne.type)))}))},f=e.workflows.definitions.filter(u=>l(u,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(u=>l(u,["signature","text.rich"])),m=e.workflows.definitions.filter(u=>l(u,["file","image","signature","text.rich"],!0)),A=e.workflows.definitions.filter(u=>u.launch.mode==="standalone"||u.launch.mode==="hidden-handoff"),I=n.some(u=>u.platformAccess?.workflow)||A.length>0,O=A.filter(u=>{let E=u.launch.submission;if(!E)return!1;let w=o.find(S=>S.code===u.definition.subject.resourceCode);return[E.create,E.existing].some(S=>S&&Object.values(S.inputs).some(T=>T.source==="field"&&w?.schema.fields.some(C=>C.code===T.fieldCode&&C.type.startsWith("resource-ref.")&&C.source)))}),b={resources:o},g={perspectives:e.perspectives,authz:e.authz},y={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:n.map(u=>({code:u.code,method:u.method,path:u.path,capability:u.capability,platformAccess:u.platformAccess||null,...u.browser?{browser:u.browser}:{},ai:u.ai||null}))}};return[...ji(e)?[{code:"application.extended-role-capacity",declaration:{roles:e.authz.roles.length,maximum:q.roles}}]:[],...Mi(e)?[{code:"application.extended-configuration-bytes",declaration:{legacyConfigBytes:_e.legacyConfigBytes,configBytes:_e.configBytes}}]:[],...Jo(e)?[{code:"application.extended-artifact-capacity",declaration:_e}]:[],...Ho(e)?[{code:"application.high-density-artifact-capacity",declaration:fn}]:[],...e.agents?.length?[{code:"application.source-agents",declaration:e.agents}]:[],...Ui(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((u,E)=>u+E.items.length,0)}}]:[],...o.some(u=>u.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:o.filter(u=>u.uniqueKeys?.length).map(u=>({code:u.code,uniqueKeys:u.uniqueKeys}))}]:[],...e.data.concurrency?[{code:"data.managed-concurrency",declaration:e.data.concurrency}]:[],...e.data.concurrency?.commands.some(u=>u.mode==="durable")?[{code:"data.managed-concurrency.durable",declaration:e.data.concurrency}]:[],...o.some(u=>u.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:o.filter(u=>u.decimalReservationLifecycle).map(u=>({code:u.code,decimalReservationLifecycle:u.decimalReservationLifecycle}))}]:[],...n.some(u=>u.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:n.filter(u=>u.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(yi)?[{code:"data.parent-read-policy",declaration:e.authz.dataPolicies.filter(yi)}]:[],...e.authz.dataPolicies.some(u=>u.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(u=>u.publicRead)}]:[],...n.some(u=>u.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:n.filter(u=>u.platformAccess?.roleAssertions?.actorAuthority)}]:[],...n.some(u=>u.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:n.filter(u=>u.platformAccess?.workflowStage)}]:[],...n.some(u=>u.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:n.filter(u=>u.platformAccess?.recordEdit)}]:[],...n.some(u=>u.platformAccess?.decimalReservation)||e.events.subscriptions.some(u=>u.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...n.filter(u=>u.platformAccess?.decimalReservation).map(u=>({code:u.code,decimalReservation:u.platformAccess.decimalReservation})),...e.events.subscriptions.filter(u=>u.platformAccess?.decimalReservation).map(u=>({subscriptionCode:u.code,decimalReservation:u.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:y},{code:"authz.native-batch-explain",declaration:g},{code:"authz.native-management",declaration:g},{code:"deployment.durable-runs",declaration:y.backend},{code:"deployment.platform-executor",declaration:y.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...o.length?[{code:"data-api-v2",declaration:b},{code:"data.native-golden-crud",declaration:b}]:[],...o.some(u=>u.recordComments!==void 0)?[{code:"data.record-comments",declaration:b}]:[],...o.some(u=>u.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:b}]:[],...o.some(u=>u.recordPrint!==void 0)?[{code:"data.record-print",declaration:b}]:[],...o.some(u=>u.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:b}]:[],...o.some(Qs)?[{code:"data.audit-read-access",declaration:b}]:[],...o.some(u=>u.schema.fields.some(E=>/^(resource-ref|user|department)\.(single|multiple)$/.test(E.type)))||e.authz.scopeDimensions.some(u=>u.valueSource)?[{code:"data.field-source-contexts",declaration:{resources:o.map(u=>({code:u.code,fields:u.schema.fields.filter(E=>/^(resource-ref|user|department)\.(single|multiple)$/.test(E.type))})),dimensions:e.authz.scopeDimensions.filter(u=>u.valueSource)}}]:[],...s?[{code:"directory-v2",declaration:{roles:t.map(u=>({code:u.code,capabilities:u.capabilities.filter(E=>E.endsWith(":directory:read"))})),resources:o.map(u=>({code:u.code,fields:u.schema.fields.filter(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type))})),operations:n.filter(u=>u.platformAccess?.directory).map(u=>({code:u.code,directory:u.platformAccess.directory}))}}]:[],...t.some(u=>u.organizationReach)?[{code:"authz.organizations",declaration:t.filter(u=>u.organizationReach).map(u=>({code:u.code,organizationReach:u.organizationReach}))}]:[],...e.authz.directoryRoleSources?.length?[{code:"authz.directory-roles",declaration:e.authz.directoryRoleSources}]:[],...o.some(u=>u.organization&&u.organization.mode!=="none")?[{code:"data.organizations",declaration:o.filter(u=>u.organization&&u.organization.mode!=="none").map(u=>({code:u.code,organization:u.organization}))}]:[],...n.some(u=>u.platformAccess?.transactionTime)?[{code:"data.transaction-time-values",declaration:n.filter(u=>u.platformAccess?.transactionTime).map(u=>({code:u.code,transactionTime:u.platformAccess.transactionTime}))}]:[],...n.some(u=>u.platformAccess?.transactionTime?.recordSetAssertions)?[{code:"data.record-set-assertions",declaration:n.filter(u=>u.platformAccess?.transactionTime?.recordSetAssertions).map(u=>({code:u.code,transactionTime:u.platformAccess.transactionTime}))}]:[],...n.some(u=>u.platformAccess?.directoryClasses)?[{code:"directory.current-classes",declaration:n.filter(u=>u.platformAccess?.directoryClasses).map(u=>({code:u.code,directoryClasses:u.platformAccess.directoryClasses}))}]:[],...n.some(u=>u.platformAccess?.selectedDepartments)?[{code:"directory.selected-departments",declaration:n.filter(u=>u.platformAccess?.selectedDepartments).map(u=>({code:u.code,selectedDepartments:u.platformAccess.selectedDepartments}))}]:[],...n.some(u=>u.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:n.filter(u=>u.platformAccess?.directory?.mode==="selected-user").map(u=>({code:u.code,directory:u.platformAccess.directory}))}]:[],...r.length||i.length?[{code:"directory.current-initiator-phone",declaration:{operations:r.map(u=>({code:u.code,directory:u.platformAccess.directory})),commands:i.map(u=>({code:u.code,directory:u.execution.directory}))}}]:[],...e.data.resources.some(u=>u.schema.fields.some(E=>E.type==="text.rich"))?[{code:"data.rich-text",declaration:{policyVersion:"rich-text-html/1"}}]:[],...d?[{code:"data.managed-files",declaration:{operations:n.filter(u=>u.platformAccess?.managedFiles||u.platformAccess?.managedFileCopies).map(u=>({code:u.code,...u.platformAccess?.managedFiles?{managedFiles:u.platformAccess.managedFiles}:{},...u.platformAccess?.managedFileCopies?{managedFileCopies:u.platformAccess.managedFileCopies}:{}})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.managedFileCopies).map(u=>({code:u.code,managedFileCopies:u.platformAccess.managedFileCopies}))}}]:[],...e.events.subscriptions.some(u=>u.execution?.kind==="worker-effect")?[{code:"events.worker-effects",declaration:e.events.subscriptions.filter(u=>u.execution?.kind==="worker-effect")}]:[],...e.events.subscriptions.some(u=>u.execution?.kind==="native-data")?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(u=>u.execution?.kind==="native-data")}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(u=>Ad(u.resourceCode,e.events.subscriptions.filter(E=>E.eventTypes.includes(u.eventType)),e.data.resources.find(E=>E.code===u.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...a?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...jr(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(u=>jr([u]))}]:[],...Wr(e.data.resources,e.workflows?.definitions||[])?[{code:"data.extended-field-capacity",declaration:{resources:e.data.resources.filter(u=>u.schema.fields.length>100),workflows:(e.workflows?.definitions||[]).filter(u=>Wr([],[u]))}}]:[],...xr(e.data.resources)?[{code:"data.aggregate-owned-subtable-capacity",declaration:e.data.resources.filter(u=>xr([u]))}]:[],...e.data.resources.some(u=>u.schema.fields.some(E=>E.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(u=>u.schema.fields.some(E=>E.userCandidates!==void 0))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.selectedInputPath!==void 0))?[{code:"workflow.role-input-selection",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.selectedInputPath!==void 0))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.roleCodes!==void 0))?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.roleCodes!==void 0))}]:[],...e.backend.operations.some(u=>u.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(u=>u.platformAccess?.ownedSubject)}]:[],...$r(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(u=>$r([u]))}]:[],...qr(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(u=>qr([u]))}]:[],...Kr(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(u=>Kr([u]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(u=>u.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(u=>u.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(u=>u.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(u=>u.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers!==void 0)||n.some(u=>u.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(u=>u.definition.commandHandlers!==void 0),operations:n.filter(u=>u.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.approve?.transitionPolicy==="workflow")?[{code:"workflow.approval-business-command",declaration:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.approve?.transitionPolicy==="workflow")}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.resubmit)||n.some(u=>u.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.resubmit),operations:n.filter(u=>u.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(u=>u.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(u=>u.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)?[{code:"workflow.correction-derived-subject-facts",declaration:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(u=>u.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(u=>vd(u.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(u=>vd(u.definition,e.data.resources))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.kind==="correction"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>Object.values(E.operationPolicy||{}).some(w=>w.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>Object.values(E.operationPolicy||{}).some(w=>w.reasonRequired===!1)))}]:[],...O.length?[{code:"workflow.named-input-sources",declaration:O}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.administration!==void 0||E.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.administration!==void 0||E.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.kind==="approval"&&E.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.kind==="approval"&&E.emptyPolicy!==void 0))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).some(E=>E.provider==="conditional"))?[{code:"workflow.conditional-assignment",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).some(E=>E.provider==="conditional"))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.provider==="supervisor_chain"))?[{code:"workflow.supervisor-chain",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.provider==="supervisor_chain"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.reminders))?[{code:"workflow.reminders",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.reminders))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>ie(E)))?[{code:"workflow.platform-notify",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>ie(E)))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.returnPolicy!==void 0))?[{code:"workflow.return-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.returnPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.kind==="handle"))?[{code:"workflow.handling-nodes",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.kind==="handle"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.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(E=>E.definition.taskPages!==void 0)})):[],...f.length?[{code:"workflow.task-managed-files",declaration:f}]:[],...m.length?[{code:"workflow.task-owned-files",declaration:m}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.taskPages||{}).some(E=>E.fields.some(w=>w.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.taskPages||{}).some(E=>E.fields.some(w=>w.subtable)))}]:[],...e.workflows.definitions.some(u=>u.definition.authoring?.businessSteps?.length||Object.values(u.definition.nodes).some(E=>E.kind==="action"&&!ie(E)))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(u=>u.definition.authoring?.businessSteps?.length||Object.values(u.definition.nodes).some(E=>E.kind==="action"&&!ie(E)))}]:[],...e.workflows.definitions.some(u=>[...Object.values(u.definition.nodes),...u.definition.authoring?.businessSteps||[]].some(E=>E.handler?.dataTransaction))?[{code:"workflow.step-data-transaction",declaration:e.workflows.definitions.filter(u=>[...Object.values(u.definition.nodes),...u.definition.authoring?.businessSteps||[]].some(E=>E.handler?.dataTransaction))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.routing!==void 0))}]:[],...I?[{code:"business-process.durable-command",declaration:{operations:n.filter(u=>u.platformAccess?.workflow).map(u=>({code:u.code,workflow:u.platformAccess.workflow})),definitions:A,activations:e.workflows.activations.filter(u=>A.some(E=>E.definition.code===u.workflowCode))}}]:[],...n.some(u=>u.platformAccess?.dataMutations)||e.events.subscriptions.some(u=>u.platformAccess?.dataMutations)?[{code:"data.service-mutations",declaration:{operations:n.filter(u=>u.platformAccess?.dataMutations).map(u=>({code:u.code,grants:u.platformAccess.dataMutations})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.dataMutations).map(u=>({code:u.code,grants:u.platformAccess.dataMutations}))}}]:[],...e.events.subscriptions.some(u=>u.platformAccess?.notification?.mode==="business-task")?[{code:"notification-hub-v2.event-tasks",declaration:e.events.subscriptions.filter(u=>u.platformAccess?.notification?.mode==="business-task")}]:[],...c?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(u=>u.definition.rejectionNotification!==void 0)}:{},operations:n.filter(u=>u.platformAccess?.notification).map(u=>({code:u.code,notification:u.platformAccess.notification})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.notification).map(u=>({code:u.code,notification:u.platformAccess.notification}))}}]:[],...e.frontend.authentication?[{code:"authentication.application-login-surface",declaration:e.frontend.authentication}]:[],...e.frontend.publicAccess?[{code:"public-access.anonymous-owner-records",declaration:e.frontend.publicAccess}]:[]].map(({code:u,declaration:E})=>({code:u,contractVersion:u==="data.unique-keys"?o.some(w=>qa(w.schema.fields,w.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":Td[u],usageDigest:`sha256:${ee(E)}`})).sort((u,E)=>u.code===E.code?0:u.code<E.code?-1:1)}function ef(e){let t=new Map,o=new Set(e.resources.map(i=>String(i.code)));for(let[i,s]of D(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let a=`/capturePlan/capturePolicies/${i}`,d=N(s,a);R(d,["resourceCode","mode"],a);let c=Q(d.resourceCode,`${a}/resourceCode`);o.has(c)||_("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",a,{resourceCode:c}),t.has(c)&&_("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",a,{resourceCode:c}),d.mode!=="all"&&d.mode!=="subscribed"&&_("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${a}/mode`),t.set(c,d.mode)}let n=new Map(e.dataPolicies.map((i,s)=>{let a=N(i,`/capturePlan/dataPolicies/${s}`);return[String(a.code),a]})),r=e.subscriptions.map((i,s)=>N(i,`/capturePlan/subscriptions/${s}`));return e.resources.map((i,s)=>{let a=`/capturePlan/resources/${s}`,d=N(i,a),c=Q(d.code,`${a}/code`),l=d.schema?N(d.schema,`${a}/schema`):d,f=new Set(D(l.fields||[],`${a}/schema/fields`,500).map((E,w)=>J(N(E,`${a}/schema/fields/${w}`).code,`${a}/schema/fields/${w}/code`))),p=d.dataPolicyCode?F(d.dataPolicyCode,`${a}/dataPolicyCode`):null,m=p?n.get(p):void 0;p&&!m&&_("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",a,{resourceCode:c,dataPolicyCode:p});let A=new Set;for(let E of m?.rules||[])A.add(E.parentRead?$o(e.resources,c,E.parentRead,`${a}/parentRead`).foreignKey:String(E.field));if(m?.readExpression)for(let E of an(m.readExpression,`${a}/readExpression`))A.add(E.rule.parentRead?$o(e.resources,c,E.rule.parentRead,`${a}/parentRead`).foreignKey:String(E.rule.field));let I=new Set,O=new Set,b=new Set;for(let[E,w]of r.entries()){let S=D(w.eventTypes,`/capturePlan/subscriptions/${E}/eventTypes`,20).map(String);if(!S.some(P=>P.startsWith("openxiangda.data.")))continue;let T=N(w.filter||{},`/capturePlan/subscriptions/${E}/filter`),C=Array.isArray(T.resourceCodes)?T.resourceCodes.map(String):[];if(C.length&&!C.includes(c))continue;for(let P of S)zi.includes(P)&&b.add(P);for(let P of tf(T,`/capturePlan/subscriptions/${E}/filter`))I.add(P);let v=N(w.payload||{},`/capturePlan/subscriptions/${E}/payload`);for(let P of D(v.fields||[],`/capturePlan/subscriptions/${E}/payload/fields`,32))O.add(J(P,`/capturePlan/subscriptions/${E}/payload/fields`))}let g=new Set([...I,...O]),y=new Set([...g,...A]);y.size>Ld&&_("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",a,{resourceCode:c,maximum:Ld});for(let E of y)!f.has(E)&&!(A.has(E)&&Hd.has(E))&&_("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",a,{resourceCode:c,field:E});let h=N(d.fieldPolicies||{},`${a}/fieldPolicies`);for(let E of g)h[E]?.mask==="omit"&&_("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",a,{resourceCode:c,field:E});let u={resourceCode:c,...t.get(c)==="subscribed"?{capturedEventTypes:[...b].sort()}:{},filterFields:[...I].sort(),projectionFields:[...O].sort(),authorizationFields:[...A].sort(),captureFields:[...y].sort()};return{...u,digest:ee(u)}}).sort((i,s)=>i.resourceCode.localeCompare(s.resourceCode))}function tf(e,t){let o=new Set;for(let[s,a]of D(e.changes||[],`${t}/changes`,16).entries()){let d=N(a,`${t}/changes/${s}`);o.add(J(d.field,`${t}/changes/${s}/field`))}let n=N(e.changedFields||{},`${t}/changedFields`);for(let s of["anyOf","allOf","noneOf"])for(let[a,d]of D(n[s]||[],`${t}/changedFields/${s}`,32).entries())o.add(J(d,`${t}/changedFields/${s}/${a}`));let r=0,i=(s,a,d)=>{d>3&&_("NATIVE_EVENT_FILTER_DEPTH_LIMIT",a);let c=N(s,a);if(c.change){let f=N(c.change,`${a}/change`);o.add(J(f.field,`${a}/change/field`)),r+=1;return}if(c.not){i(c.not,`${a}/not`,d+1);return}let l=c.all?"all":c.any?"any":null;l||_("NATIVE_EVENT_FILTER_CONDITION_INVALID",a);for(let[f,p]of D(c[l],`${a}/${l}`,16).entries())i(p,`${a}/${l}/${f}`,d+1)};return e.where&&i(e.where,`${t}/where`,1),r+=Array.isArray(e.changes)?e.changes.length:0,r>16&&_("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...o].sort()}function nf(e,t){R(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config",["agents"]),Sa(t,e.agents,e.data?.resources||[],{authz:e.authz}),x(e.schemaVersion,Du,"/config/schemaVersion"),x(e.compilerContractVersion,Bn,"/config/compilerContractVersion"),x(e.appCode,t,"/config/appCode"),D(e.perspectives,"/config/perspectives",100);let o=N(e.authz,"/config/authz");try{Oa(e)}catch(f){if(!(f instanceof Cn))throw f;_(f.code,f.pointer)}R(o,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode","directoryRoleSources"]),D(o.capabilities,"/config/authz/capabilities",q.capabilities),D(o.roles,"/config/authz/roles",q.roles),D(o.scopeDimensions,"/config/authz/scopeDimensions",100),D(o.scopeSources,"/config/authz/scopeSources",100),D(o.roleMembershipSources,"/config/authz/roleMembershipSources",100),D(o.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),D(o.dataPolicies,"/config/authz/dataPolicies",q.dataPolicies),D(o.authorizationTransitions,"/config/authz/authorizationTransitions",100);let n=N(e.backend,"/config/backend");R(n,["secrets","operations"],"/config/backend"),D(n.secrets,"/config/backend/secrets",100),D(n.operations,"/config/backend/operations",500),xf(n.secrets);let r=N(e.data,"/config/data");R(r,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),D(r.resources,"/config/data/resources",q.resources),r.subjectReadSurfaces!==void 0&&D(r.subjectReadSurfaces,"/config/data/subjectReadSurfaces",q.subjectReadSurfaces),r.resourceDetailRoutes!==void 0&&D(r.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let i=N(e.events,"/config/events");R(i,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),D(i.schemas,"/config/events/schemas",100),D(i.subscriptions,"/config/events/subscriptions",100),D(i.timers,"/config/events/timers",100),D(i.dateTriggers,"/config/events/dateTriggers",100);let s=N(e.workflows,"/config/workflows");R(s,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),D(s.definitions,"/config/workflows/definitions",q.workflows),D(s.bindings,"/config/workflows/bindings",q.workflows),D(s.activations,"/config/workflows/activations",q.workflows),D(s.providers,"/config/workflows/providers",100),D(s.editableParameters,"/config/workflows/editableParameters",100);let a=N(e.frontend,"/config/frontend");R(a,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),D(a.routes,"/config/frontend/routes",q.routes);let d=N(a.user,"/config/frontend/user");R(d,["applicationTodoCenter"],"/config/frontend/user"),_n(d.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Xi(a.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(a,"authentication")&&Xd(a.authentication,a.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(a,"publicAccess")&&yf(a.publicAccess,e,"/config/frontend/publicAccess");let c=N(a.admin,"/config/frontend/admin");R(c,["navigation"],"/config/frontend/admin",["access"]),c.access!==void 0&&nr(c.access,"/config/frontend/admin/access",e.appCode),Nf(c.navigation,"/config/frontend/admin/navigation");let l=N(e.runtime,"/config/runtime");R(l,["protocolCapabilities","health"],"/config/runtime"),V(l.protocolCapabilities,"/config/runtime/protocolCapabilities",100),R(N(l.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),x(l.health.livePath,"/__platform/health","/config/runtime/health/livePath"),x(l.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),x(l.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function of(e,t,o){R(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces","concurrency"]),x(e.schemaVersion,Gd,"/contracts/schemaVersion"),x(e.compilerContractVersion,Bn,"/contracts/compilerContractVersion"),k(e.generatorVersion,"/contracts/generatorVersion",128),x(e.appCode,t,"/contracts/appCode"),x(e.configDigest,o,"/contracts/configDigest"),D(e.perspectives,"/contracts/perspectives",q.perspectives),D(e.resources,"/contracts/resources",q.resources),e.subjectReadSurfaces!==void 0&&D(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",q.subjectReadSurfaces),D(e.capabilities,"/contracts/capabilities",q.capabilities),D(e.operations,"/contracts/operations",q.operations),D(e.eventConsumers,"/contracts/eventConsumers",q.eventConsumers),D(e.eventProducers,"/contracts/eventProducers",q.eventProducers),D(e.eventSchemas,"/contracts/eventSchemas",q.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),V(e.eventTypes,"/contracts/eventTypes",q.eventTypes),D(e.workflows,"/contracts/workflows",q.workflows),D(e.routes,"/contracts/routes",q.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Af(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Of(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&nr(e.adminAccess,"/contracts/adminAccess",t),Df(e.routeManifest,"/contracts/routeManifest",t),Tf(e.adminPages,"/contracts/adminPages"),Cf(e.adminNavigation,"/contracts/adminNavigation")}function rf(e,t,o){let n=df(e);$f(e,n),Vf(e),Ff(e),jf(e);let r=e.events.schemas.map((g,y)=>{let h=`/config/events/schemas/${y}`,u=N(g,h),E=k(u.eventType,`${h}/eventType`,255);return E.startsWith("openxiangda.")&&_("NATIVE_EVENT_SCHEMA_RESERVED",`${h}/eventType`,{eventType:E}),x(u.schemaDigest,ee(N(u.jsonSchema,`${h}/jsonSchema`)),`${h}/schemaDigest`),u}),i=new Set([...zi,...Mn,...r.map(g=>String(g.eventType))]),s=new Map(e.data.resources.map(g=>[String(g.code),new Map(g.schema.fields.map(y=>[String(y.code),String(y.type)]))])),a=ue(e.events.subscriptions.map((g,y)=>{let h=`/config/events/subscriptions/${y}`,u=N(g,h),E=V(u.eventTypes,`${h}/eventTypes`,20);E.forEach((C,v)=>{i.has(C)||_("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${h}/eventTypes/${v}`,{eventType:C})});let w=Xa(u,e.data.resources,h,{emitEventTypes:r.map(C=>String(C.eventType)),workflowResources:e.workflows.definitions.map(C=>String(C.definition?.subject?.resourceCode||""))}),S=af(u.delivery,E,`${h}/delivery`),T=sf(u.platformAccess,`${h}/platformAccess`,s,e,u);return{code:F(u.code,`${h}/code`),endpointPath:Je(u.endpointPath,`${h}/endpointPath`),eventTypes:E,filter:N(u.filter,`${h}/filter`),payload:w?.payload||N(u.payload,`${h}/payload`),...w?{execution:w.execution}:{},...T?{platformAccess:T}:{},delivery:S}}),g=>g.code),d=new Map(r.map(g=>[String(g.eventType),String(g.dataSchemaVersion)])),c=ue([...e.data.resources.flatMap(g=>zi.map(y=>({code:`data:${g.code}:${y}`,source:"data",eventType:y,dataSchemaVersion:"2.0.0",resourceCode:g.code}))),...r.map(g=>({code:`app:${g.eventType}`,source:"app",eventType:g.eventType,dataSchemaVersion:g.dataSchemaVersion})),...e.events.timers.map(g=>({code:g.code,source:"timer",eventType:g.eventType,dataSchemaVersion:d.get(String(g.eventType))||"2.0.0"})),...e.events.dateTriggers.map(g=>({code:g.code,source:"date",eventType:g.eventType,dataSchemaVersion:d.get(String(g.eventType))||"2.0.0",resourceCode:g.resourceCode,field:g.field})),...e.workflows.activations.length?Bi(e.workflows.definitions).map(g=>({code:`workflow:${g}`,source:"workflow",eventType:g,dataSchemaVersion:"2.0.0"})):[]],g=>`${g.source}:${g.code}:${g.eventType}`),l=K([...a.flatMap(g=>g.eventTypes),...c.map(g=>String(g.eventType))]);Rf(e);let f=ec(e),p;try{p=la(e.data.concurrency,e.data.resources,n)}catch(g){throw g instanceof wn&&_(g.code,g.pointer,{reason:g.reason}),g}p?.commands.some(g=>g.mode==="durable")&&e.backend?.enabled===!1&&_("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let m=lf(e,n),A=Yd(e),I=e.workflows.definitions.map(g=>g.definition),O=Nr(I),b=bs(I,a,!0);b.length&&_(b[0],"/config/events/subscriptions");try{fa(e.data.resources,A)}catch(g){throw g instanceof rn&&_(g.code,g.pointer,{reason:g.reason}),g}return{schemaVersion:Gd,compilerContractVersion:Bn,generatorVersion:o,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:cf(e),...m.length?{subjectReadSurfaces:m}:{},...p?{concurrency:p}:{},capabilities:ue(n,g=>g.code),operations:A,eventConsumers:a,eventProducers:c,eventSchemas:r,eventHandlerManifest:{schemaVersion:Xu,appCode:e.appCode,handlers:a.filter(g=>g.execution?.kind!=="native-data").map(g=>({code:g.code,endpointPath:g.endpointPath,eventTypes:g.eventTypes,dataSchemaVersions:K(g.eventTypes.map(y=>y.startsWith("openxiangda.")?"2.0.0":d.get(y)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...O[g.code]?{workflowStep:O[g.code]}:{}}))},eventTypes:l,workflows:oc(e),routes:tr(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:Ef(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:bf(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:vf(e),adminPages:f,adminNavigation:hf(e)}}function sf(e,t,o,n,r){if(e===void 0)return;let i=N(e,t);R(i,["notification","managedFileCopies","decimalReservation","dataMutations"],t,!0);let s={};if(i.dataMutations!==void 0)try{s.dataMutations=Ei(i.dataMutations,o)}catch{_("NATIVE_EVENT_DATA_MUTATIONS_INVALID",`${t}/dataMutations`)}if(i.decimalReservation!==void 0)try{s.decimalReservation=Ga(i.decimalReservation,Ja(n,r))}catch{_("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(i.notification!==void 0){let a=N(i.notification,`${t}/notification`);if(a.mode==="business-task"){R(a,["mode","taskCodes"],`${t}/notification`);let d=D(a.taskCodes,`${t}/notification/taskCodes`,16).map((c,l)=>F(c,`${t}/notification/taskCodes/${l}`));(!d.length||new Set(d).size!==d.length||d.some(c=>!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(c)))&&_("NATIVE_EVENT_TASK_CODES_INVALID",`${t}/notification/taskCodes`),s.notification={mode:"business-task",taskCodes:d}}else R(a,["mode"],`${t}/notification`),x(a.mode,"business-standard",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(i.managedFileCopies!==void 0){let a=D(i.managedFileCopies,`${t}/managedFileCopies`,16);a.length||_("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let d=new Set;s.managedFileCopies=ue(a.map((c,l)=>{let f=`${t}/managedFileCopies/${l}`,p=N(c,f);R(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],f),x(p.mode,"copy",`${f}/mode`);let m=Q(p.sourceResourceCode,`${f}/sourceResourceCode`),A=Q(p.targetResourceCode,`${f}/targetResourceCode`),I=o.get(m),O=o.get(A);(!I||!O)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",f);let b=V(p.sourceFieldCodes,`${f}/sourceFieldCodes`,16),g=V(p.targetFieldCodes,`${f}/targetFieldCodes`,16);(!b.length||b.length!==g.length)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",f),b.forEach((h,u)=>{let E=I.get(h),w=O.get(g[u]);(!["file","image","text.rich"].includes(String(E))||E!==w)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${f}/sourceFieldCodes/${u}`)});let y=`${m}:${b.join(",")}=>${A}:${g.join(",")}`;return d.has(y)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",f),d.add(y),{mode:"copy",sourceResourceCode:m,sourceFieldCodes:K(b),targetResourceCode:A,targetFieldCodes:K(g)}}),c=>`${c.sourceResourceCode}:${c.sourceFieldCodes.join(",")}=>${c.targetResourceCode}:${c.targetFieldCodes.join(",")}`)}return Object.keys(s).length||_("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),s}function af(e,t,o){let n=N(e,o);R(n,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],o),Ae(n.timeoutMs,`${o}/timeoutMs`,1e3,3e4),Ae(n.maxAttempts,`${o}/maxAttempts`,1,12);let r=Ae(n.initialBackoffMs,`${o}/initialBackoffMs`,1e3,3e5);Ae(n.maxBackoffMs,`${o}/maxBackoffMs`,r,18e5),Ae(n.concurrency,`${o}/concurrency`,1,50);let i=k(n.ordering,`${o}/ordering`,32);return["none","record","workflow-instance"].includes(i)||_("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${o}/ordering`),i==="workflow-instance"&&t.some(s=>!Zu.has(s))&&_("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${o}/ordering`),n}function df(e){let t=new Map;for(let i of sc(e.appCode))t.set(i.code,i);for(let[i,s]of e.authz.capabilities.entries()){let a=`/config/authz/capabilities/${i}`,d=N(s,a);R(d,["code","kind","name","description"],a,!0);let c=Pe(d.code,`${a}/code`,e.appCode);t.has(c)&&_("NATIVE_CAPABILITY_DUPLICATE",`${a}/code`),["backend","ui"].includes(d.kind)||_("NATIVE_CAPABILITY_KIND_INVALID",`${a}/kind`);let l={code:c,kind:d.kind,name:k(d.name,`${a}/name`,255),source:"explicit",...d.description===void 0?{}:{description:Qi(d.description,`${a}/description`,2e3)}};t.set(c,l)}let o=e.data.resources.map((i,s)=>({pointer:`/config/data/resources/${s}`,resource:Ut(i,`/config/data/resources/${s}`,e.appCode)}));for(let{pointer:i,resource:s}of o){let a={read:`\u8BFB\u53D6${s.name}`,create:`\u65B0\u5EFA${s.name}`,update:`\u66F4\u65B0${s.name}`,delete:`\u5220\u9664${s.name}`};for(let d of["read","create","update","delete"]){let c=Pe(s.capabilities[d],`${i}/capabilities/${d}`,e.appCode);t.has(c)&&_("NATIVE_CAPABILITY_DUPLICATE",`${i}/capabilities/${d}`),t.set(c,{code:c,kind:"data",name:a[d],source:"data"})}}let n=new Set(t.keys()),r=new Map;for(let{pointer:i,resource:s}of o)for(let[a,d]of Object.entries(s.fieldPolicies)){if(Vt(a))continue;let c=N(d,`${i}/fieldPolicies/${a}`);for(let l of["read","create","update"])if(Array.isArray(c[l]))for(let f of V(c[l],`${i}/fieldPolicies/${a}/${l}`,2e3)){if(Pe(f,`${i}/fieldPolicies/${a}/${l}`,e.appCode),n.has(f))continue;let p=r.get(f);p&&p!==s.code&&_("NATIVE_CAPABILITY_DUPLICATE",`${i}/fieldPolicies/${a}/${l}`),r.set(f,s.code),!t.has(f)&&t.set(f,{code:f,kind:"data",name:`${s.name}.${a}.${l}`,source:"data"})}}return[...t.values()]}function cf(e){let t=uf(e);return ue(e.data.resources.map((o,n)=>{let r=Ut(o,`/config/data/resources/${n}`,e.appCode),i=t.get(r.code);return{code:r.code,schemaDigest:ee(r.schema),fields:ue(r.schema.fields.map(s=>({code:s.code,type:s.type})),s=>s.code),...i?{detailRouteCode:i}:{}}}),o=>o.code)}function lf(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let o=D(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",q.subjectReadSurfaces),n=new Set(t.map(s=>String(s.code))),r=new Map(e.data.resources.map((s,a)=>{let d=`/config/data/resources/${a}`,c=Ut(s,d,e.appCode);return[String(c.code),{resource:c,fields:new Map(D(N(c.schema,`${d}/schema`).fields,`${d}/schema/fields`,500).map(l=>{let f=N(l,`${d}/schema/fields`);return[String(f.code),f]}))}]})),i=new Set;return ue(o.map((s,a)=>{let d=`/config/data/subjectReadSurfaces/${a}`,c=N(s,d);R(c,["code","name","capability","subject","relations"],d);let l=F(c.code,`${d}/code`);i.has(l)&&_("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${d}/code`),i.add(l);let f=Pe(c.capability,`${d}/capability`,e.appCode);n.has(f)||_("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${d}/capability`);let p=N(c.subject,`${d}/subject`);R(p,["resourceCode","fields"],`${d}/subject`);let m=Q(p.resourceCode,`${d}/subject/resourceCode`),A=r.get(m);A||_("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${d}/subject/resourceCode`);let I=V(p.fields,`${d}/subject/fields`,100).map((h,u)=>J(h,`${d}/subject/fields/${u}`));I.length||_("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${d}/subject/fields`);for(let[h,u]of I.entries()){let E=A.fields.get(u);(!E||E.type==="subtable")&&_("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${d}/subject/fields/${h}`)}let O=D(c.relations,`${d}/relations`,8);O.length||_("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${d}/relations`);let b=new Set,g=0,y=ue(O.map((h,u)=>{let E=`${d}/relations/${u}`,w=N(h,E);R(w,["code","resourceCode","foreignKeyField","fields","limit"],E,["order"]);let S=F(w.code,`${E}/code`);b.has(S)&&_("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${E}/code`),b.add(S);let T=Q(w.resourceCode,`${E}/resourceCode`),C=r.get(T);C||_("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${E}/resourceCode`);let v=J(w.foreignKeyField,`${E}/foreignKeyField`),P=C.fields.get(v),H=N(P?.source||{},`${E}/foreignKeyField/source`);(!P||!["uuid","resource-ref.single"].includes(String(P.type))||P.type==="resource-ref.single"&&(H.kind!=="resource"||H.resourceCode!==m))&&_("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${E}/foreignKeyField`);let ne=V(w.fields,`${E}/fields`,100).map((Ee,Ie)=>J(Ee,`${E}/fields/${Ie}`));ne.length||_("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${E}/fields`);for(let[Ee,Ie]of ne.entries()){let fe=C.fields.get(Ie);(!fe||fe.type==="subtable")&&_("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${E}/fields/${Ee}`)}let Z=D(w.order||[],`${E}/order`,10).map((Ee,Ie)=>{let fe=`${E}/order/${Ie}`,ye=N(Ee,fe);R(ye,["field","direction"],fe);let $=J(ye.field,`${fe}/field`),Y=C.fields.get($);return(!Hd.has($)&&!Y||Y?.type==="subtable"||Y&&!Nn(Y.type))&&_("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${fe}/field`),["asc","desc"].includes(String(ye.direction))||_("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${fe}/direction`),{field:$,direction:ye.direction}}),Se=Ae(w.limit,`${E}/limit`,1,100);return g+=Se,{code:S,resourceCode:T,foreignKeyField:v,fields:K(ne),...Z.length?{order:Z}:{},limit:Se}}),h=>h.code);return g>400&&_("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${d}/relations`),{code:l,name:k(c.name,`${d}/name`,255),capability:f,subject:{resourceCode:m,fields:K(I)},relations:y}}),s=>s.code)}function uf(e){let t=e.data.resourceDetailRoutes===void 0?[]:D(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),o=new Map(e.data.resources.map((i,s)=>{let a=`/config/data/resources/${s}`,d=Ut(i,a,e.appCode);return[d.code,d]})),n=new Map(tr(e).map(i=>[String(i.code),i])),r=new Map;for(let[i,s]of t.entries()){let a=`/config/data/resourceDetailRoutes/${i}`,d=N(s,a);R(d,["resourceCode","desktop","mobile"],a);let c=Q(d.resourceCode,`${a}/resourceCode`);r.has(c)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${a}/resourceCode`);let l=o.get(c);l||_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${a}/resourceCode`);let f=F(d.desktop,`${a}/desktop`),p=F(d.mobile,`${a}/mobile`);f===p&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",a);let m=String(l.capabilities.read);for(let[A,I]of[["desktop",f],["mobile",p]]){let O=`${a}/${A}`,b=n.get(I);b||_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",O),b.surface!=="user"&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",O);let g=Je(b.path,`${O}/path`),y=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],h=A==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||y.length!==1||h)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",O);let u=Array.isArray(b.access?.allOf)?b.access.allOf:[];b.capability!==m&&!u.includes(m)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",O)}r.set(c,{desktop:f,mobile:p})}return r}function Yd(e){let t=new Map(e.data.resources.map((s,a)=>{let d=`/config/data/resources/${a}`,c=Ut(s,d,e.appCode);return[c.code,new Map(c.schema.fields.map(l=>[String(l.code),l]))]})),o=new Map(e.data.resources.map((s,a)=>{let d=`/config/data/resources/${a}`,c=Ut(s,d,e.appCode);return[c.code,new Map(c.schema.fields.map(l=>[String(l.code),String(l.type)]))]})),n=new Set(o.keys()),r=new Set(e.workflows.activations.map((s,a)=>or(N(s,`/config/workflows/activations/${a}`).workflowCode,`/config/workflows/activations/${a}/workflowCode`))),i=new Map;return ue(e.backend.operations.map((s,a)=>{let d=`/config/backend/operations/${a}`,c=N(s,d);R(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],d,!0);let l=k(c.method,`${d}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(l)||_("NATIVE_OPERATION_METHOD_INVALID",`${d}/method`);let f=F(c.code,`${d}/code`);gf(c.ai,d,f,l,n);let p=mf(c.platformAccess,`${d}/platformAccess`,o,t,r,new Set(e.authz.roles.map(A=>String(A.code))));if(p?.workflowStage){let A=p.workflowStage,I=e.workflows.definitions.find(O=>O.definition.code===A.workflowCode);(!I||I.definition.subject?.resourceCode!==A.resourceCode||A.runningNodeIds.some(O=>!I.definition.nodes[O]))&&_("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${d}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let A=e.data.resources.find(I=>I.code===p.recordEdit.resourceCode);A?.surface?.mutationOwner!=="action"&&_("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${d}/platformAccess/recordEdit`);for(let I of p.recordEdit.fieldCodes)(!A.fieldPolicies?.[I]?.update?.length||A.surface?.fields?.[I]?.system===!0)&&_("NATIVE_RECORD_EDIT_FIELD_INVALID",`${d}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let A=p.decimalReservation,I=String(A.resourceCode),O=JSON.stringify([A.amountFieldCode,A.currencyFieldCode,A.relationFieldCode,A.parentFieldCode,A.rootFieldCode,A.statusFieldCode,A.parentRelationValue,A.childRelationValue]),b=i.get(I);b&&b!==O&&_("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${d}/platformAccess/decimalReservation`),i.set(I,O)}let m=ff(c.browser,`${d}/browser`,l,c.requestSchema,c.responseSchema,o,t,e.data.subjectReadSurfaces||[]);return{code:f,method:l,path:Je(c.path,`${d}/path`),requiredCapability:Pe(c.capability,`${d}/capability`,e.appCode),requestSchemaDigest:ee(N(c.requestSchema,`${d}/requestSchema`)),responseSchemaDigest:ee(N(c.responseSchema,`${d}/responseSchema`)),...c.description===void 0?{}:{description:Qi(c.description,`${d}/description`,2e3)},...p?{platformAccess:p}:{},...m?{browser:m}:{}}}),s=>s.code)}function ff(e,t,o,n,r,i,s,a){if(e===void 0)return null;let d=N(e,t);R(d,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),x(d.exposure,"authenticated",`${t}/exposure`);let c=k(d.behavior,`${t}/behavior`,32);["read","controlled"].includes(c)||_("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let l=k(d.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(l)||c==="controlled"&&l!=="required"||c==="read"&&l!=="none")&&_("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let f=N(d.subject,`${t}/subject`);R(f,["resourceCode","inputField"],`${t}/subject`);let p=Q(f.resourceCode,`${t}/subject/resourceCode`);i.has(p)||_("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let m=J(f.inputField,`${t}/subject/inputField`),A=N(n,`${t}/requestSchema`),I=N(r,`${t}/responseSchema`);(A.type!=="object"||A.additionalProperties!==!1||I.type!=="object"||I.additionalProperties!==!1)&&_("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let O=N(A.properties,`${t}/requestSchema/properties`),b=new Set(A.required===void 0?[]:V(A.required,`${t}/requestSchema/required`,200));(!(m in O)||!b.has(m))&&_("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=N(O[m],`${t}/requestSchema/properties/${m}`);(g.type!=="string"||g.format!=="uuid")&&_("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let y=new Map((Array.isArray(a)?a:[]).map((S,T)=>{let C=N(S,`/config/data/subjectReadSurfaces/${T}`);return[String(C.code),String(N(C.subject,`/config/data/subjectReadSurfaces/${T}/subject`).resourceCode)]})),h=d.refreshTargets===void 0?[]:D(d.refreshTargets,`${t}/refreshTargets`,16),u=new Set,E=ue(h.map((S,T)=>{let C=`${t}/refreshTargets/${T}`,v=N(S,C);R(v,["kind","code"],C),x(v.kind,"subject-surface",`${C}/kind`);let P=F(v.code,`${C}/code`);return(u.has(P)||!y.has(P)||y.get(P)!==p)&&_("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${C}/code`),u.add(P),{kind:"subject-surface",code:P}}),S=>`${S.kind}:${S.code}`),w=pf(d.fileIntent,`${t}/fileIntent`,o,c,l,p,O,b,s);return{exposure:"authenticated",behavior:c,idempotency:l,subject:{resourceCode:p,inputField:m},...E.length?{refreshTargets:E}:{},...w?{fileIntent:w}:{}}}function pf(e,t,o,n,r,i,s,a,d){if(e===void 0)return null;let c=N(e,t);R(c,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(o!=="GET"||n!=="read"||r!=="none")&&_("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let l=Q(c.recordResourceCode,`${t}/recordResourceCode`),f=d.get(l);f||_("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=J(c.recordIdInputField,`${t}/recordIdInputField`),m=N(s[p],`${t}/recordIdInputField`);(!a.has(p)||m.type!=="string"||m.format!=="uuid")&&_("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let A=J(c.relationField,`${t}/relationField`),I=f.get(A);(!I||!["uuid","resource-ref.single"].includes(String(I.type))||String(I.type)==="resource-ref.single"&&(String(N(I.source,`${t}/relationField`).kind||"")!=="resource"||String(N(I.source,`${t}/relationField`).resourceCode||"")!==i))&&_("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[u,E]of O){let w=J(c[u],`${t}/${u}`);E.includes(String(f.get(w)?.type))||_("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${u}`),b[u]=w}let g=ue(V(c.purposes,`${t}/purposes`,2),u=>u);(!g.length||g.some(u=>!["preview","download"].includes(u)))&&_("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let y=Number(c.maxTtlSeconds);(!Number.isSafeInteger(y)||y<1||y>300)&&_("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let h=Number(c.maxBytes);return(!Number.isSafeInteger(h)||h<1||h>104857600)&&_("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:l,recordIdInputField:p,relationField:A,fileNameField:b.fileNameField,contentTypeField:b.contentTypeField,sizeField:b.sizeField,purposes:g,maxTtlSeconds:y,maxBytes:h}}function mf(e,t,o,n,r,i){if(e===void 0)return null;let s=N(e,t);R(s,["directory","directoryClasses","transactionTime","selectedDepartments","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage","dataMutations"],t,!0),Object.keys(s).length===0&&_("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let a={};if(s.dataMutations!==void 0)try{a.dataMutations=Ei(s.dataMutations,n)}catch{_("NATIVE_OPERATION_DATA_MUTATIONS_INVALID",`${t}/dataMutations`)}if(s.dataCommands!==void 0){let d=N(s.dataCommands,`${t}/dataCommands`);R(d,["mode"],`${t}/dataCommands`),x(d.mode,"recoverable-native",`${t}/dataCommands/mode`),a.dataCommands={mode:"recoverable-native"}}if(s.workflowStage!==void 0){try{ja(s.workflowStage)}catch{_("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let d=s.workflowStage;(!a.dataCommands||s.decimalReservation!==void 0||!o.has(d.resourceCode)||!r.has(d.workflowCode)||!s.workflow?.codes?.includes(d.workflowCode))&&_("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),a.workflowStage={...d,runningNodeIds:K([...d.runningNodeIds]),allowedStatuses:K([...d.allowedStatuses])}}if(s.recordEdit!==void 0){let d=`${t}/recordEdit`,c=N(s.recordEdit,d);R(c,["resourceCode","fieldCodes"],d);let l=Q(c.resourceCode,`${d}/resourceCode`),f=n.get(l),p=V(c.fieldCodes,`${d}/fieldCodes`,200);(!f||!p.length||!a.dataCommands)&&_("NATIVE_RECORD_EDIT_DECLARATION_INVALID",d);for(let m of p){let A=f.get(m);(!A||A.type==="serial-number"||A.type==="subtable")&&_("NATIVE_RECORD_EDIT_FIELD_INVALID",`${d}/fieldCodes`)}a.recordEdit={resourceCode:l,fieldCodes:K(p)}}if(s.roleAssertions!==void 0){let d=N(s.roleAssertions,`${t}/roleAssertions`);R(d,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),d.actorAuthority!==void 0&&x(d.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let c=V(d.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||_("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((l,f)=>{i.has(l)||_("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${f}`)}),a.roleAssertions={roleCodes:K(c),...d.actorAuthority===!0?{actorAuthority:!0}:{}}}if(s.directory!==void 0){let d=N(s.directory,`${t}/directory`);R(d,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(d.mode))||_("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments",...d.mode==="current-initiator"?["phone"]:[]]),l=V(d.fields,`${t}/directory/fields`,c.size);(!l.length||l.some(f=>!c.has(f)))&&_("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),a.directory={mode:String(d.mode),fields:K(l)}}if(s.transactionTime!==void 0){let d=`${t}/transactionTime`,c=N(s.transactionTime,d);R(c,["mode","recordSetAssertions"],d,!0),(c.mode!=="database-accepted"||s.dataCommands?.mode!=="recoverable-native"||c.recordSetAssertions!==void 0&&c.recordSetAssertions!==!0)&&_("NATIVE_OPERATION_TRANSACTION_TIME_INVALID",d),a.transactionTime={mode:"database-accepted",...c.recordSetAssertions?{recordSetAssertions:!0}:{}}}if(s.directoryClasses!==void 0){let d=`${t}/directoryClasses`,c=N(s.directoryClasses,d);R(c,["maxIds"],d),(!Number.isSafeInteger(c.maxIds)||c.maxIds<1||c.maxIds>20)&&_("NATIVE_OPERATION_DIRECTORY_CLASSES_INVALID",d),a.directoryClasses={maxIds:c.maxIds}}if(s.selectedDepartments!==void 0){let d=`${t}/selectedDepartments`,c=N(s.selectedDepartments,d);R(c,["fields","maxIds"],d);let l=V(c.fields,`${d}/fields`,4);(!l.includes("name")||l.some(f=>!["name","path","parent","fullPath"].includes(f))||!Number.isSafeInteger(c.maxIds)||c.maxIds<1||c.maxIds>50)&&_("NATIVE_OPERATION_SELECTED_DEPARTMENTS_INVALID",d),a.selectedDepartments={fields:K(l),maxIds:c.maxIds}}if(s.managedFiles!==void 0){let d=D(s.managedFiles,`${t}/managedFiles`,16);d.length||_("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;a.managedFiles=ue(d.map((l,f)=>{let p=`${t}/managedFiles/${f}`,m=N(l,p);R(m,["resourceCode","fieldCodes","intents"],p);let A=Q(m.resourceCode,`${p}/resourceCode`);(c.has(A)||!o.has(A))&&_("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),c.add(A);let I=V(m.fieldCodes,`${p}/fieldCodes`,16);(!I.length||I.some(b=>!["file","image","signature","text.rich"].includes(String(o.get(A)?.get(b)||""))))&&_("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let O=V(m.intents,`${p}/intents`,2);return(!O.length||O.some(b=>!["create","update"].includes(b)))&&_("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:A,fieldCodes:K(I),intents:K(O)}}),l=>l.resourceCode)}if(s.managedFileCopies!==void 0){let d=D(s.managedFileCopies,`${t}/managedFileCopies`,16);d.length||_("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;a.managedFileCopies=ue(d.map((l,f)=>{let p=`${t}/managedFileCopies/${f}`,m=N(l,p);R(m,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),x(m.mode,"copy",`${p}/mode`);let A=Q(m.sourceResourceCode,`${p}/sourceResourceCode`),I=Q(m.targetResourceCode,`${p}/targetResourceCode`),O=o.get(A),b=o.get(I);(!O||!b)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let g=V(m.sourceFieldCodes,`${p}/sourceFieldCodes`,16),y=V(m.targetFieldCodes,`${p}/targetFieldCodes`,16);(!g.length||g.length!==y.length)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),g.forEach((u,E)=>{let w=O.get(u),S=b.get(y[E]);(!["file","image","text.rich"].includes(String(w))||w!==S)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${E}`)});let h=`${A}:${g.join(",")}=>${I}:${y.join(",")}`;return c.has(h)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),c.add(h),{mode:"copy",sourceResourceCode:A,sourceFieldCodes:K(g),targetResourceCode:I,targetFieldCodes:K(y)}}),l=>`${l.sourceResourceCode}:${l.sourceFieldCodes.join(",")}=>${l.targetResourceCode}:${l.targetFieldCodes.join(",")}`)}if(s.notification!==void 0){let d=N(s.notification,`${t}/notification`);R(d,["mode"],`${t}/notification`),d.mode!=="business-standard"&&_("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),a.notification={mode:"business-standard"}}if(s.workflow!==void 0){let d=N(s.workflow,`${t}/workflow`);R(d,["codes"],`${t}/workflow`,["businessCommands"]);let c=V(d.codes,`${t}/workflow/codes`,16);(!c.length||c.some(f=>!r.has(f)))&&_("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let l=d.businessCommands===void 0?void 0:V(d.businessCommands,`${t}/workflow/businessCommands`,4);l&&(!l.length||l.some(f=>!["approve","reject","withdraw","resubmit"].includes(f)))&&_("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),a.workflow={codes:K(c),...l?{businessCommands:K(l)}:{}}}if(s.ownedSubject!==void 0){let d=`${t}/ownedSubject`,c=s.ownedSubject;try{Go(c)}catch{_("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",d)}(!a.workflow||s.decimalReservation!==void 0)&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",d);try{wd(c,n,a.managedFiles||[])}catch(l){_(`NATIVE_${l.message}`,d)}a.ownedSubject={mode:"create",resourceCode:c.resourceCode,subtables:ue(c.subtables.map(l=>({fieldCode:l.fieldCode,fieldCodes:K([...l.fieldCodes])})),l=>l.fieldCode)}}if(s.decimalReservation!==void 0){let d=`${t}/decimalReservation`,c=N(s.decimalReservation,d);R(c,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],d);let l=k(c.mode,`${d}/mode`,16);["reserve","commit","release"].includes(l)||_("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${d}/mode`);let f=Q(c.resourceCode,`${d}/resourceCode`),p=n.get(f);p||_("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${d}/resourceCode`);let A=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(u=>[u,J(c[u],`${d}/${u}`)])),I=u=>p.get(A[u]),O=u=>new Set((I(u)?.options||[]).map(E=>String(E.value))),b=F(c.parentRelationValue,`${d}/parentRelationValue`),g=F(c.childRelationValue,`${d}/childRelationValue`),y=V(c.eligibleParentStatuses,`${d}/eligibleParentStatuses`,16),h=V(c.eligibleChildStatuses,`${d}/eligibleChildStatuses`,16);(I("amountFieldCode")?.type!=="number.decimal"||I("amountFieldCode")?.exactDecimal!==!0||I("amountFieldCode")?.precision!==18||I("amountFieldCode")?.scale!==2||I("currencyFieldCode")?.type!=="option.single"||I("relationFieldCode")?.type!=="option.single"||I("parentFieldCode")?.type!=="resource-ref.single"||I("parentFieldCode")?.source?.resourceCode!==f||I("rootFieldCode")?.type!=="uuid"||I("statusFieldCode")?.type!=="option.single"||b===g||!O("relationFieldCode").has(b)||!O("relationFieldCode").has(g)||!y.length||!h.length||y.some(u=>!O("statusFieldCode").has(u))||h.some(u=>!O("statusFieldCode").has(u)))&&_("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",d),a.decimalReservation={mode:l,resourceCode:f,...A,parentRelationValue:b,childRelationValue:g,eligibleParentStatuses:K(y),eligibleChildStatuses:K(h)}}return a}function gf(e,t,o,n,r){if(e===void 0)return;let i=`${t}/ai`,s=N(e,i);$u.test(o)||_("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),R(s,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],i,!0),k(s.name,`${i}/name`,qi),k(s.description,`${i}/description`,qi);let a=k(s.risk,`${i}/risk`,16);["read","write","destructive","external"].includes(a)||_("NATIVE_OPERATION_AI_RISK_INVALID",`${i}/risk`),a==="read"!=(n==="GET")&&_("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`),n==="DELETE"&&!["destructive","external"].includes(a)&&_("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`);let d=V(s.resources,`${i}/resources`,16);d.length===0&&_("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${i}/resources`),d.forEach((l,f)=>{let p=Q(l,`${i}/resources/${f}`);r.has(p)||_("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${i}/resources/${f}`)});let c=V(s.sideEffects,`${i}/sideEffects`,20);(a==="read"&&c.length!==0||a!=="read"&&c.length===0)&&_("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${i}/sideEffects`),s.concurrency!==void 0&&!["none","revision"].includes(k(s.concurrency,`${i}/concurrency`,16))&&_("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${i}/concurrency`),s.timeoutMs!==void 0&&Ae(s.timeoutMs,`${i}/timeoutMs`,100,3e4)}function Xo(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(o=>o.startsWith(":")?":":o.includes("*")?"*":o).join("/")}function _f(e,t){let o=N(e,t),n=k(o.type,`${t}/type`,32),r=["code","type","label","presentation","required"],i=n==="sso"?[...r,"provider"]:n==="dingtalk"?[...r,"flow"]:r;R(o,i,t);let s=F(o.code,`${t}/code`),a=k(o.label,`${t}/label`,255),d=k(o.presentation,`${t}/presentation`,16);["primary","secondary"].includes(d)||_("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let c=_n(o.required,`${t}/required`);return["sso","password","dingtalk"].includes(n)||_("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),n==="sso"&&o.provider!=="tenant-default"&&_("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),n==="dingtalk"&&!["auto","jsapi","oauth"].includes(k(o.flow,`${t}/flow`,16))&&_("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:s,type:n,label:a,presentation:d,required:c,...n==="sso"?{provider:"tenant-default"}:{},...n==="dingtalk"?{flow:o.flow}:{}}}function Pd(e,t,o){let n=N(e,o);R(n,["routeCode","path","defaultRouteCode"],o);let r=F(n.routeCode,`${o}/routeCode`),i=Je(n.path,`${o}/path`),s=t==="desktop"?"/login":"/m/login";return(i!==s||/[:*?#\\]/.test(i))&&_("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${o}/path`,{device:t,expectedPath:s}),{routeCode:r,path:i,defaultRouteCode:F(n.defaultRouteCode,`${o}/defaultRouteCode`)}}function Xd(e,t,o,n){if(e===null)return;let r=N(e,n);R(r,["accountMode","registration","methods","surfaces"],n),x(r.accountMode,"existing-platform-users-only",`${n}/accountMode`);let i=N(r.registration,`${n}/registration`);R(i,["mode"],`${n}/registration`),x(i.mode,"reject",`${n}/registration/mode`);let s=D(r.methods,`${n}/methods`,8);s.length===0&&_("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${n}/methods`);let a=s.map((b,g)=>_f(b,`${n}/methods/${g}`)),d=new Set,c=new Set;for(let[b,g]of a.entries())d.has(g.code)&&_("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${n}/methods/${b}/code`),c.has(g.type)&&_("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${n}/methods/${b}/type`),d.add(g.code),c.add(g.type);a.filter(b=>b.presentation==="primary").length!==1&&_("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${n}/methods`);let l=N(r.surfaces,`${n}/surfaces`);R(l,["desktop","mobile"],`${n}/surfaces`);let f=Pd(l.desktop,"desktop",`${n}/surfaces/desktop`),p=Pd(l.mobile,"mobile",`${n}/surfaces/mobile`);f.routeCode===p.routeCode&&_("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${n}/surfaces/mobile/routeCode`);let m=D(t,"/config/frontend/routes",q.routes),A=new Map;for(let[b,g]of m.entries()){let y=N(g,`/config/frontend/routes/${b}`);A.set(String(y.code||""),y)}let I=new Set((Array.isArray(o.data?.resources)?o.data.resources:[]).map(b=>String(b.code||"")).filter(b=>/^[a-z][a-z0-9-]{0,62}$/.test(b)));for(let[b,g]of[["desktop",f],["mobile",p]]){A.has(g.routeCode)&&_("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${n}/surfaces/${b}/routeCode`);let y=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),h=A.get(g.defaultRouteCode),u=String(h?.path||"");if(y&&I.has(y[1])){let w=y[2]==="records"?`/my/${y[1]}`:`/my/${y[1]}/submit`;h={surface:"user",path:b==="mobile"?`/m${w}`:w},u=String(h.path)}let E=b==="desktop"?u==="/m"||u.startsWith("/m/"):!(u==="/m"||u.startsWith("/m/"));(!h||h.surface!=="user"||/[:*]/.test(u)||E)&&_("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${n}/surfaces/${b}/defaultRouteCode`)}let O=Zd(o).filter(b=>!b.owner.startsWith("authentication:"));for(let[b,g]of[["desktop",f],["mobile",p]]){let y=O.find(h=>Xo(h.path)===Xo(g.path));y&&_("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${n}/surfaces/${b}/path`,{owner:y.owner})}}function Af(e,t){if(e===null)return;let o={data:{resources:[]},workflows:{definitions:[]},frontend:{routes:[{code:"auth-desktop-default",path:"/auth-desktop-default",surface:"user"},{code:"auth-mobile-default",path:"/m/auth-mobile-default",surface:"user"}],user:{applicationTodoCenter:!1},admin:{navigation:[]},authentication:e}},n=N(e,t),r=N(n.surfaces,`${t}/surfaces`),i={...n,surfaces:{...r,desktop:{...N(r.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(r.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};Xd(i,o.frontend.routes,{...o,frontend:{...o.frontend,authentication:i}},t)}function Ef(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 If=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read","public.query"]);function yf(e,t,o){let n=N(e,o);R(n,["policies"],o);let r=D(n.policies,`${o}/policies`,16);r.length<1&&_("NATIVE_PUBLIC_POLICY_REQUIRED",o);let i=new Map(t.frontend.routes.map(c=>[c.code,c])),s=new Map(t.data.resources.map(c=>[c.code,c])),a=new Set,d=new Set(r.map(c=>String(c?.code||"")));r.forEach((c,l)=>{let f=`${o}/policies/${l}`,p=N(c,f);R(p,["code","routeCode","mode","resourceCode","operations","fields"],f,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","publicQueries","draft","validations"]);let m=F(p.code,`${f}/code`);a.has(m)&&_("NATIVE_PUBLIC_POLICY_DUPLICATE",`${f}/code`);let A=F(p.routeCode,`${f}/routeCode`),I=i.get(A);(!I||I.surface!=="user"||I.capability!==void 0||I.access!==void 0||/[:*]/.test(String(I.path)))&&_("NATIVE_PUBLIC_ROUTE_INVALID",`${f}/routeCode`),x(p.mode,"anonymous",`${f}/mode`);let O=Q(p.resourceCode,`${f}/resourceCode`),b=s.get(O);b||_("NATIVE_PUBLIC_RESOURCE_MISSING",`${f}/resourceCode`);let g=new Map(b.schema.fields.map($=>[String($.code),String($.type)])),y=V(p.operations,`${f}/operations`,8);(y.length<1||y.some($=>!If.has($)))&&_("NATIVE_PUBLIC_OPERATION_INVALID",`${f}/operations`),y.includes("draft.read")!==y.includes("draft.update")&&_("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${f}/operations`);let h=V(p.fields,`${f}/fields`,64);(h.length<1||h.some($=>!g.has($)))&&_("NATIVE_PUBLIC_FIELD_INVALID",`${f}/fields`);for(let $ of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,$))continue;V(p[$],`${f}/${$}`,64).some(W=>!h.includes(W))&&_("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${f}/${$}`)}let u=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?D(p.serverGeneratedFields,`${f}/serverGeneratedFields`,16):[],E=new Set;u.forEach(($,Y)=>{let W=`${f}/serverGeneratedFields/${Y}`,M=N($,W);R(M,["field","kind"],W);let B=J(M.field,`${W}/field`);(E.has(B)||!g.has(B)||h.includes(B)||g.get(B)!=="text.short"&&g.get(B)!=="text.long")&&_("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${W}/field`),x(M.kind,"random-token",`${W}/kind`),E.add(B)});let w=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${f}/schedule`):null;if(w){let $=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];R(w,$,`${f}/schedule`);for(let Y of["campusPolicyCode","rulePolicyCode"])F(w[Y],`${f}/schedule/${Y}`);for(let Y of $.filter(W=>!["campusPolicyCode","rulePolicyCode"].includes(W)))J(w[Y],`${f}/schedule/${Y}`);for(let Y of[w.campusField,w.dateField,w.timeField])h.includes(String(Y))||_("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${f}/schedule`);(!d.has(String(w.campusPolicyCode))||!d.has(String(w.rulePolicyCode)))&&_("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${f}/schedule`)}let S=Object.prototype.hasOwnProperty.call(p,"publicFilters")?D(p.publicFilters,`${f}/publicFilters`,16):[],T=new Set;S.forEach(($,Y)=>{let W=`${f}/publicFilters/${Y}`,M=N($,W);R(M,["field","operator","value"],W);let B=J(M.field,`${W}/field`);T.has(B)&&_("NATIVE_PUBLIC_FILTER_DUPLICATE",`${W}/field`),h.includes(B)||_("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${W}/field`),x(M.operator,"eq",`${W}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time","option.single"].includes(g.get(B)||"")||_("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${W}/field`),M.value!==null&&typeof M.value!="string"&&typeof M.value!="number"&&typeof M.value!="boolean"&&_("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${W}/value`),["option.single"].includes(g.get(B)||"")&&M.value!==null&&typeof M.value!="string"&&_("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${W}/value`),T.add(B)});let C=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${f}/publicSubtableFields`):null;if(C){Object.keys(C).length>64&&_("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${f}/publicSubtableFields`);for(let[$,Y]of Object.entries(C)){let W=b.schema.fields.find(pe=>String(pe.code)===$),M=String(W?.subtable?.resourceCode||""),B=s.get(M),oe=new Map((B?.schema?.fields||[]).map(pe=>[String(pe.code),String(pe.type)])),se=V(Y,`${f}/publicSubtableFields/${$}`,64);(!h.includes($)||g.get($)!=="subtable"||!B||se.length<1||se.some(pe=>!oe.has(pe))||se.some(pe=>oe.get(pe)==="subtable")||se.some(pe=>oe.get(pe)==="signature"))&&_("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${f}/publicSubtableFields/${$}`)}}let v=Object.prototype.hasOwnProperty.call(p,"publicRecordFields")?V(p.publicRecordFields,f+"/publicRecordFields",64):[];y.some($=>$.startsWith("public."))&&(Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||_("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",f+"/publicRecordFields"),(v.length<1||v.some($=>!h.includes($))||v.some($=>g.get($)==="signature"||g.get($)==="subtable"&&!C?.[$]))&&_("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",f+"/publicRecordFields"));let P=Object.prototype.hasOwnProperty.call(p,"publicQueries")?D(p.publicQueries,f+"/publicQueries",16):[],H=new Set;P.forEach(($,Y)=>{let W=f+"/publicQueries/"+Y,M=N($,W);R(M,["code","kind","resourceCode","fields","defaultLimit","maxLimit"],W,["sort","parameters","aggregate"]);let B=F(M.code,W+"/code");H.has(B)&&_("NATIVE_PUBLIC_QUERY_DUPLICATE",W+"/code"),H.add(B),["records","aggregate"].includes(String(M.kind))||_("NATIVE_PUBLIC_QUERY_KIND_INVALID",W+"/kind"),String(M.resourceCode)!==O&&_("NATIVE_PUBLIC_QUERY_RESOURCE_INVALID",W+"/resourceCode");let oe=V(M.fields,W+"/fields",64);(oe.length<1||oe.some(te=>!h.includes(te))||oe.some(te=>!v?.includes(te)))&&_("NATIVE_PUBLIC_QUERY_FIELDS_INVALID",W+"/fields");let se=Number(M.defaultLimit),pe=Number(M.maxLimit);if((!Number.isSafeInteger(se)||!Number.isSafeInteger(pe)||se<1||pe<se||pe>100)&&_("NATIVE_PUBLIC_QUERY_LIMIT_INVALID",W+"/maxLimit"),Object.prototype.hasOwnProperty.call(M,"sort")){let te=D(M.sort,W+"/sort",4),de=new Set;te.forEach((gt,Xe)=>{let Me=W+"/sort/"+Xe,Ve=N(gt,Me);R(Ve,["field","direction"],Me);let De=J(Ve.field,Me+"/field");(!oe.includes(De)||de.has(De)||!["asc","desc"].includes(String(Ve.direction)))&&_("NATIVE_PUBLIC_QUERY_SORT_INVALID",Me),de.add(De)})}if(Object.prototype.hasOwnProperty.call(M,"parameters")){let te=D(M.parameters,W+"/parameters",8),de=new Set;te.forEach((gt,Xe)=>{let Me=W+"/parameters/"+Xe,Ve=N(gt,Me);R(Ve,["name","field","operator","type"],Me);let De=F(Ve.name,Me+"/name"),at=J(Ve.field,Me+"/field");(de.has(De)||!oe.includes(at)||!["eq","contains","in"].includes(String(Ve.operator))||!["string","number","boolean","string[]"].includes(String(Ve.type)))&&_("NATIVE_PUBLIC_QUERY_PARAMETER_INVALID",Me),de.add(De)})}if(Object.prototype.hasOwnProperty.call(M,"aggregate")){String(M.kind)!=="aggregate"&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_KIND_INVALID",W+"/aggregate");let te=W+"/aggregate",de=N(M.aggregate,te);R(de,["measures"],te,["dimensions","order"]);let gt=new Set,Xe=(De,at)=>{let ce=String(De||"").trim();return(!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(ce)||gt.has(ce))&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_ALIAS_INVALID",at),gt.add(ce),ce};(Object.prototype.hasOwnProperty.call(de,"dimensions")?D(de.dimensions,te+"/dimensions",3):[]).forEach((De,at)=>{let ce=`${te}/dimensions/${at}`,Oe=N(De,ce);R(Oe,["field","as"],ce,["bucket"]);let Be=J(Oe.field,ce+"/field");oe.includes(Be)||_("NATIVE_PUBLIC_QUERY_AGGREGATE_FIELD_INVALID",ce+"/field"),Xe(Oe.as,ce+"/as"),Oe.bucket!==void 0&&!["day","week","month","quarter","year"].includes(String(Oe.bucket))&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_BUCKET_INVALID",ce+"/bucket")});let Ve=D(de.measures,te+"/measures",8);Ve.length<1&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_MEASURES_INVALID",te+"/measures"),Ve.forEach((De,at)=>{let ce=`${te}/measures/${at}`,Oe=N(De,ce);R(Oe,["type","as"],ce,["field"]);let Be=String(Oe.type),_r=Oe.field===void 0?void 0:J(Oe.field,ce+"/field");(!["count","countDistinct","sum","avg","min","max"].includes(Be)||(Be==="count"?_r!==void 0:!_r||!oe.includes(_r)))&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_MEASURE_INVALID",ce),Xe(Oe.as,ce+"/as")}),Object.prototype.hasOwnProperty.call(de,"order")&&D(de.order,te+"/order",10).forEach((at,ce)=>{let Oe=`${te}/order/${ce}`,Be=N(at,Oe);R(Be,["field"],Oe,["direction","nulls"]),(!gt.has(String(Be.field))||Be.direction!==void 0&&!["asc","desc"].includes(String(Be.direction))||Be.nulls!==void 0&&!["first","last"].includes(String(Be.nulls)))&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_ORDER_INVALID",Oe)})}});let ne=Object.prototype.hasOwnProperty.call(p,"requiredFields")?V(p.requiredFields,`${f}/requiredFields`,64):[],Z=b.surface||{},Se=Z.fields||{},Ee=String(Z.mutationOwner||"native")==="native"&&Z.generated?.create!==!1,Ie=b.schema.fields.filter($=>Et($,Se[$.code])).map($=>String($.code));if(y.includes("create")&&!Ee&&_("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${f}/fields`),y.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&_("NATIVE_PUBLIC_DRAFT_REQUIRED",`${f}/draft`),y.includes("create"))for(let $ of Ie){let Y=h.includes($)?ne.includes($)?null:"requiredFields":"fields";Y&&_("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${f}/${Y}`,{resourceCode:Q,fieldCode:$})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let $=N(p.draft,`${f}/draft`);R($,["enabled","inactivityTtlSeconds","maxBytes"],`${f}/draft`),x($.enabled,!0,`${f}/draft/enabled`),Ae($.inactivityTtlSeconds,`${f}/draft/inactivityTtlSeconds`,3600,7776e3),Ae($.maxBytes,`${f}/draft/maxBytes`,4096,262144)}else y.includes("draft.read")&&_("NATIVE_PUBLIC_DRAFT_REQUIRED",`${f}/draft`);let fe=Object.prototype.hasOwnProperty.call(p,"validations")?D(p.validations,`${f}/validations`,16):[],ye=new Set;fe.forEach(($,Y)=>{let W=`${f}/validations/${Y}`,M=N($,W);R(M,["code","kind","fields","result"],W);let B=F(M.code,`${W}/code`);ye.has(B)&&_("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${W}/code`),x(M.kind,"duplicate",`${W}/kind`),x(M.result,"availability",`${W}/result`);let oe=V(M.fields,`${W}/fields`,8);(oe.length<1||oe.some(se=>!h.includes(se))||oe.some(se=>["file","subtable"].includes(g.get(se)||"")))&&_("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${W}/fields`),ye.add(B)}),a.add(m)})}function Of(e,t){let o=N(e,t);R(o,["policies"],t),D(o.policies,`${t}/policies`,16).length<1&&_("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function bf(e){return{policies:ue(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:K(t.operations),fields:K(t.fields),...t.requiredFields?{requiredFields:K(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:K(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:K(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(o=>({field:o.field,operator:o.operator,value:o.value})).sort((o,n)=>Ce(o.field,n.field))}:{},...t.publicQueries?{publicQueries:ue(t.publicQueries.map(o=>({code:o.code,kind:o.kind,resourceCode:o.resourceCode,fields:K(o.fields),defaultLimit:Number(o.defaultLimit),maxLimit:Number(o.maxLimit),...o.sort?{sort:o.sort.map(n=>({field:n.field,direction:n.direction})).sort((n,r)=>Ce(n.field,r.field))}:{},...o.parameters?{parameters:o.parameters.map(n=>({name:n.name,field:n.field,operator:n.operator,type:n.type})).sort((n,r)=>Ce(n.name,r.name))}:{},...o.aggregate?{aggregate:{...o.aggregate.dimensions?{dimensions:o.aggregate.dimensions.map(n=>({field:n.field,as:n.as,...n.bucket?{bucket:n.bucket}:{}})).sort((n,r)=>n.as.localeCompare(r.as))}:{},measures:o.aggregate.measures.map(n=>({type:n.type,...n.field?{field:n.field}:{},as:n.as})).sort((n,r)=>n.as.localeCompare(r.as)),...o.aggregate.order?{order:o.aggregate.order.map(n=>({field:n.field,...n.direction?{direction:n.direction}:{},...n.nulls?{nulls:n.nulls}:{}})).sort((n,r)=>n.field.localeCompare(r.field))}:{}}}:{}})),o=>String(o.code))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([o],[n])=>o.localeCompare(n)).map(([o,n])=>[o,K(Array.isArray(n)?n.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(o=>({field:o.field,kind:o.kind})).sort((o,n)=>Ce(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:ue(t.validations.map(o=>({code:o.code,kind:o.kind,fields:K(o.fields),result:o.result})),o=>o.code)}:{}})),t=>t.code)}}function Zd(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=Qd(o),r=`/admin/resources/${o.code}`,i=[["list",r],["detail",`${r}/:id`],["create",`${r}/new`],["update",`${r}/:id/edit`]];for(let[s,a]of i)n[s]&&t.push({owner:`resource:${o.code}:${s}`,path:a},{owner:`resource:${o.code}:${s}:mobile`,path:`/m${a}`})}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 tr(e){let t=new Map(Zd(e).map(o=>[Xo(o.path),o]));return ue(e.frontend.routes.map((o,n)=>{let r=`/config/frontend/routes/${n}`,i=N(o,r);R(i,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],r,!0),["admin","user"].includes(i.surface)||_("NATIVE_ROUTE_SURFACE_INVALID",`${r}/surface`);let s=Je(i.path,`${r}/path`);i.surface==="admin"&&s!=="/admin"&&!s.startsWith("/admin/")&&_("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${r}/path`),i.surface==="user"&&(s==="/admin"||s.startsWith("/admin/"))&&_("NATIVE_USER_ROUTE_PATH_RESERVED",`${r}/path`);let a=Xo(s),d=t.get(a);d&&_("NATIVE_ROUTE_PATH_CONFLICT",`${r}/path`,{path:s,owner:d.owner}),t.set(a,{owner:`frontend:${String(i.code||n)}`,path:s});let c=/[:*]/.test(s),l=Zi(i,r,e.appCode),f=i.pinned===void 0?void 0:_n(i.pinned,`${r}/pinned`),p=i.tabPersistence===void 0?c?"none":"session":k(i.tabPersistence,`${r}/tabPersistence`,16),m=i.keepAlive===void 0?"none":k(i.keepAlive,`${r}/keepAlive`,16);return["session","none"].includes(p)||_("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${r}/tabPersistence`),["none","memory"].includes(m)||_("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${r}/keepAlive`),c&&f===!0&&_("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${r}/pinned`),c&&p==="session"&&_("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${r}/tabPersistence`),c&&m==="memory"&&_("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${r}/keepAlive`),{code:F(i.code,`${r}/code`),path:s,label:k(i.label,`${r}/label`,255),surface:i.surface,...i.parentCode===void 0?{}:{parentCode:F(i.parentCode,`${r}/parentCode`)},...l,...f===void 0?{}:{pinned:f},tabPersistence:p,keepAlive:m}}),o=>o.code)}function Qd(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),o=t.mutationOwner||"native",n=t.generated===void 0?{}:N(t.generated,"/surface/generated"),r=o==="native";return{list:n.list??!0,detail:n.detail??!0,create:n.create??r,update:n.update??r,delete:n.delete??r}}function ec(e){let t=[];for(let o of ue(e.data.resources,n=>n.code).flatMap(n=>[{resource:n,viewCode:void 0},...(n.surface?.views||[]).map(r=>({viewCode:r.code,resource:{...n,name:r.name,surface:ni(n.surface,r.code)}}))])){let{resource:n,viewCode:r}=o,i=`/admin/resources/${n.code}${r?`/views/${r}`:""}`,s=Qd(n),a=[{operation:"list",kind:"resource-list",path:`${i}`,label:n.name,capability:n.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${i}/:id`,label:`${n.name}\u8BE6\u60C5`,capability:n.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${i}/new`,label:`\u65B0\u589E${n.name}`,capability:n.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${i}/:id/edit`,label:`\u7F16\u8F91${n.name}`,capability:n.capabilities.update,navigationEligible:!1}];for(let d of a)s[d.operation]&&t.push({code:`resource:${n.code}${r?`:view:${r}`:""}:${d.operation}`,kind:d.kind,path:d.path,label:d.label,navigationEligible:d.navigationEligible,capability:d.capability,resourceCode:n.code,...r?{viewCode:r}:{}})}for(let o of tr(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)=>Ce(o.code,n.code))}function tc(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function hf(e){return e.frontend.admin.navigation.map((t,o)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??o,items:t.items.map((n,r)=>({pageCode:tc(n.page),...n.label===void 0?{}:{label:n.label},...n.icon===void 0?{}:{icon:n.icon},order:n.order??r})).sort((n,r)=>n.order-r.order||Ce(n.pageCode,r.pageCode))})).sort((t,o)=>t.order-o.order||Ce(t.code,o.code))}function Nf(e,t){let o=D(e,t,q.adminNavigationGroups);o.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>q.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((r,i)=>{let s=`${t}/${i}`,a=N(r,s);R(a,["code","label","icon","order","items"],s,!0),F(a.code,`${s}/code`),k(a.label,`${s}/label`,255),Zo(a.icon,`${s}/icon`),xd(a.order,`${s}/order`);let d=D(a.items,`${s}/items`,500);d.length===0&&_("NATIVE_ADMIN_GROUP_ORPHANED",`${s}/items`),n+=d.length,n>q.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),d.forEach((c,l)=>{let f=`${s}/items/${l}`,p=N(c,f);R(p,["page","label","icon","order"],f,!0),wf(p.page,`${f}/page`),p.label!==void 0&&k(p.label,`${f}/label`,255),Zo(p.icon,`${f}/icon`),xd(p.order,`${f}/order`)})})}function wf(e,t){let o=N(e,t),n=k(o.kind,`${t}/kind`,64);if(n==="resource"){R(o,["kind","resourceCode"],t,["viewCode"]),o.viewCode!==void 0&&F(o.viewCode,`${t}/viewCode`),Q(o.resourceCode,`${t}/resourceCode`);return}if(n==="operation"){R(o,["kind","routeCode"],t),F(o.routeCode,`${t}/routeCode`);return}_("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function Rf(e){let t=new Map(ec(e).map(r=>[String(r.code),r])),o=new Set,n=new Set;e.frontend.admin.navigation.forEach((r,i)=>{let s=`/config/frontend/admin/navigation/${i}`;o.has(r.code)&&_("NATIVE_ADMIN_GROUP_DUPLICATE",`${s}/code`),o.add(r.code),r.label===r.code&&_("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${s}/label`),r.items.forEach((a,d)=>{let c=`${s}/items/${d}`,l=tc(a.page),f=t.get(l);(!f||f.navigationEligible!==!0)&&_("NATIVE_ADMIN_PAGE_NOT_FOUND",`${c}/page`),n.has(l)&&_("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/page`),n.add(l);let p=a.page.resourceCode||a.page.routeCode||a.page.workflowCode||l,m=a.label||f.label;(!m||m===p||m===l)&&_("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`)})})}function Tf(e,t){let o=D(e,t,q.adminPages),n=new Set;o.forEach((r,i)=>{let s=`${t}/${i}`,a=N(r,s);R(a,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],s,!0);let d=k(a.code,`${s}/code`,255);n.has(d)&&_("NATIVE_ADMIN_PAGE_DUPLICATE",`${s}/code`),n.add(d);let c=k(a.kind,`${s}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(c)||_("NATIVE_ADMIN_PAGE_KIND_INVALID",`${s}/kind`),Je(a.path,`${s}/path`),k(a.label,`${s}/label`,255),_n(a.navigationEligible,`${s}/navigationEligible`),a.capability!==void 0&&a.access!==void 0&&_("NATIVE_ROUTE_ACCESS_CONFLICT",`${s}/access`),a.capability!==void 0&&k(a.capability,`${s}/capability`,255),a.access!==void 0){let l=N(a.access,`${s}/access`);R(l,["allOf","anyOf"],`${s}/access`,!0);for(let f of["allOf","anyOf"])l[f]!==void 0&&V(l[f],`${s}/access/${f}`,50)}for(let l of["resourceCode","viewCode","routeCode"])a[l]!==void 0&&F(a[l],`${s}/${l}`)})}function Cf(e,t){let o=D(e,t,q.adminNavigationGroups);o.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>q.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let n=0;o.forEach((r,i)=>{let s=`${t}/${i}`,a=N(r,s);R(a,["code","label","icon","order","items"],s,!0),F(a.code,`${s}/code`),k(a.label,`${s}/label`,255),Zo(a.icon,`${s}/icon`),Ae(a.order,`${s}/order`,-1e4,1e4);let d=D(a.items,`${s}/items`,500);d.length===0&&_("NATIVE_ADMIN_GROUP_ORPHANED",`${s}/items`),n+=d.length,n>q.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),d.forEach((c,l)=>{let f=`${s}/items/${l}`,p=N(c,f);R(p,["pageCode","label","icon","order"],f,!0),k(p.pageCode,`${f}/pageCode`,255),p.label!==void 0&&k(p.label,`${f}/label`,255),Zo(p.icon,`${f}/icon`),Ae(p.order,`${f}/order`,-1e4,1e4)})})}var Sf=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function Df(e,t,o){let n=N(e,t);R(n,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),x(n.schemaVersion,Jd,`${t}/schemaVersion`),x(n.appCode,o,`${t}/appCode`),Xi(n.devicePolicy,`${t}/devicePolicy`),kf(n.rootEntry,`${t}/rootEntry`),Lf(n.authentication,`${t}/authentication`),Hi(n.digest,`${t}/digest`);let r=D(n.routes,`${t}/routes`,q.routes),i=new Set;r.forEach((s,a)=>{let d=`${t}/routes/${a}`,c=N(s,d),l=c.kind==="resource-records"||c.kind==="resource-submit";R(c,["code","kind","desktop","mobile"],d,["workflowCode",...l?["resourceCode"]:[]]);let f=k(c.code,`${d}/code`,255);i.has(f)&&_("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${d}/code`),i.add(f);let p=k(c.kind,`${d}/kind`,64);if(Sf.has(p)||_("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${d}/kind`),c.workflowCode!==void 0&&F(c.workflowCode,`${d}/workflowCode`),l){let I=Q(c.resourceCode,`${d}/resourceCode`);x(f,`user.${I}.${c.kind==="resource-records"?"records":"submit"}`,`${d}/code`)}else c.resourceCode!==void 0&&_("NATIVE_PROPERTY_UNKNOWN",`${d}/resourceCode`);let m=Fd(c.desktop,`${d}/desktop`,o),A=Fd(c.mobile,`${d}/mobile`,o);m.surface!=="user"&&_("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${d}/desktop/surface`),A.surface!=="user"&&_("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${d}/mobile/surface`),m.routeCode===A.routeCode&&_("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",d)}),x(n.digest,ee({schemaVersion:n.schemaVersion,appCode:n.appCode,devicePolicy:n.devicePolicy,rootEntry:n.rootEntry,authentication:n.authentication,routes:n.routes}),`${t}/digest`)}function Xi(e,t){let o=N(e,t);R(o,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),x(o.kind,"viewport-family",`${t}/kind`);let n=Ae(o.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),r=Ae(o.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return r!==n+1&&_("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:n,desktopMinWidthPx:r}}function kf(e,t){let o=N(e,t);R(o,["code","desktop","mobile"],t);let n=F(o.code,`${t}/code`),r=Ji(o.desktop,`${t}/desktop`),i=Ji(o.mobile,`${t}/mobile`);return(r===i||i==="/"||!i.startsWith("/m/"))&&_("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),r.startsWith("/m/")&&_("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:n,desktop:r,mobile:i}}function Lf(e,t){let o=N(e,t);R(o,["desktop","mobile"],t);let n=$d(o.desktop,`${t}/desktop`,!1),r=$d(o.mobile,`${t}/mobile`,!0);return(n.routeCode===r.routeCode||n.path===r.path)&&_("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:n,mobile:r}}function $d(e,t,o){let n=N(e,t);R(n,["routeCode","path"],t);let r=F(n.routeCode,`${t}/routeCode`),i=Ji(n.path,`${t}/path`);return(o?!i.startsWith("/m/"):i.startsWith("/m/"))&&_("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:r,path:i}}function Ji(e,t){let o=Je(e,t);return/[:*?#\\\\]/.test(o)&&_("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),o}function Fd(e,t,o){let n=N(e,t);R(n,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),F(n.routeCode,`${t}/routeCode`);let r=Je(n.path,`${t}/path`),i=k(n.surface,`${t}/surface`,16);["admin","user"].includes(i)||_("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let s=V(n.pathParams,`${t}/pathParams`,8);return s.forEach((a,d)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(a)||a.length>64)&&_("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${d}`)}),re(s)!==re(nc(r))&&_("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Zi(n,t,o),n.requiresAuthentication!==!0&&_("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),n}function nc(e){return K([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function Vd(e,t,o,n){return{routeCode:e,path:t,surface:o,pathParams:nc(t),...n?.capability?{capability:n.capability}:{},...n?.access?{access:n.access}:{},requiresAuthentication:!0}}function Wd(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 vf(e){let t=e.appCode,o=[],n=(m,A,I,O,b,g,y)=>{o.push({code:m,kind:A,...b?{workflowCode:b}:{},...y?{resourceCode:y}:{},desktop:Vd(Wd(A,"desktop",b,y),I,"user",g),mobile:Vd(Wd(A,"mobile",b,y),O,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&n("application:todo-center","application-todo-center","/todos","/m/todos");let r=oc(e);r.length>0&&(n("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),n("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),n("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let m of r){if(!["standalone","hidden-handoff"].includes(m.launch.mode))continue;let A=K([m.launch.submission?.create?.requiredCapability,m.launch.submission?.existing?.requiredCapability].filter(I=>!!I));n(`workflow:${m.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",m.code,A.length===1?{capability:A[0]}:A.length>1?{access:{anyOf:A}}:void 0)}let i=o.sort((m,A)=>Ce(String(m.code),String(A.code))),s=tr(e),a=m=>{let A=m==="mobile"?"/m/":"/",I=s.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&b.path===A).sort((b,g)=>Ce(b.code,g.code))[0];if(I)return{code:I.code,path:I.path};let O=s.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&(m==="mobile"?b.path.startsWith("/m/"):!b.path.startsWith("/m/"))).sort((b,g)=>Ce(b.code,g.code))[0];return O?{code:O.code,path:O.path}:{code:m==="mobile"?"application-root-mobile":"application-root",path:A}},d=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},c=Xi(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),l=a("desktop"),f=a("mobile"),p={schemaVersion:Jd,appCode:t,devicePolicy:c,rootEntry:{code:l.code,desktop:l.path,mobile:f.path},authentication:d,routes:i};return{...p,digest:ee(p)}}function Zo(e,t){if(e===void 0)return;let o=k(e,t,32);zu.has(o)||_("NATIVE_ADMIN_ICON_INVALID",t)}function xd(e,t){e!==void 0&&Ae(e,t,-1e4,1e4)}function Zi(e,t,o){return e.capability!==void 0&&e.access!==void 0&&_("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:Pe(e.capability,`${t}/capability`,o)}:e.access===void 0?{}:{access:nr(e.access,`${t}/access`,o)}}function nr(e,t,o){let n=N(e,t);R(n,["allOf","anyOf"],t,!0);let r=n.allOf===void 0?void 0:K(V(n.allOf,`${t}/allOf`,50).map((s,a)=>Pe(s,`${t}/allOf/${a}`,o))),i=n.anyOf===void 0?void 0:K(V(n.anyOf,`${t}/anyOf`,50).map((s,a)=>Pe(s,`${t}/anyOf/${a}`,o)));return(r?.length||0)+(i?.length||0)===0&&_("NATIVE_ROUTE_ACCESS_EMPTY",t),{...r===void 0?{}:{allOf:r},...i===void 0?{}:{anyOf:i}}}function oc(e){let t=new Map(Yd(e).map(r=>[String(r.code),r])),o=e.workflows.definitions.map((r,i)=>{let s=`/config/workflows/definitions/${i}`,a=N(r,s);R(a,["version","definition","launch"],s,["detailRouteCode"]);let d=N(a.definition,`${s}/definition`),c=a.detailRouteCode===void 0?void 0:ic(a.detailRouteCode,`${s}/detailRouteCode`);return{code:F(d.code,`${s}/definition/code`),title:k(d.title,`${s}/definition/title`,255),version:gn(a.version,`${s}/version`),launch:Pf(e,d,a.launch,`${s}/launch`,t),...c?{detailRouteCode:c}:{},definition:d}});return K(o.map(r=>r.code)).map(r=>{let i=o.filter(c=>c.code===r),s=e.workflows.activations.find(c=>c.workflowCode===r)?.definitionVersion,a=i.find(c=>c.version===s)||[...i].sort((c,l)=>l.version-c.version)[0],d=new Set;for(let c of i){let l=N(c.definition.nodes,"/config/workflows/definitions/nodes");for(let f of Object.values(l)){let p=N(f,"/config/workflows/definitions/nodes/*");if(!(p.kind!=="approval"&&p.kind!=="handle"))for(let m of V(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))d.add(m)}}return{code:r,title:a.title,acceptedCommandDeactivationPolicy:a.definition.acceptedCommandDeactivationPolicy,subject:a.definition.subject,launch:a.launch,...["standalone","hidden-handoff"].includes(a.launch.mode)&&!a.launch.submission?{processOperationCode:`openxiangda.workflow.${r}.submit`}:{},...a.detailRouteCode?{detailRouteCode:a.detailRouteCode}:{},definitionVersions:zd(i.map(c=>c.version)),bindingVersions:zd(e.workflows.bindings.map((c,l)=>{let f=`/config/workflows/bindings/${l}`,p=N(c,f),m=N(p.binding,`${f}/binding`);return{code:F(m.workflowCode,`${f}/binding/workflowCode`),version:gn(p.version,`${f}/version`)}}).filter(c=>c.code===r).map(c=>c.version)),providerCodes:K(e.workflows.providers.map((c,l)=>F(N(c,`/config/workflows/providers/${l}`).code,`/config/workflows/providers/${l}/code`))),allowedOperations:[...d].sort(Ce),editableParameterCodes:K(e.workflows.editableParameters.map((c,l)=>{let f=`/config/workflows/editableParameters/${l}`,p=N(c,f);return{code:F(p.code,`${f}/code`),workflowCode:F(p.workflowCode,`${f}/workflowCode`)}}).filter(c=>c.workflowCode===r).map(c=>c.code))}})}function rc(e,t){let o=N(e,t);R(o,["mode"],t,["submission"]);let n=k(o.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(n)||_("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:n,...o.submission===void 0?{}:{submission:N(o.submission,`${t}/submission`)}}}function Pf(e,t,o,n,r){let i=rc(o,n);if(!i.submission)return{mode:i.mode};["standalone","hidden-handoff"].includes(i.mode)||_("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let s=N(i.submission,`${n}/submission`);R(s,["kind"],`${n}/submission`,["create","existing","context"]),x(s.kind,"named-operation",`${n}/submission/kind`);let a=n.endsWith("/launch")?n.slice(0,-7):n,d=N(t.subject,`${a}/definition/subject`),c=Q(d.resourceCode,`${a}/definition/subject/resourceCode`),l=e.data.resources.findIndex(E=>E.code===c),f=e.data.resources[l];(l<0||!f)&&_("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${a}/definition/subject/resourceCode`);let p=new Set(N(f.schema,`/config/data/resources/${l}/schema`).fields.map(E=>String(E.code))),m=new Map(e.backend.operations.map(E=>[String(E.code),E])),A=(E,w)=>{let S=`${n}/submission/${w}`,T=N(E,S);R(T,["operationCode","inputs","output"],S);let C=F(T.operationCode,`${S}/operationCode`),v=m.get(C),P=r.get(C),H=P?.platformAccess?.workflow?.codes;(!v||!P||P.method!=="POST"||!Array.isArray(H)||!H.includes(t.code))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",S);let ne=N(v.requestSchema,`${S}/operation/requestSchema`),Z=N(ne.properties,`${S}/operation/requestSchema/properties`),Se=new Set(ne.required===void 0?[]:V(ne.required,`${S}/operation/requestSchema/required`,205)),Ee=N(T.inputs,`${S}/inputs`),Ie=Object.entries(Ee);(!Ie.length||Ie.length>205)&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${S}/inputs`);let fe=new Set,ye=new Map,$={},Y=P.platformAccess?.ownedSubject;Y&&(w!=="create"||Y.resourceCode!==c)&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",S);for(let[B,oe]of Ie){(!kd.test(B)||!Object.prototype.hasOwnProperty.call(Z,B))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${S}/inputs/${B}`);let se=`${S}/inputs/${B}`,pe=N(oe,se),te=k(pe.source,`${se}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(te)||_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",se),R(pe,["source"],se,te==="field"?["fieldCode"]:!1),ye.set(te,(ye.get(te)||0)+1),te==="field"){let de=J(pe.fieldCode,`${se}/fieldCode`);(fe.has(de)||!p.has(de))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${se}/fieldCode`),fe.add(de),f.schema.fields.find(Xe=>Xe.code===de)?.type==="subtable"&&(!Y||!Y.subtables.some(Xe=>Xe.fieldCode===de))&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",se),$[B]={source:te,fieldCode:de}}else $[B]={source:te}}([...Se].some(B=>!(B in Ee))||(ye.get("idempotency-key")||0)!==1||!Ie.some(([B,oe])=>N(oe,`${S}/inputs/${B}`).source==="idempotency-key"&&Se.has(B))||w==="create"&&((ye.get("subject-id")||0)>0||(ye.get("subject-revision")||0)>0)||w==="existing"&&((ye.get("subject-id")||0)!==1||(ye.get("subject-revision")||0)!==1))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${S}/inputs`);let W=N(T.output,`${S}/output`);R(W,["subjectId"],`${S}/output`,["subjectRevision","processCommand"]);let M=N(N(v.responseSchema,`${S}/operation/responseSchema`).properties,`${S}/operation/responseSchema/properties`);for(let B of["subjectId","subjectRevision","processCommand"]){if(W[B]===void 0)continue;let oe=k(W[B],`${S}/output/${B}`,128);(!kd.test(oe)||!Object.prototype.hasOwnProperty.call(M,oe))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${S}/output/${B}`)}return{operationCode:C,method:"POST",path:P.path,requiredCapability:P.requiredCapability,requestSchemaDigest:P.requestSchemaDigest,responseSchemaDigest:P.responseSchemaDigest,inputs:$,output:{...W},fieldCodes:fe}},I=s.create===void 0?void 0:A(s.create,"create"),O=s.existing===void 0?void 0:A(s.existing,"existing");!I&&!O&&_("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${n}/submission`);let b=new Set([...I?.fieldCodes||[],...O?.fieldCodes||[]]),g=s.context===void 0?[]:D(s.context,`${n}/submission/context`,16),y=new Set,h=g.map((E,w)=>{let S=`${n}/submission/context/${w}`,T=N(E,S);R(T,["queryParameter","fieldCode"],S);let C=k(T.queryParameter,`${S}/queryParameter`,64),v=J(T.fieldCode,`${S}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(C)||y.has(C)||!b.has(v))&&_("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",S),y.add(C),{queryParameter:C,fieldCode:v}}),u=E=>{let{fieldCodes:w,...S}=E;return S};return{mode:i.mode,submission:{kind:"named-operation",...I?{create:u(I)}:{},...O?{existing:u(O)}:{},context:h}}}function ic(e,t){let o=N(e,t);R(o,["desktop","mobile"],t);let n=F(o.desktop,`${t}/desktop`),r=F(o.mobile,`${t}/mobile`);return n===r&&_("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:n,mobile:r}}function $f(e,t){let o=new Set(t.map(l=>l.code)),n=new Map;e.data.resources.forEach((l,f)=>{let p=`/config/data/resources/${f}`,m=N(l,p);if(m.recordDeletion!==void 0){let O=`${p}/recordDeletion/delete`;for(let b of m.recordDeletion.delete)Pe(b,O,e.appCode),o.has(b)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(m.recordComments!==void 0)for(let O of["read","create"]){let b=`${p}/recordComments/${O}`;for(let g of m.recordComments[O])Pe(g,b,e.appCode),o.has(g)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(m.recordPrint!==void 0){let O=`${p}/recordPrint/read`;for(let b of m.recordPrint.read)Pe(b,O,e.appCode),o.has(b)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(m.workflowHistory!==void 0){let O=`${p}/workflowHistory/read`;for(let b of m.workflowHistory.read)Pe(b,O,e.appCode),o.has(b)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}for(let[O,b]of Object.entries(m.fieldPolicies||{})){if(!Vt(O))continue;let g=`${p}/fieldPolicies/${O}/read`,y=N(b,`${p}/fieldPolicies/${O}`);for(let h of V(y.read||[],g,2e3))o.has(h)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}let A=m.surface===void 0?{}:N(m.surface,`${p}/surface`);if(["native","queued-command"].includes(A.mutationOwner||"native"))return;let I=N(m.capabilities,`${p}/capabilities`);for(let O of["create","update","delete"])O==="delete"&&Array.isArray(m.recordDeletion?.delete)&&m.recordDeletion.delete.length>0||n.set(String(I[O]),O)});let r=new Set;for(let[l,f]of e.authz.roles.entries()){let p=`/config/authz/roles/${l}`,m=N(f,p);R(m,["code","name","description","capabilities","organizationReach"],p,!0);let A=F(m.code,`${p}/code`);r.has(A)&&_("NATIVE_ROLE_DUPLICATE",`${p}/code`),r.add(A),k(m.name,`${p}/name`,255);let I=V(m.capabilities,`${p}/capabilities`,2e3);for(let[O,b]of I.entries())n.has(b)&&_("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${O}`,{operation:n.get(b)}),o.has(b)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let i=e.authz.authenticatedUserRoleCode===void 0?"":F(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");i&&!r.has(i)&&_("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let s=new Set,a=0;for(let[l,f]of e.perspectives.entries()){let p=`/config/perspectives/${l}`,m=N(f,p);R(m,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let A=F(m.code,`${p}/code`);s.has(A)&&_("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),s.add(A),k(m.name,`${p}/name`,255);let I=V(m.roleCodes,`${p}/roleCodes`,20);I.length<1&&_("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),I.forEach((g,y)=>{r.has(g)||_("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${y}`)});let O=K(e.authz.roles.filter(g=>I.includes(g.code)).flatMap(g=>g.capabilities)),b=V(m.capabilityCodes,`${p}/capabilityCodes`,2e3);re(O)!==re(b)&&_("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),m.default===!0?a+=1:m.default!==void 0&&_("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}a>1&&_("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[l,f]of e.backend.operations.entries()){let p=N(f,`/config/backend/operations/${l}`);o.has(p.capability)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${l}/capability`)}let d=new Set,c=new Set;for(let[l,f]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${l}`,m=N(f,p),A=F(m.code,`${p}/code`);d.has(A)&&_("NATIVE_ROUTE_DUPLICATE",`${p}/code`),d.add(A);let I=Je(m.path,`${p}/path`);c.has(I)&&_("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),c.add(I);let O=Zi(m,p,e.appCode);O.capability&&!o.has(O.capability)&&_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let b=m.access===void 0?void 0:N(m.access,`${p}/access`);for(let g of["allOf","anyOf"]){let y=b?.[g]===void 0?[]:D(b[g],`${p}/access/${g}`,50);for(let[h,u]of y.entries()){let E=Pe(u,`${p}/access/${g}/${h}`,e.appCode);o.has(E)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${g}/${h}`)}}}if(e.frontend.admin.access!==void 0){let l=nr(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let f of["allOf","anyOf"])for(let[p,m]of(l[f]||[]).entries())o.has(m)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${f}/${p}`)}for(let[l,f]of e.frontend.routes.entries()){let p=N(f,`/config/frontend/routes/${l}`);p.parentCode&&!d.has(p.parentCode)&&_("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${l}/parentCode`)}}function Ff(e){let t=new Set(e.authz.roles.map(c=>String(c.code))),o=e.authz.authenticatedUserRoleCode===void 0?"":F(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),n=new Map(e.authz.scopeDimensions.map(c=>[String(c.code),{valueType:c.valueType==="uuid"?"uuid":"string",...c.valueSource?.resourceCode?{valueSourceResourceCode:String(c.valueSource.resourceCode)}:{}}])),r=new Set(n.keys()),i=new Map(e.data.resources.map((c,l)=>{let f=Ut(c,`/config/data/resources/${l}`,e.appCode);return[f.code,new Map(f.schema.fields.map(p=>[String(p.code),p]))]}));for(let[c,l]of e.authz.scopeDimensions.entries()){let f=`/config/authz/scopeDimensions/${c}`,p=N(l,f);if(R(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],f,!0),p.valueSource===void 0)continue;let m=N(p.valueSource,`${f}/valueSource`);R(m,["kind","resourceCode","labelField","enabledField"],`${f}/valueSource`,!0),m.kind!=="native_resource"&&_("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${f}/valueSource/kind`),p.valueType!=="uuid"&&_("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${f}/valueType`);let A=Q(m.resourceCode,`${f}/valueSource/resourceCode`),I=i.get(A);I||_("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${f}/valueSource/resourceCode`);let O=J(m.labelField,`${f}/valueSource/labelField`);if(["text.short","text.long"].includes(String(I.get(O)?.type||""))||_("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${f}/valueSource/labelField`),m.enabledField!==void 0){let b=J(m.enabledField,`${f}/valueSource/enabledField`);I.get(b)?.type!=="boolean"&&_("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${f}/valueSource/enabledField`)}}let s=new Set,a=new Set;for(let[c,l]of e.authz.scopeSources.entries()){let f=`/config/authz/scopeSources/${c}`,p=N(l,f);R(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],f,!0);let m=F(p.code,`${f}/code`);s.has(m)&&_("NATIVE_SCOPE_SOURCE_DUPLICATE",`${f}/code`),s.add(m),k(p.name,`${f}/name`,255);let A=Q(p.resourceCode,`${f}/resourceCode`),I=i.get(A);I||_("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${f}/resourceCode`);let O=N(p.subject,`${f}/subject`),b=k(O.type,`${f}/subject/type`,32);R(O,b==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${f}/subject`),["user","role_membership"].includes(b)||_("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${f}/subject/type`);let g=Rn(O.userIdField,I);ci(g)||_("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${f}/subject/userIdField`),b==="role_membership"&&!t.has(String(O.roleCode))&&_("NATIVE_ROLE_REFERENCE_MISSING",`${f}/subject/roleCode`);let y=new Set;for(let[h,u]of D(p.grants,`${f}/grants`,100).entries()){let E=`${f}/grants/${h}`,w=N(u,E);R(w,["dimensionCode","valueField","parentValueField"],E,!0);let S=F(w.dimensionCode,`${E}/dimensionCode`);(!r.has(S)||y.has(S))&&_("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${E}/dimensionCode`),y.add(S),p.failureMode==="last_known_good"&&a.add(S);for(let T of["valueField","parentValueField"]){if(w[T]===void 0)continue;let C=Rn(w[T],I);Ea(C,n.get(S),i)||_("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${E}/${T}`)}}y.size===0&&_("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${f}/grants`),["strict","last_known_good"].includes(p.failureMode)||_("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${f}/failureMode`);for(let h of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[h]===void 0)continue;let u=J(p[h],`${f}/${h}`);I.has(u)||_("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${f}/${h}`)}}Wf(e,t,i,o);let d=new Set;for(let[c,l]of e.authz.dataPolicies.entries()){let f=`/config/authz/dataPolicies/${c}`,p=N(l,f);R(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],f,!0);let m=F(p.code,`${f}/code`);d.has(m)&&_("NATIVE_DATA_POLICY_DUPLICATE",`${f}/code`),d.add(m);let A=p.readExpression!==void 0,I=V(p.operations||[],`${f}/operations`,4);p.operations!==void 0&&(I.length===0||I.some(u=>!["read","create","update","delete"].includes(u)))&&_("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${f}/operations`),["AND","OR"].includes(p.matchMode)||_("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${f}/matchMode`),A&&p.operations!==void 0&&_("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${f}/operations`);let O=e.data.resources.find(u=>u.dataPolicyCode===m),b=p.resourceCode||O?.code,g=b?i.get(Q(b,`${f}/resourceCode`)):void 0;if(A&&!g&&_("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${f}/resourceCode`),p.publicRead!==void 0){try{let u=e.authz.roles.find(E=>E.code===o);Ma({policy:p,resource:e.data.resources.find(E=>E.code===b),baselineRoleCode:o,baselineCapabilities:u?.capabilities||[],baselineDeniedCapabilities:u?.deniedCapabilities||[],pointer:f})}catch(u){if(!(u instanceof kn))throw u;_(u.code,u.pointer)}(p.unrestrictedRoleCodes||[]).includes(o)||_("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${f}/unrestrictedRoleCodes`)}else o&&(p.unrestrictedRoleCodes||[]).includes(o)&&_("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${f}/unrestrictedRoleCodes`);let y=V(p.unrestrictedRoleCodes||[],`${f}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&y.length===0&&_("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${f}/unrestrictedRoleCodes`);for(let u of y)t.has(u)||_("NATIVE_ROLE_REFERENCE_MISSING",`${f}/unrestrictedRoleCodes`);let h;try{let u=D(p.rules,`${f}/rules`,100).map((E,w)=>({rule:N(E,`${f}/rules/${w}`),pointer:`${f}/rules/${w}`}));u.length===0?(!A||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&_("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",f):p.writeBoundary!==void 0&&_("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${f}/writeBoundary`),h=[...u],A&&(h.push(...an(p.readExpression,`${f}/readExpression`)),ka(p.readExpression,`${f}/readExpression`))}catch(u){throw u instanceof Dn&&_(u.code,u.pointer),u}for(let{rule:u,pointer:E}of h){if(R(u,["parentRead","subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],E,!0),u.parentRead!==void 0){for(let Z of V(u.roleCodes||[],`${E}/roleCodes`,100))t.has(Z)||_("NATIVE_ROLE_REFERENCE_MISSING",`${E}/roleCodes`);continue}let w=J(u.field,`${E}/field`),S=g?.get(w);A&&!S&&_("NATIVE_DATA_POLICY_FIELD_MISSING",`${E}/field`);for(let Z of V(u.roleCodes||[],`${E}/roleCodes`,100))t.has(Z)||_("NATIVE_ROLE_REFERENCE_MISSING",`${E}/roleCodes`);let T=String(u.operator||""),C=u.operand==="db_now",v=["is_null","is_not_null"].includes(T),P=["eq","not_eq","in","not_in"].includes(T),H=!C&&(u.operator!==void 0||u.value!==void 0);if([u.subject==="current_user"?"current_user":"",typeof u.dimensionCode=="string"?"dimension":"",typeof u.relationCode=="string"?"relationship":"",H?"constant":"",C?"db_now":""].filter(Boolean).length!==1&&_("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",E),u.subject!==void 0&&u.subject!=="current_user"&&_("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${E}/subject`),H){if(!P&&!v&&_("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${E}/operator`),["in","not_in"].includes(T)){let Z=D(u.value,`${E}/value`,100).map((Se,Ee)=>k(Se,`${E}/value/${Ee}`,2048));(Z.length===0||new Set(Z).size!==Z.length)&&_("NATIVE_DATA_POLICY_VALUE_INVALID",`${E}/value`)}else["eq","not_eq"].includes(T)?k(u.value,`${E}/value`,2048):(u.value!==void 0||u.operand!==void 0)&&_("NATIVE_DATA_POLICY_VALUE_INVALID",`${E}/value`);for(let Z of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])u[Z]!==void 0&&_("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${E}/${Z}`)}if(C){(!["lt","lte","gt","gte"].includes(T)||u.value!==void 0||S?.type!=="datetime")&&_("NATIVE_DATA_POLICY_DB_NOW_INVALID",E);for(let Z of["operation","valuePath","emptyMatchesAll","resourceCode","value"])u[Z]!==void 0&&_("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${E}/${Z}`)}u.dimensionCode&&!r.has(u.dimensionCode)&&_("NATIVE_SCOPE_DIMENSION_MISSING",`${E}/dimensionCode`),a.has(String(u.dimensionCode||""))&&u.operation!=="read"&&_("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${E}/operation`)}}try{$a(e.data.resources,e.authz.dataPolicies)}catch(c){throw c instanceof Te&&_(c.code,c.pointer),c}for(let[c,l]of e.data.resources.entries()){let f=N(l,`/config/data/resources/${c}`);f.dataPolicyCode&&!d.has(f.dataPolicyCode)&&_("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${c}/dataPolicyCode`)}}function Vf(e){try{Xs(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,o)=>Ms(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 We||t instanceof $t)&&_(t.code,t.pointer),t}}function Wf(e,t,o,n){let r=new Set;for(let[i,s]of e.authz.roleMembershipSources.entries()){let a=`/config/authz/roleMembershipSources/${i}`,d=N(s,a);R(d,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],a,!0);let c=F(d.code,`${a}/code`);c.length>100&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${a}/code`),r.has(c)&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${a}/code`),r.add(c),k(d.name,`${a}/name`,255);let l=jd(d.resourceCode,`${a}/resourceCode`,o);Ud(d.userIdField,`${a}/userIdField`,l),t.has(String(d.roleCode||""))||_("NATIVE_ROLE_REFERENCE_MISSING",`${a}/roleCode`),n&&d.roleCode===n&&_("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${a}/roleCode`),Md(d,a,l)}for(let[i,s]of e.authz.relationshipGrantSources.entries()){let a=`/config/authz/relationshipGrantSources/${i}`,d=N(s,a);R(d,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],a,!0);let c=F(d.code,`${a}/code`);c.length>100&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${a}/code`),r.has(c)&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${a}/code`),r.add(c),k(d.name,`${a}/name`,255);let l=jd(d.resourceCode,`${a}/resourceCode`,o),f=N(d.subject,`${a}/subject`),p=k(f.type,`${a}/subject/type`,32);R(f,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${a}/subject`),["user","role_membership"].includes(p)||_("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${a}/subject/type`),Ud(f.userIdField,`${a}/subject/userIdField`,l),p==="role_membership"&&!t.has(String(f.roleCode||""))&&_("NATIVE_ROLE_REFERENCE_MISSING",`${a}/subject/roleCode`),F(d.relationCode,`${a}/relationCode`);let m=Q(d.targetResourceCode,`${a}/targetResourceCode`);o.has(m)||_("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${a}/targetResourceCode`);let A=Rn(d.resourceIdField,l),I=A?.field.type==="resource-ref.single"&&A.valuePath==="value"&&A.field.source?.resourceCode===m;(d.resourceIdField==="id"?m!==String(d.resourceCode):!I)&&_("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${a}/resourceIdField`);let O=V(d.operations,`${a}/operations`,20);(O.length===0||O.some(b=>b.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(b)))&&_("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${a}/operations`),Md(d,a,l)}}function jd(e,t,o){let n=Q(e,t),r=o.get(n);return r||_("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),r}function Ud(e,t,o){let n=Rn(e,o);ci(n)||_("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Md(e,t,o){if(e.failureMode!=="strict"&&_("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let n=J(e.enabledField,`${t}/enabledField`);o.get(n)?.type!=="boolean"&&_("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let n of["effectiveFromField","effectiveToField"]){if(e[n]===void 0)continue;let r=J(e[n],`${t}/${n}`);["date","datetime"].includes(String(o.get(r)?.type))||_("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${n}`)}}function xf(e){let t=new Set,o=new Set;e.forEach((n,r)=>{let i=`/config/backend/secrets/${r}`,s=N(n,i);R(s,["name","env","description","required","exposure"],i,!0);let a=k(s.name,`${i}/name`,128),d=k(s.env,`${i}/env`,128);Wu.test(a)||_("NATIVE_SECRET_NAME_INVALID",`${i}/name`),(!xu.test(d)||d.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(d))&&_("NATIVE_SECRET_ENV_INVALID",`${i}/env`),t.has(a)&&_("NATIVE_SECRET_NAME_DUPLICATE",`${i}/name`),o.has(d)&&_("NATIVE_SECRET_ENV_DUPLICATE",`${i}/env`),t.add(a),o.add(d),x(s.exposure,"active_only",`${i}/exposure`),s.required!==void 0&&_n(s.required,`${i}/required`),s.description!==void 0&&Qi(s.description,`${i}/description`,2e3)})}function jf(e){let t=new Set,o=new Map,n=new Map(e.data.resources.map(A=>[String(A.code),A])),r=new Map(e.frontend.routes.map((A,I)=>{let O=N(A,`/config/frontend/routes/${I}`);return[F(O.code,`/config/frontend/routes/${I}/code`),O]}));for(let[A,I]of e.workflows.definitions.entries()){let O=`/config/workflows/definitions/${A}`,b=N(I,O);if(R(b,["version","definition","launch"],O,["detailRouteCode"]),rc(b.launch,`${O}/launch`),b.detailRouteCode!==void 0){let v=ic(b.detailRouteCode,`${O}/detailRouteCode`);for(let[P,H,ne]of[["desktop",v.desktop,["admin","user"]],["mobile",v.mobile,["user"]]]){let Z=`${O}/detailRouteCode/${P}`,Se=r.get(H);Se||_("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",Z),ne.some(fe=>fe===Se.surface)||_("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",Z);let Ee=Je(Se.path,Z),Ie=[...Ee.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(fe=>fe[1]);(Ee.includes("*")||Ie.length!==1||Ie[0]!=="instanceId")&&_("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",Z)}}let g=N(b.definition,`${O}/definition`),y=`${g.code}:${gn(b.version,`${O}/version`)}`;t.has(y)&&_("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",O),t.add(y),Mf(g,`${O}/definition`);let h=Pi(g);h.length&&_(h[0],`${O}/definition/launchPreflight`);let u=gd(g);u.length&&_(u[0],`${O}/definition/approvedDelegation`);let E=fd(g,e.backend.operations);E.length&&_(E[0],`${O}/definition/commandHandlers`),Uf(g.subject,n,`${O}/definition/subject`);let w=g.commandHandlers?.resubmit?.derivedSubjectFields||[],S=n.get(g.subject.resourceCode);for(let v of w){let P=S?.schema.fields.find(H=>H.code===v);(!P||P.system===!0||S?.surface?.fields?.[v]?.system===!0)&&_("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID",`${O}/definition/commandHandlers/resubmit/derivedSubjectFields`)}let T=zo(g,new Map((n.get(g.subject.resourceCode)?.schema.fields||[]).map(v=>[v.code,{...n.get(g.subject.resourceCode)?.surface?.fields?.[v.code],...v,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(v.code)}])),new Map([...n].map(([v,P])=>[v,new Map(P.schema.fields.map(H=>[H.code,{...P.surface?.fields?.[H.code],...H,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(H.code)}]))])),fo(n.get(g.subject.resourceCode)?.schema||{}));T.length&&_(T[0],`${O}/definition/taskPages`);let C=Qa(g,{appCode:e.appCode,capabilities:e.authz.capabilities.map(v=>v.code),fields:new Map((n.get(g.subject.resourceCode)?.schema.fields||[]).map(v=>[v.code,v]))});C.length&&_("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${O}/definition/instanceCommands`,{errors:C}),g.title===g.code&&_("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${O}/definition/title`),o.set(y,g)}let i=new Set,s=new Map;for(let[A,I]of e.workflows.bindings.entries()){let O=N(I,`/config/workflows/bindings/${A}`),b=N(O.binding,`/config/workflows/bindings/${A}/binding`),g=`${b.workflowCode}:${gn(O.version,`/config/workflows/bindings/${A}/version`)}`;i.has(g)&&_("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${A}`),i.add(g),Bf(b,`/config/workflows/bindings/${A}/binding`),s.set(g,b)}let a=new Set(e.authz.roles.map(A=>A.code));for(let[A,I]of e.workflows.bindings.entries())for(let[O,b]of Object.entries(I.binding.bindings))if(b.provider==="conditional")for(let g of ae(b)){let y=[...Yn(g),...Object.values(g.routing?.sources||{}).map(h=>h.roleCode)];for(let h of y)a.has(h)||_("WORKFLOW_CONDITIONAL_ROLE_UNDECLARED",`/config/workflows/bindings/${A}/binding/bindings/${O}`)}let d=new Set,c=new Map;for(let[A,I]of e.workflows.activations.entries()){let O=`/config/workflows/activations/${A}`,b=N(I,O);R(b,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],O,["environmentKey","sourceBase"]);let g=F(b.workflowCode,`${O}/workflowCode`);if(d.has(g)&&_("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",O),d.add(g),b.sourceBase!==void 0){let T=N(b.sourceBase,`${O}/sourceBase`);R(T,["definitionDigest","bindingDigest"],`${O}/sourceBase`);for(let C of["definitionDigest","bindingDigest"])/^(sha256:)?[a-f0-9]{64}$/.test(String(T[C]||""))||_("NATIVE_WORKFLOW_SOURCE_BASE_INVALID",`${O}/sourceBase/${C}`)}let y=`${g}:${gn(b.definitionVersion,`${O}/definitionVersion`)}`,h=`${g}:${gn(b.bindingVersion,`${O}/bindingVersion`)}`;t.has(y)||_("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${O}/definitionVersion`),i.has(h)||_("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${O}/bindingVersion`);let u=o.get(y),E=s.get(h),w=Pi(u,E);w.length&&_(w[0],O);let S=ki(u,E);S.length&&_(S[0],O),(!["finish-pinned","cancel-on-deactivate"].includes(b.acceptedCommandDeactivationPolicy)||b.acceptedCommandDeactivationPolicy!==u.acceptedCommandDeactivationPolicy)&&_("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${O}/acceptedCommandDeactivationPolicy`),Kf(u,E,`/config/workflows/activations/${A}`);try{let T=n.get(u.subject.resourceCode)?.schema.fields||[];Bs(u,E,new Map(T.map(C=>[C.code,C])),`${O}/bindings`,new Map([...n].map(([C,v])=>[C,new Map(v.schema.fields.map(P=>[P.code,P]))])))}catch(T){throw T instanceof $t&&_(T.code,T.pointer),T}c.set(g,E)}let l=Ts([...c.values()].map(A=>co(A)));l.length&&_(l[0],"/config/workflows/activations");let f=new Set;e.workflows.providers.forEach((A,I)=>{let O=`/config/workflows/providers/${I}`,b=N(A,O);R(b,["code","endpointPath","timeoutMs"],O,!0);let g=F(b.code,`${O}/code`);f.has(g)&&_("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${O}/code`),f.add(g),Je(b.endpointPath,`${O}/endpointPath`),b.timeoutMs!==void 0&&Ae(b.timeoutMs,`${O}/timeoutMs`,100,1e4)});for(let[A,I]of c.entries())for(let[O,b]of Object.entries(N(I.bindings,"/config/workflows/bindings/*/binding/bindings"))){let g=N(b,`/config/workflows/${A}/bindings/${O}`);g.provider==="application_provider"&&!f.has(g.providerCode)&&_("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${A}/bindings/${O}/providerCode`)}let p=new Set(e.authz.roles.map(A=>A.code)),m=new Set;e.workflows.editableParameters.forEach((A,I)=>{let O=`/config/workflows/editableParameters/${I}`,b=N(A,O);R(b,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],O,!0);let g=F(b.code,`${O}/code`);m.has(g)&&_("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${O}/code`),m.add(g);let y=or(b.workflowCode,`${O}/workflowCode`),h=Qo(b.bindingKey,`${O}/bindingKey`),u=c.get(y);(!u||!N(u.bindings,`${O}/bindingKey`)[h])&&_("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${O}/bindingKey`),k(b.label,`${O}/label`,255),["role_code","user_ids","provider_code"].includes(b.valueType)||_("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${O}/valueType`);for(let E of V(b.allowedRoleCodes||[],`${O}/allowedRoleCodes`,100))p.has(E)||_("NATIVE_ROLE_REFERENCE_MISSING",`${O}/allowedRoleCodes`);for(let E of V(b.allowedProviderCodes||[],`${O}/allowedProviderCodes`,100))f.has(E)||_("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${O}/allowedProviderCodes`);b.required!==void 0&&_n(b.required,`${O}/required`),b.maxItems!==void 0&&Ae(b.maxItems,`${O}/maxItems`,1,200)})}function Uf(e,t,o){let n=N(e,o);R(n,["resourceCode","factProjection"],o,["summaryFields"]);let r=Q(n.resourceCode,`${o}/resourceCode`),i=t.get(r);i||_("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${o}/resourceCode`);let s=new Set(D(N(i.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((c,l)=>J(N(c,`${o}/resourceCode/${l}`).code,`${o}/resourceCode/${l}`))),a=N(n.factProjection,`${o}/factProjection`),d=Object.entries(a);(d.length<1||d.length>64)&&_("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${o}/factProjection`);for(let[c,l]of d){Mu.test(c)||_("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${o}/factProjection/${c}`);let f=J(l,`${o}/factProjection/${c}`);s.has(f)||_("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${o}/factProjection/${c}`)}if(n.summaryFields!==void 0){let c=V(n.summaryFields,`${o}/summaryFields`,Bu).map((A,I)=>J(A,`${o}/summaryFields/${I}`)),l=t.get(r),f=l.surface&&typeof l.surface=="object"&&!Array.isArray(l.surface)?l.surface:{},p=f.fields&&typeof f.fields=="object"&&!Array.isArray(f.fields)?f.fields:{},m=new Map(D(N(l.schema,`${o}/resourceCode`).fields,`${o}/resourceCode`,500).map((A,I)=>{let O=N(A,`${o}/resourceCode/${I}`);return[String(O.code),O]}));for(let[A,I]of c.entries()){let O=m.get(I),b=p[I],g=String(O?.type||""),y=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(I)||!qu.has(g)||g==="text.long"&&typeof y=="number"&&Number.isFinite(y)&&y>Ku)&&_("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${o}/summaryFields/${A}`)}}}function Mf(e,t){R(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["authoring","organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),x(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),or(e.code,`${t}/code`),k(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||_("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let o=N(e.nodes,`${t}/nodes`),n=Object.keys(o);(n.length===0||n.length>200)&&_("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let r=k(e.startAt,`${t}/startAt`,128),i=Ls(e);i.length&&_(i[0],`${t}/authoring/peopleSources`);let s=ed(e);s.length&&_(s[0],`${t}/readability`);let a=ki(e);a.length&&_(a[0],`${t}/nodes`);let d=Li(e);d.length&&_(d[0],`${t}/nodes`);let c=Vn(e);c.length&&_(c[0],`${t}/nodes`);let l=cd(e);l.length&&_(l[0],`${t}/nodes`);let f=ud(e);f.length&&_(f[0],`${t}/rejectionNotification`);let p=Si(e);p.length&&_(p[0],`${t}/nodes`);let m=zo(e);m.length&&_(m[0],`${t}/taskPages`);let A=ko(e);A.length&&_(A[0],`${t}/nodes`);let I=Do(e);I.length&&_(I[0],`${t}/nodes`);let O=Po(e);O.length&&_(O[0],`${t}/nodes`);let b=vo(e);b.length&&_(b[0],`${t}/nodes`);let g=eo(e);g.length&&_(g[0],`${t}/nodes`),o[r]||_("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let y=new Map;for(let[w,S]of Object.entries(o)){let T=`${t}/nodes/${w}`,C=N(S,T);x(C.id,w,`${T}/id`),["approval","handle","condition","end","cc","action","correction","parallel","join"].includes(C.kind)||_("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${T}/kind`);let v=[];if(C.kind==="approval"||C.kind==="handle"){k(C.title,`${T}/title`,255),Qo(C.binding,`${T}/binding`),["single","any","all","sequence"].includes(C.mode)||_("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${T}/mode`),C.kind==="handle"?v.push(k(C.next,`${T}/next`,128)):v.push(k(C.onApprove,`${T}/onApprove`,128),k(C.onReject,`${T}/onReject`,128));for(let P of V(C.returnTargets||[],`${T}/returnTargets`,200))o[P]||_("NATIVE_WORKFLOW_TARGET_MISSING",`${T}/returnTargets`);for(let P of V(C.allowedOperations||[],`${T}/allowedOperations`,20))Gu.has(P)||_("NATIVE_WORKFLOW_OPERATION_INVALID",`${T}/allowedOperations`)}else if(C.kind==="correction"){let P=_d(e);P.length&&_(P[0],T)}else if(C.kind==="action")v.push(k(C.next,`${T}/next`,128));else if(C.kind==="cc")k(C.title,`${T}/title`,255),Qo(C.binding,`${T}/binding`),v.push(k(C.next,`${T}/next`,128));else if(C.kind==="parallel"){k(C.title,`${T}/title`,255),v.push(k(C.join,`${T}/join`,128));for(let[P,H]of D(C.branches,`${T}/branches`,8).entries()){let ne=N(H,`${T}/branches/${P}`);ne.when!==void 0&&mn(ne.when,`${T}/branches/${P}/when`,0),v.push(k(ne.target,`${T}/branches/${P}/target`,128))}}else if(C.kind==="join")k(C.title,`${T}/title`,255),v.push(k(C.next,`${T}/next`,128));else if(C.kind==="condition"){let P=D(C.branches,`${T}/branches`,100);P.length===0&&_("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${T}/branches`),P.forEach((H,ne)=>{let Z=N(H,`${T}/branches/${ne}`);mn(Z.when,`${T}/branches/${ne}/when`,0),v.push(k(Z.target,`${T}/branches/${ne}/target`,128))}),v.push(k(C.otherwise,`${T}/otherwise`,128))}else k(C.title,`${T}/title`,255),k(C.outcome,`${T}/outcome`,128);for(let P of v)o[P]||_("NATIVE_WORKFLOW_TARGET_MISSING",T);y.set(w,v)}let h=new Set,u=new Set,E=w=>{if(u.has(w)&&_("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${w}`),!h.has(w)){h.add(w),u.add(w);for(let S of y.get(w)||[])E(S);u.delete(w)}};E(r);for(let w of[...h]){let S=o[w];if(S?.kind==="approval"||S?.kind==="handle")for(let T of ot(S))o[T]?.kind==="correction"&&h.add(T)}h.size!==n.length&&_("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function mn(e,t,o){o>20&&_("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let n=N(e,t),r=k(n.op,`${t}/op`,16);if(r!=="literal"){if(r==="path"){let i=k(n.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(i)||i.split(".").some(s=>["__proto__","constructor","prototype"].includes(s)))&&_("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(r)){mn(n.left,`${t}/left`,o+1),mn(n.right,`${t}/right`,o+1);return}if(["and","or"].includes(r)){let i=D(n.values,`${t}/values`,100);i.length===0&&_("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),i.forEach((s,a)=>mn(s,`${t}/values/${a}`,o+1));return}if(["not","exists"].includes(r)){mn(n.value,`${t}/value`,o+1);return}_("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Bf(e,t){x(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),or(e.workflowCode,`${t}/workflowCode`);let o=N(e.bindings,`${t}/bindings`);Object.keys(o).length>200&&_("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[n,r]of Object.entries(o)){Qo(n,`${t}/bindings/${n}`);let i=N(r,`${t}/bindings/${n}`);if(i.provider==="conditional"){let l=ke(i);l.length&&_(l[0],`${t}/bindings/${n}`);continue}let s=Ht(i);s.length&&_(s[0],`${t}/bindings/${n}`);let a=Xn(i);a.length&&_(a[0],`${t}/bindings/${n}/selectedInputPath`);let d=qt(i);d.length&&_(d[0],`${t}/bindings/${n}/roleCodes`);let c=k(i.provider,`${t}/bindings/${n}/provider`,64);if(["fixed_users","initiator","input_users","form_field_users","department_supervisor","supervisor_chain","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(c)||_("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${n}/provider`),c==="fixed_users"&&(Array.isArray(i.users)||_("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${n}/users`),D(i.users,`${t}/bindings/${n}/users`,200)),["input_users","form_field_users"].includes(c)&&k(i.inputPath,`${t}/bindings/${n}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(c)&&i.roleCodes===void 0&&F(i.roleCode,`${t}/bindings/${n}/roleCode`),c==="department_supervisor"&&k(i.departmentIdFrom,`${t}/bindings/${n}/departmentIdFrom`,255),c==="application_provider"&&F(i.providerCode,`${t}/bindings/${n}/providerCode`),i.routing!==void 0){let l=Yt(i.routing);l.length&&_(l[0],`${t}/bindings/${n}/routing`)}}}function Kf(e,t,o){let n=Xt(e,t);n.length&&_(n[0],o);let r=At(e,t);r.length&&_(r[0],o),x(t.workflowCode,e.code,`${o}/workflowCode`);let i=N(t.bindings,`${o}/bindings`);for(let[c,l]of Object.entries(i))l.provider==="fixed_users"&&!l.users.length&&!ad(e,c)&&_("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${o}/bindings/${c}/users`);let s=Li(e,t);s.length&&_(s[0],o);let a=Si(e,t);a.length&&_(a[0],o);let d=eo(e,t);d.length&&_(d[0],o);for(let[c,l]of Object.entries(N(e.nodes,`${o}/nodes`))){let f=N(l,`${o}/nodes/${c}`);["approval","handle","cc"].includes(f.kind)&&!i[f.binding]&&_("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${o}/nodes/${c}/binding`)}}function qf(e,t,o){let n=N(t.routeManifest,"/contracts/routeManifest"),r=N(e.routeManifest,"/contracts/routeManifest"),i=new Map;for(let l of D(o.data?.resources,"/config/data/resources",q.resources)){let f=N(l,"/config/data/resources");i.set(String(f.code||""),f)}let s=new Set(D(r.routes,"/contracts/routeManifest/routes",q.routes).map(l=>String(N(l,"/contracts/routeManifest/routes").code||""))),a=[];for(let l of D(n.routes,"/contracts/routeManifest/routes",q.routes)){let f=N(l,"/contracts/routeManifest/routes"),p=String(f.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let m=String(f.resourceCode||""),A=i.get(m);A||_("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let O=`user.${m}.${p==="resource-records"?"records":"submit"}`;x(String(f.code||""),O,"/contracts/routeManifest/routes/code");let b=p==="resource-records"?"read":"create",g=String(N(A.capabilities,"/config/data/resources/capabilities")[b]||"");for(let y of["desktop","mobile"]){let h=N(f[y],`/contracts/routeManifest/routes/${y}`),u=y==="mobile"?"/m/my/":"/my/",E=p==="resource-records"?`${u}${m}`:`${u}${m}/submit`;x(String(h.path||""),E,`/contracts/routeManifest/routes/${y}/path`),x(String(h.capability||""),g,`/contracts/routeManifest/routes/${y}/capability`),x(String(h.routeCode||""),`${O}.${y}`,`/contracts/routeManifest/routes/${y}/routeCode`)}(s.has(O)||a.some(y=>String(y.code)===O))&&_("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),a.push(f)}if(!a.length)return;r.routes=D([...r.routes,...a],"/contracts/routeManifest/routes",1e3).sort((l,f)=>Ce(String(N(l,"x").code||""),String(N(f,"x").code||"")));let d=String(N(n.rootEntry,"x").code||"");if(a.find(l=>String(l.code)===d&&l.kind==="resource-records")){let l=N(n.rootEntry,"x");r.rootEntry={code:d,desktop:String(l.desktop||""),mobile:String(l.mobile||"")}}r.digest=ee({schemaVersion:r.schemaVersion,appCode:r.appCode,devicePolicy:r.devicePolicy,rootEntry:r.rootEntry,authentication:r.authentication,routes:r.routes})}function Ut(e,t,o){let n=N(e,t);R(n,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","organization","fieldPolicies"],t,!0),x(n.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),x(n.appCode,o,`${t}/appCode`);let r=Q(n.code,`${t}/code`),i=k(n.name,`${t}/name`,255),s=N(n.schema,`${t}/schema`);R(s,["fields","ownedRowLimit"],`${t}/schema`,!0),s.ownedRowLimit!==void 0&&!On(s.ownedRowLimit)&&_("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${t}/schema/ownedRowLimit`);let a,d,c,l;try{c=si(n.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),a=bn(s.fields,`${t}/schema/fields`),l=Ka(n.uniqueKeys,a,`${t}/uniqueKeys`),d=Zs(n.invariants,a,`${t}/invariants`),ti(n.surface,a,`${t}/surface`)}catch(A){throw(A instanceof We||A instanceof $t||A instanceof rn||A instanceof vn)&&_(A.code,A.pointer),A}if(n.recordComments!==void 0){let A=N(n.recordComments,`${t}/recordComments`);R(A,["read","create"],`${t}/recordComments`);for(let I of["read","create"]){let O=A[I];(!Array.isArray(O)||O.length>20||O.some(b=>typeof b!="string"||!b.trim())||new Set(O).size!==O.length)&&_("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${I}`)}}if(n.recordDeletion!==void 0){let A=N(n.recordDeletion,`${t}/recordDeletion`);R(A,["delete"],`${t}/recordDeletion`);let I=A.delete;(!Array.isArray(I)||I.length>20||I.some(O=>typeof O!="string"||!O.trim())||new Set(I).size!==I.length)&&_("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(n.recordPrint!==void 0){let A=N(n.recordPrint,`${t}/recordPrint`);R(A,["read"],`${t}/recordPrint`);let I=A.read;(!Array.isArray(I)||I.length>20||I.some(O=>typeof O!="string"||!O.trim())||new Set(I).size!==I.length)&&_("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(n.workflowHistory!==void 0){let A=N(n.workflowHistory,`${t}/workflowHistory`);R(A,["read"],`${t}/workflowHistory`);let I=A.read;(!Array.isArray(I)||I.length>20||I.some(O=>typeof O!="string"||!O.trim())||new Set(I).size!==I.length)&&_("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let f=new Set(a.map(A=>A.code)),p=N(n.capabilities,`${t}/capabilities`);R(p,["read","create","update","delete"],`${t}/capabilities`);let m=N(n.fieldPolicies,`${t}/fieldPolicies`);for(let[A,I]of Object.entries(m)){!f.has(A)&&!Vt(A)&&_("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${A}`);let O=`${t}/fieldPolicies/${A}`,b=N(I,O);Vt(A)&&(R(b,["read"],O,!0),(!Array.isArray(b.read)||b.read.length>20||b.read.some(g=>typeof g!="string"||!g.trim())||new Set(b.read).size!==b.read.length)&&_("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${O}/read`)),R(b,["read","create","update","mask"],O,!0),b.mask!==void 0&&!["omit","null"].includes(b.mask)&&_("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${O}/mask`)}return{...n,code:r,name:i,schema:{fields:a,...s.ownedRowLimit!==void 0?{ownedRowLimit:s.ownedRowLimit}:{}},...n.invariants===void 0?{}:{invariants:d},...c?{decimalReservationLifecycle:c}:{},...l!==void 0?{uniqueKeys:l}:{},capabilities:p,fieldPolicies:m}}function sc(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 Bd(e,t,o,n){let r=e.toString("utf8"),i;try{i=JSON.parse(r)}catch{_(o,t)}let s=N(i,t);return re(s)!==r&&_(n,t),s}function Yo(e,t,o){let n=0,r=(i,s,a)=>{if(n+=1,n>o&&_("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",s),a>Yu&&_("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",s),typeof i=="string"){Buffer.byteLength(i)>qi&&_("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",s);return}if(Array.isArray(i)){i.forEach((d,c)=>r(d,`${s}/${c}`,a+1));return}if(!(!i||typeof i!="object"))for(let[d,c]of Object.entries(i))["__proto__","prototype","constructor"].includes(d)&&_("NATIVE_ARTIFACT_DANGEROUS_KEY",`${s}/${d}`),zf(d)&&_("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${s}/${d}`),r(c,`${s}/${d}`,a+1)};r(e,t,0)}function zf(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function pn(e){return{value:e,digest:ee(e)}}function Kd(e,t,o,n){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&_("NATIVE_ARTIFACT_BYTES_REQUIRED",o);let r=Buffer.isBuffer(e)?e:Buffer.from(e);return r.byteLength===0&&_("NATIVE_ARTIFACT_EMPTY",o),r.byteLength>t&&_(n,o),r}function qd(e,t,o,n){let r=er.createHash("sha256").update(e).digest("hex");er.timingSafeEqual(Buffer.from(r),Buffer.from(t))||_(n,o)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&_("NATIVE_OBJECT_REQUIRED",t),e}function D(e,t,o){return Array.isArray(e)||_("NATIVE_ARRAY_REQUIRED",t),e.length>o&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function V(e,t,o){let n=D(e,t,o).map((r,i)=>k(r,`${t}/${i}`,255));return new Set(n).size!==n.length&&_("NATIVE_ARRAY_DUPLICATE",t),n}function k(e,t,o){return(typeof e!="string"||e.length===0||e.length>o)&&_("NATIVE_STRING_INVALID",t),e}function Qi(e,t,o){return(typeof e!="string"||e.length>o)&&_("NATIVE_STRING_INVALID",t),e}function F(e,t){let o=k(e,t,128);return Pu.test(o)||_("NATIVE_CODE_INVALID",t),o}function Q(e,t){let o=k(e,t,64);return Fu.test(o)||_("NATIVE_RESOURCE_CODE_INVALID",t),o}function J(e,t){let o=k(e,t,63);return Vu.test(o)||_("NATIVE_FIELD_CODE_INVALID",t),o}function or(e,t){let o=k(e,t,128);return ju.test(o)||_("NATIVE_WORKFLOW_CODE_INVALID",t),o}function Qo(e,t){let o=k(e,t,128);return Uu.test(o)||_("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),o}function Pe(e,t,o){let n=k(e,t,255);return vu.test(n)||_("NATIVE_CAPABILITY_CODE_INVALID",t),!n.startsWith(`app:${o}:`)&&!sc(o).some(r=>r.code===n)&&_("NATIVE_CAPABILITY_APP_MISMATCH",t),n}function Je(e,t){let o=k(e,t,2048);return(!o.startsWith("/")||o.startsWith("//")||o.includes("..")||o.includes("?")||o.includes("#"))&&_("NATIVE_ABSOLUTE_PATH_INVALID",t),o}function gn(e,t){return(!Number.isInteger(e)||Number(e)<1)&&_("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function Ae(e,t,o,n){return(!Number.isInteger(e)||Number(e)<o||Number(e)>n)&&_("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function _n(e,t){return typeof e!="boolean"&&_("NATIVE_BOOLEAN_REQUIRED",t),e}function Hi(e,t){let o=k(e,t,64).toLowerCase();return ku.test(o)||_("NATIVE_DIGEST_INVALID",t),o}function x(e,t,o){e!==t&&_("NATIVE_VALUE_MISMATCH",o)}function R(e,t,o,n=!1){let r=new Set([...t,...Array.isArray(n)?n:[]]);for(let i of Object.keys(e))r.has(i)||_("NATIVE_PROPERTY_UNKNOWN",`${o}/${i}`);if(n!==!0)for(let i of t)Object.prototype.hasOwnProperty.call(e,i)||_("NATIVE_PROPERTY_REQUIRED",`${o}/${i}`)}function ue(e,t){return[...e].sort((o,n)=>Ce(t(o),t(n)))}function K(e){return[...new Set(e)].sort(Ce)}function zd(e){return[...new Set(e)].sort((t,o)=>t-o)}function Ce(e,t){return e===t?0:e<t?-1:1}function ac(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>ac(t))),e}function Yi(e,t,o){if(Ki(e,t))return o;if(Array.isArray(e)&&Array.isArray(t)){let n=Math.max(e.length,t.length);for(let r=0;r<n;r+=1)if(!Ki(e[r],t[r]))return Yi(e[r],t[r],`${o}/${r}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let n=K([...Object.keys(e),...Object.keys(t)]);for(let r of n){let i=e[r],s=t[r];if(!Ki(i,s))return Yi(i,s,`${o}/${r}`)}}return o}function Ki(e,t){return e===void 0||t===void 0?e===t:re(e)===re(t)}function _(e,t,o={}){throw new Gi(e,t,o)}var kE="openxiangda.workflow-step-data-command/v1",Gf="openxiangda.workflow-step-data-resolution/v1";function LE(e,t,o=!1){let n=a=>!!a&&typeof a=="object"&&!Array.isArray(a),r=a=>typeof a=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(a),i=()=>{throw new Error("WORKFLOW_STEP_DATA_RESPONSE_INVALID")};if(!n(e)||e.schemaVersion!==Gf||e.executionId!==t||Object.keys(e).some(a=>!["schemaVersion","executionId","outcome","transaction"].includes(a)))return i();if(e.outcome==="not_observed"&&!Object.hasOwn(e,"transaction")&&!o)return e;let s=e.transaction;if(e.outcome!=="committed"||!n(s)||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==`workflow-step:${t}`||typeof s.replayed!="boolean"||!Array.isArray(s.items)||s.items.length<1||s.items.length>Ks||s.evaluatedAt!==void 0&&(typeof s.evaluatedAt!="string"||!Number.isFinite(Date.parse(s.evaluatedAt))))return i();for(let[a,d]of s.items.entries()){if(!n(d)||d.index!==a)return i();if(d.operation==="emitEvent"){if(typeof d.eventType!="string"||!d.eventType||!r(d.eventId))return i()}else if(!["create","update","delete","increment"].includes(d.operation)||typeof d.resourceCode!="string"||!d.resourceCode||!r(d.id)||!Number.isSafeInteger(d.revision)||d.revision<1)return i()}return e}var PE=50,$E=131072,es=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 FE(e){let t=f=>{throw new es(f)},o=(f,p)=>((!f||typeof f!="object"||Array.isArray(f))&&t(p),f),n=(f,p,m)=>{for(let A of Object.keys(f))p.includes(A)||t(`${m}/${A}`)},r=(f,p,m)=>((typeof f!="string"||!f.trim()||f.length>p)&&t(m),f),i=(f,p)=>{let m=r(f,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(m)||t(p),m.toLowerCase()},s=o(e,""),a;try{a=new TextEncoder().encode(JSON.stringify(s)).byteLength}catch{t("")}a>131072&&t(""),n(s,["schemaVersion","environmentKey","items"],""),s.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),s.environmentKey!==void 0&&!["preproduction","production"].includes(String(s.environmentKey))&&t("/environmentKey"),(!Array.isArray(s.items)||s.items.length<1||s.items.length>50)&&t("/items");let d=new Set,c=new Set,l;for(let[f,p]of s.items.entries()){let m=`/items/${f}`,A=o(p,m);["create","update","revoke"].includes(String(A.operation))||t(`${m}/operation`),l??=A.operation,l!==A.operation&&t(`${m}/operation`),n(A,["operation","operationId","reason",...l==="create"?["userId","roleCode","organizationId"]:["membershipId","expectedRevision"],...l!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],m);let I=i(A.operationId,`${m}/operationId`);d.has(I)&&t(`${m}/operationId`),d.add(I),r(A.reason,1e3,`${m}/reason`);let O;if(l==="create"){let b=r(A.userId,255,`${m}/userId`),g=r(A.roleCode,128,`${m}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(g)||t(`${m}/roleCode`);let y=A.organizationId===void 0?null:i(A.organizationId,`${m}/organizationId`);O=JSON.stringify([b,g,y])}else O=i(A.membershipId,`${m}/membershipId`),(!Number.isSafeInteger(A.expectedRevision)||Number(A.expectedRevision)<1)&&t(`${m}/expectedRevision`);c.has(O)&&t(m),c.add(O),A.scopeGrants!==void 0&&(!Array.isArray(A.scopeGrants)||A.scopeGrants.length>100)&&t(`${m}/scopeGrants`);for(let b of["validFrom","validTo"])A[b]!==void 0&&A[b]!==null&&r(A[b],64,`${m}/${b}`)}}var uc="openxiangda.workflow-delegation-administration/v2",fc="openxiangda.workflow-delegation-mutation/v2",dc="openxiangda.workflow-delegation-preview/v2";var Kn={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},$e={type:"string",minLength:1,maxLength:255},Mt={type:"string",format:"date-time"},An={type:"integer",minimum:1},Jf={anyOf:[Mt,{type:"null"}]},ts={anyOf:[$e,{type:"null"}]},pc={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},rr={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}$"},mc={const:"future-assignments-only"},ns={schemaVersion:{const:uc},id:Kn,appCode:$e,environmentKey:$e,workflowCode:ts,nodeId:pc,delegatorUserId:$e,delegateUserId:$e,delegatorRoleSubjectKey:rr,delegateRoleSubjectKey:rr,validFrom:Mt,validTo:Mt,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:$e,createdAt:Mt,revokedAt:Jf,revision:An,roleCode:$e,roleName:$e,delegatorDisplayName:$e,delegateDisplayName:$e,delegatorRoleSubjectRevision:An,delegateRoleSubjectRevision:An,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:Mt,issues:{type:"array",maxItems:20,uniqueItems:!0,items:$e},canRevoke:{type:"boolean"},revokedBy:ts,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:mc},os={type:"object",additionalProperties:!1,required:Object.keys(ns).filter(e=>e!=="nodeId"),properties:ns},WE={$id:uc,...os},gc={schemaVersion:{const:fc},operationId:Kn,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},cc={...gc,operation:{const:"create"},workflowCode:ts,nodeId:pc,delegatorRoleSubjectKey:rr,expectedDelegatorRevision:An,delegateUserId:$e,delegateRoleSubjectKey:rr,expectedDelegateRevision:An,validFrom:Mt,validTo:Mt},lc={...gc,operation:{const:"revoke"},delegationId:Kn,expectedRevision:An},Hf={$id:fc,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(cc).filter(e=>e!=="nodeId"),properties:cc,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:$e}}},{type:"object",additionalProperties:!1,required:Object.keys(lc),properties:lc}]},Yf={type:"string",pattern:"^[0-9a-f]{64}$"},xE={$id:dc,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:dc},operationId:Kn,operation:{enum:["create","revoke"]},requestDigest:Yf,before:{anyOf:[os,{type:"null"}]},after:{...os,properties:{...ns,id:{anyOf:[Kn,{type:"null"}]}}},taskPolicy:mc}};function ME(e){return e===void 0?"":`
10
- ${ee(e)}`}function BE(e,t){let o=e.handlers.find(n=>n.code===t);return ee(o?.workflowStep?o:e)}var qE="openxiangda.data-business-command/v1",Xf="openxiangda.data-business-command-resolution/v1",zE=65536;function GE(e){let t=0,o=0,n=new Set,r=new TextEncoder,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},s=d=>(o+=r.encode(d).byteLength,o>65536&&i(),d),a=(d,c)=>{if(++t>1e4||c>32)return i();if(d===null||typeof d=="string"||typeof d=="boolean")return s(JSON.stringify(d));if(typeof d=="number")return Number.isFinite(d)?s(JSON.stringify(d)):i();if(!d||typeof d!="object"||n.has(d)||Object.getOwnPropertySymbols(d).length)return i();n.add(d);let l;if(Array.isArray(d))return Object.keys(d).length!==d.length?i():(l=s("[")+d.map((p,m)=>(m?s(","):"")+a(p,c+1)).join("")+s("]"),n.delete(d),l);let f=Object.getPrototypeOf(d);return f!==Object.prototype&&f!==null?i():(l=s("{")+Object.keys(d).sort().map((p,m)=>(m?s(","):"")+s(JSON.stringify(p))+s(":")+a(d[p],c+1)).join("")+s("}"),n.delete(d),l)};return!e||typeof e!="object"||Array.isArray(e)?i():a(e,0)}function JE(e,t,o=!1){let n=e,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!n||typeof n!="object"||n.schemaVersion!==Xf)return r();for(let d of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(n[d]!==t[d])return r();if(typeof n.observedAt!="string"||!Number.isFinite(Date.parse(n.observedAt)))return r();if(n.outcome==="not_observed"&&n.receipt===null&&!o)return n;if(n.outcome!=="committed"||!n.receipt)return r();let i=n.receipt,s=d=>typeof d=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(d);if(!s(i.id)||!s(i.appVersionId)||!Number.isSafeInteger(i.environmentHeadRevision)||i.environmentHeadRevision<1||typeof i.completedAt!="string"||!Number.isFinite(Date.parse(i.completedAt)))return r();let a=i.transaction;if(!a||a.schemaVersion!=="openxiangda.data-transaction-result/v2"||a.idempotencyKey!==t.idempotencyKey||typeof a.replayed!="boolean"||!Array.isArray(a.items)||!a.items.length||a.items.length>1e3)return r();for(let[d,c]of a.items.entries()){if(!c||c.index!==d)return r();if(c.operation==="emitEvent"){if(!s(c.eventId)||typeof c.eventType!="string"||!c.eventType)return r()}else if(!["create","update","delete","increment"].includes(c.operation)||!s(c.id)||typeof c.resourceCode!="string"||!c.resourceCode||!Number.isSafeInteger(c.revision)||c.revision<1)return r()}return n}var _c=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ir=e=>!!e&&typeof e=="object"&&!Array.isArray(e),qn=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),rs=(e,t,o=[])=>t.every(n=>Object.hasOwn(e,n))&&Object.keys(e).every(n=>[...t,...o].includes(n));function YE(e){if(!ir(e)||!rs(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!qn(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(!ir(o)||!rs(o,["roleCode"],["scope"])||!qn(o.roleCode,100)||!_c.test(o.roleCode))return!1;if(Object.hasOwn(o,"scope")){let i=o.scope;if(!ir(i)||!rs(i,["dimensionCode","value","operation"])||!qn(i.dimensionCode,100)||!_c.test(i.dimensionCode)||!qn(i.value,255)||!qn(i.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(i.operation))return!1}let n=o.scope,r=JSON.stringify([o.roleCode,n?.dimensionCode,n?.value,n?.operation]);return t.has(r)?!1:(t.add(r),!0)})}function XE(e,t,o){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!o||!t.capabilityCodes.includes(o))return!1;if(!e.scope)return!0;let n;try{n=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(n))return!1;let r=e.scope;return n.some(i=>ir(i)&&i.dimensionCode===r.dimensionCode&&Array.isArray(i.values)&&i.values.includes(r.value)&&(i.operations===void 0||i.operations===null||Array.isArray(i.operations)&&(!i.operations.length||i.operations.includes("*")||i.operations.includes(r.operation))))}var sr=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(e),Ac=new Set(["eq","neq","gt","gte","lt","lte"]);function Ec(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,o=Object.keys(t);return t.kind==="value"?o.some(n=>!["kind","field","operator","value","path"].includes(n))||!sr(t.field)||typeof t.operator!="string"||!Wo.has(t.operator)||Object.hasOwn(t,"path")&&(typeof t.path!="string"||!t.path||t.path.length>128)?!1:Ha.has(t.operator)?!Object.hasOwn(t,"value"):Object.hasOwn(t,"value"):t.kind==="field"?o.length===4&&["kind","leftField","operator","rightField"].every(n=>o.includes(n))&&sr(t.leftField)&&sr(t.rightField)&&Ac.has(String(t.operator)):t.kind==="database-now"?o.length===3&&["kind","field","operator"].every(n=>o.includes(n))&&sr(t.field)&&Ac.has(String(t.operator)):!1}var Zf=500,Qf=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,is=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function nI(e){if(!is(e)||e.kind!=="record-set-match"||Object.keys(e).some(o=>!["kind","resourceCode","errorCode","records","where","assertions"].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>Zf||Object.hasOwn(e,"where")&&!is(e.where)||Object.hasOwn(e,"assertions")&&(!Array.isArray(e.assertions)||!e.assertions.length||e.assertions.length>20||!e.assertions.every(Ec)))return!1;let t=new Set;return e.records.every(o=>{if(!is(o)||Object.keys(o).length!==2||typeof o.id!="string"||!Qf.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)})}var ep="openxiangda.development-configuration/v2",Ic="openxiangda.development-configuration-manifest/v1",sI="application.development-configuration",aI="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",ss=class extends Error{constructor(o,n){super(o);this.code=o;this.pointer=n;this.data={pointer:n}}code;pointer;status=400;data};function Tt(e){throw new ss("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function tp(e){(!e||typeof e!="object"||Array.isArray(e))&&Tt("/packageManifest");let t=e,o=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(r=>!o.includes(r))||t.schemaVersion!==Ic||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}`)&&Tt("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(r=>!["repository","commit","dirty"].includes(r))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&Tt("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(r=>!["version","contractVersion"].includes(r))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==xi)&&Tt("/packageManifest/toolchain");let n=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return re(t.artifacts)!==re(n)&&Tt("/packageManifest/artifacts"),t}function dI(e,t){return tp({schemaVersion:Ic,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:xi},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function cI(e,t,o){return(!Number.isSafeInteger(t)||t<1)&&Tt("/expectedHeadRevision"),`development:${ee({manifest:e,expectedHeadRevision:t,...o?{actorUserId:o}:{}})}`}function lI(e,t,o){(!e||typeof e!="object"||Array.isArray(e))&&Tt("/result");let n=e,r=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","publishedAppVersionId","selection","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],i=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(n).some(s=>!r.includes(s))||n.schemaVersion!==ep||n.appCode!==t||n.environmentKey!=="preproduction"||n.configDigest!==o.configDigest||n.contractDigest!==o.contractDigest||!i.test(n.environmentId)||!i.test(n.appVersionId)||!i.test(n.publishedAppVersionId)||n.appVersionId===n.publishedAppVersionId||n.selection!=="session"||!i.test(n.configurationRunId)||typeof n.reused!="boolean"||!Number.isSafeInteger(n.headRevision)||n.headRevision<1||n.headRevision!==o.expectedHeadRevision||n.runtimeArtifactsDeployed!==!1||n.backendEventsAvailable!==!1)&&Tt("/result"),n}var fI="application.development-backend-events",pI="openxiangda.development-backend/v1",mI="application.development-backend-invocations",np="openxiangda.development-backend-invocation/v1",gI=262144,_I=1048576,AI=131072,EI=131072,II=8,yI=45,OI=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function bI(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 hI(e){return`connected-development:${e}`}function op(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 rp(e,t,o){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||o.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let n=t.split("/"),r=String(o.path||"").split("/");return n.length!==r.length?!1:n.every((i,s)=>{if(s===0)return r[s]==="";let a;try{a=decodeURIComponent(i)}catch{return!1}return!a||[".",".."].includes(a)||/[\/\\\s\u0000-\u001f\u007f]/.test(a)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(r[s]||"")||i===r[s]})}var ip=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token|dev-selection))$/i,sp=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function ap(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let o=Object.entries(e),n=o.map(([r])=>r.toLowerCase());return o.length<=24&&new Set(n).size===n.length&&o.every(([r,i])=>(t?sp:ip).test(r)&&typeof i=="string"&&i.length<=8192&&!/[\r\n\u0000]/.test(i))}function NI(e){let t=op(e.body);return e.schemaVersion===np&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&rp(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&&ap(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 RI=Object.freeze({version:"rich-text-html/1",maxBytes:1048576,maxNodes:25e3,maxDepth:128,maxImages:20,imageMaxBytes:10485760,maxVideos:4,videoMaxBytes:104857600,imageTypes:["image/png","image/jpeg","image/webp","image/gif"],videoTypes:["video/mp4","video/webm"],fonts:["Arial","Verdana","Tahoma","Times New Roman","Courier New","\u5B8B\u4F53","\u5FAE\u8F6F\u96C5\u9ED1","SimSun","Microsoft YaHei","sans-serif","serif","monospace"]});function dp(e,t,o){let n=e.nodes,r=n[t],i=n[o];if(!r||!["approval","handle"].includes(r.kind)||!i||!["approval","handle","correction"].includes(i.kind)||t===o)return{allowed:!1,reason:"\u4E0D\u662F\u53EF\u9000\u56DE\u7684\u529E\u7406\u8282\u70B9"};let s=rt(e).regions;for(let c of s){let l=c.branches.find(p=>p.nodeIds.includes(t)),f=c.branches.find(p=>p.nodeIds.includes(o));if(l?.id!==f?.id&&(l||f))return{allowed:!1,reason:"\u5E76\u884C\u5206\u652F\u5185\u53EA\u80FD\u9000\u56DE\u672C\u5206\u652F\u7684\u8282\u70B9\uFF0C\u4E0D\u80FD\u8DE8\u8D8A\u6C47\u5408\u8FB9\u754C"}}let a=[o],d=new Set;for(;a.length;){let c=a.shift();if(c===t)return{allowed:!0};if(d.has(c))continue;d.add(c);let l=n[c];l&&a.push(...Lo(l).filter(f=>!d.has(f)))}return{allowed:!1,reason:"\u8BE5\u8282\u70B9\u4E0D\u5728\u672C\u8282\u70B9\u4E4B\u524D\u7684\u53EF\u8FBE\u6D41\u8F6C\u8DEF\u5F84\u4E0A"}}function yc(e){return Object.values(e.nodes||{}).flatMap(t=>t.kind==="approval"||t.kind==="handle"?ot(t).filter(o=>!dp(e,t.id,o).allowed).map(o=>`WORKFLOW_RETURN_TARGET_UNREACHABLE:${t.id}:${o}`):[])}var zn=e=>`canvas_${e}`,Oc=(e,t)=>[...e==="approval"?["approve","reject"]:["complete"],...t?["save_form"]:[],"return","transfer","delegate",...e==="approval"?["add_assignee"]:[]];function dr(e,t,o="",n=""){let r=new Map;for(let i of[...Object.values(e.nodes),...e.authoring?.businessSteps||[]])!("handler"in i)||ie(i)||r.set(`${i.handler.code}@${i.handler.version}`,{title:i.title,handler:i.handler,inputSchema:i.inputSchema,outputSchema:i.outputSchema});return{appVersionId:o,digest:n,taskPages:e.taskPages||{},steps:[...r.values()],peopleSources:{...t.bindings,...Object.fromEntries((e.authoring?.peopleSources||[]).map(i=>[`authoring:${i.code}`,i.entry]))},...e.authoring?.peopleSources?.length?{peopleSourceTemplates:JSON.parse(JSON.stringify(e.authoring.peopleSources))}:{}}}function cp(e,t,o,n,r,i={},s=n){let a=zn(e);if(t==="cc")return{id:e,kind:t,title:o,next:n,binding:a,emptyPolicy:"block",notify:!0,administration:{assigneeProviders:["fixed_users","app_role"]}};let d=r?i[r]:void 0,c=Oc(t,!!d),l={id:e,title:o,binding:a,mode:"single",allowedOperations:c,requiredOperations:[t==="approval"?"approve":"complete"],administration:{modes:["single","any","all","sequence"],assigneeProviders:["fixed_users","app_role"],operations:c},fieldPolicy:{default:"readonly",fields:Object.fromEntries((d?.fields||[]).map(f=>[f.code,f.readonly?"readonly":f.required?"edit_required":"edit"]))},operationPolicy:{...t==="approval"?{approve:{opinion:"optional",minimumOpinion:"optional"},reject:{opinion:"required",minimumOpinion:"required"}}:{complete:{opinion:"optional",minimumOpinion:"optional"}},return:{opinion:"required",minimumOpinion:"required"},transfer:{opinion:"required",minimumOpinion:"required"},delegate:{opinion:"required",minimumOpinion:"required"},...t==="approval"?{add_assignee:{opinion:"required",minimumOpinion:"required"}}:{}},...d?{taskPageCode:r}:{}};return t==="approval"?{...l,kind:t,onApprove:n,onReject:s}:{...l,kind:t,next:n}}var ar=(e,t)=>{let o=n=>Array.isArray(n)?n.map(o):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().filter(r=>n[r]!==void 0).map(r=>[r,o(n[r])])):n;return JSON.stringify(o(e))===JSON.stringify(o(t))};function bc(e,t){if(!["approval","handle","cc"].includes(e.kind)||!("binding"in e)||e.binding!==zn(e.id))return["WORKFLOW_DESIGNER_CANVAS_BINDING_REQUIRED"];if(e.kind==="cc")return ar(e.administration,{assigneeProviders:["fixed_users","app_role"]})?[]:["WORKFLOW_DESIGNER_CODE_OWNED:administration"];if(e.kind!=="approval"&&e.kind!=="handle")return[];let o=cp(e.id,e.kind,e.title,"",e.taskPageCode,t.taskPages),n=[];for(let s of["administration","requiredOperations"])ar(e[s],o[s])||n.push(`WORKFLOW_DESIGNER_CODE_OWNED:${e.id}.${s}`);e.taskPageCode&&!t.taskPages[e.taskPageCode]&&n.push(`WORKFLOW_DESIGNER_PAGE_UNRELEASED:${e.id}`);let r=o.fieldPolicy;e.fieldPolicy?.default&&e.fieldPolicy.default!=="readonly"&&n.push(`WORKFLOW_DESIGNER_FIELD_CEILING:${e.id}`);for(let[s,a]of Object.entries(e.fieldPolicy?.fields||{}))(!(s in r.fields)||!["readonly","edit","edit_required"].includes(a)||["edit","edit_required"].includes(a)&&r.fields[s]==="readonly")&&n.push(`WORKFLOW_DESIGNER_FIELD_CEILING:${e.id}.${s}`);let i=Oc(e.kind,!!e.taskPageCode);(e.allowedOperations||i).some(s=>!i.includes(s))&&n.push(`WORKFLOW_DESIGNER_OPERATION_NOT_ALLOWED:${e.id}`);for(let[s,a]of Object.entries(e.operationPolicy||{})){let d=o.operationPolicy?.[s];(!i.includes(s)||!ar(a.minimumOpinion,d?.minimumOpinion)||["none","optional","required"].indexOf(xt(s,a))<["none","optional","required"].indexOf(ln(s,d)))&&n.push(`WORKFLOW_DESIGNER_OPINION_MINIMUM:${e.id}.${s}`)}return n}function hc(e,t,o=!1,n){if(e.provider==="conditional"){if(!t.conditionalAssignments||!n)return["WORKFLOW_DESIGNER_CONDITIONAL_ASSIGNMENT_UNAVAILABLE"];let i=n.definition.nodes[n.nodeId];if(!i||!["approval","handle"].includes(i.kind))return["WORKFLOW_CONDITIONAL_HUMAN_REQUIRED"];if("emptyPolicy"in i&&i.emptyPolicy==="skip")return["WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED"];let s;try{s=Object.fromEntries(Object.entries(t.peopleSources).flatMap(([a,d])=>ae(d).map((c,l)=>[`${a}/${l}`,c])))}catch{return["WORKFLOW_CONDITIONAL_BINDING_INVALID"]}return Zt(e,{...n,releasedSources:s,peopleSourceTemplates:t.peopleSourceTemplates,standardProviders:["fixed_users","app_role"]},{allowIncomplete:o})}if(Object.values(t.peopleSources).some(i=>ar(i,e))||io(e,t.peopleSourceTemplates))return n?Lr(e,n.definition,n.nodeId):[];let r=Object.keys(e);if(e.provider==="fixed_users"&&r.every(i=>["provider","users"].includes(i))&&Array.isArray(e.users)&&e.users.length<=200&&(o||e.users.length>0)&&new Set(e.users).size===e.users.length&&e.users.every(i=>typeof i=="string"&&!!i.trim()&&i.length<=255))return[];if(e.provider==="app_role"&&r.every(i=>["provider","roleCode","roleCodes"].includes(i))){let i=e.roleCodes||(e.roleCode?[e.roleCode]:[]);if(!(e.roleCode&&e.roleCodes)&&(o||i.length>0)&&i.length<=8&&new Set(i).size===i.length&&i.every(s=>/^[a-z][a-z0-9_-]{0,127}$/.test(s)))return[]}return["WORKFLOW_DESIGNER_BINDING_UNRELEASED"]}function FI(e,t,o){return{...t,bindings:Object.fromEntries(Object.entries(t.bindings).filter(([n])=>Object.hasOwn(o.bindings,n)||!n.startsWith("canvas_")||Object.values(e.nodes).some(r=>"binding"in r&&r.binding===n)))}}var Ne=e=>!!e&&typeof e=="object"&&!Array.isArray(e),cr=e=>Array.isArray(e)?e.map(cr):Ne(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,cr(e[t])])):e,Fe=(e,t)=>JSON.stringify(cr(e))===JSON.stringify(cr(t));function lr(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="parallel"?[...(e.branches||[]).map(t=>t.target),e.join]:e.kind==="condition"?[...(e.branches||[]).map(t=>t.target),e.otherwise]:"next"in e?[e.next]:[]}function wc(e,t,o,n,r={}){let i=[...Do(t),...At(t,n)];if(!Ne(t)||!Ne(t.nodes)||!Ne(n?.bindings))return["WORKFLOW_DESIGNER_DOCUMENT_INVALID"];let s=new Set(["title","startAt","nodes","readability"]);for(let c of new Set([...Object.keys(e),...Object.keys(t)]))!s.has(c)&&!Fe(e[c],t[c])&&i.push(`WORKFLOW_DESIGNER_CODE_OWNED:${c}`);(o.workflowCode!==n.workflowCode||o.schemaVersion!==n.schemaVersion)&&i.push("WORKFLOW_DESIGNER_BINDING_IDENTITY");let a=r.catalog||dr(e,o),d=a.steps;for(let[c,l]of Object.entries(t.nodes)){if(!Ne(l)||l.id!==c||!["approval","handle","condition","cc","action","correction","end","parallel","join"].includes(l.kind)){i.push(`WORKFLOW_DESIGNER_NODE_INVALID:${c}`);continue}let f=e.nodes[c];f&&"binding"in f&&"binding"in l&&f.binding!==l.binding&&i.push(`WORKFLOW_DESIGNER_BINDING_CODE_OWNED:${c}`),"taskPageCode"in l&&l.taskPageCode&&!a.taskPages[l.taskPageCode]&&i.push(`WORKFLOW_DESIGNER_PAGE_UNRELEASED:${c}`),l.kind==="action"&&!ie(l)&&!d.some(m=>Fe(m.handler,l.handler)&&Fe(m.inputSchema,l.inputSchema)&&Fe(m.outputSchema,l.outputSchema))&&i.push(`WORKFLOW_DESIGNER_STEP_UNRELEASED:${c}`),["approval","handle"].includes(l.kind)&&"allowedOperations"in l&&l.allowedOperations&&(!Array.isArray(l.allowedOperations)||!l.allowedOperations.includes(l.kind==="handle"?"complete":"approve"))&&i.push(`WORKFLOW_DESIGNER_REQUIRED_ACTION:${c}.approve`);let p=e.nodes[c]||(l.kind==="approval"||l.kind==="handle"?Object.values(e.nodes).find(m=>{if(m.kind!==l.kind||!["approval","handle"].includes(m.kind)||!["fieldPolicy","administration","requiredOperations","taskPageCode"].every(O=>Fe(m[O],l[O])))return!1;let A=m;if(l.mode!==A.mode&&!A.administration?.modes?.includes(l.mode))return!1;let I=["none","optional","required"];return Object.entries(A.operationPolicy||{}).every(([O,b])=>{let g=l.operationPolicy?.[O];return Fe(b?.minimumOpinion,g?.minimumOpinion)&&I.indexOf(xt(O,g))>=I.indexOf(ln(O,b))})}):void 0);if(!p&&["approval","handle","cc"].includes(l.kind)&&("binding"in l&&l.binding!==zn(c)?i.push(`WORKFLOW_DESIGNER_APPROVAL_TEMPLATE_REQUIRED:${c}`):i.push(...bc(l,a).map(m=>`${m}:${c}`))),(p?.kind==="approval"||p?.kind==="handle")&&(l.kind==="approval"||l.kind==="handle")){l.mode!==p.mode&&!p.administration?.modes?.includes(l.mode)&&i.push(`WORKFLOW_DESIGNER_MODE_NOT_ALLOWED:${c}`);for(let m of["requiredOperations","fieldPolicy","administration"])Fe(p[m],l[m])||i.push(`WORKFLOW_DESIGNER_CODE_OWNED:${c}.${m}`);for(let m of p.requiredOperations||[])l.allowedOperations&&!l.allowedOperations.includes(m)&&i.push(`WORKFLOW_DESIGNER_REQUIRED_ACTION:${c}.${m}`);for(let[m,A]of Object.entries(p.operationPolicy||{})){let I=l.operationPolicy?.[m],O=["none","optional","required"];(!Fe(A?.minimumOpinion,I?.minimumOpinion)||O.indexOf(xt(m,I))<O.indexOf(ln(m,A)))&&i.push(`WORKFLOW_DESIGNER_CODE_OWNED:${c}.${m}.minimumOpinion`)}}"binding"in l&&!n.bindings[l.binding]&&i.push(`WORKFLOW_DESIGNER_BINDING_MISSING:${c}`)}Fe(e.readability?.logic,t.readability?.logic)||i.push("WORKFLOW_DESIGNER_CODE_OWNED:readability.logic");for(let[c,l]of Object.entries(n.bindings)){let f=o.bindings[c],p=Object.values(t.nodes).find(m=>"binding"in m&&m.binding===c&&c===zn(m.id));!f&&p&&!e.nodes[p.id]?i.push(...hc(l,a,r.allowIncomplete,{definition:t,nodeId:p.id}).map(m=>`${m}:${c}`)):!f&&!Object.values(o.bindings).some(m=>Fe(m,l))&&i.push(`WORKFLOW_DESIGNER_BINDING_UNRELEASED:${c}`),f&&!Fe(f,l)&&i.push(`WORKFLOW_DESIGNER_BINDING_CODE_OWNED:${c}`)}return i.push(...as(t)),[...new Set(i)]}function lp(e,t){if(t.type==="insert_parallel"||t.type==="insert_start_parallel"){if(e.nodes[t.joinId]||t.joinId===t.id||t.branches.length<2||t.branches.length>8)throw new Error("WORKFLOW_DESIGNER_PARALLEL_INSERT_INVALID");let r={id:t.id,kind:"parallel",title:t.title,join:t.joinId,branches:t.branches.map(s=>({...s,target:t.joinId}))},i=lp(e,t.type==="insert_start_parallel"?{type:"insert_start",target:t.target,node:r}:{type:"insert",from:t.from,target:t.target,node:r,...t.edge===void 0?{}:{edge:t.edge}});return i.nodes[t.joinId]={id:t.joinId,kind:"join",title:"\u5168\u90E8\u5B8C\u6210\u540E\u7EE7\u7EED",parallel:t.id,next:t.target},i}let o=structuredClone(e);if(t.type==="insert_start"){if(e.startAt!==t.target||!o.nodes[t.target]||o.nodes[t.node.id]||t.node.kind==="correction"||t.node.kind==="end"||t.node.kind==="join")throw new Error("WORKFLOW_DESIGNER_INSERT_INVALID");o.nodes[t.node.id]=structuredClone(t.node),o.startAt=t.node.id;for(let r of Object.values(o.nodes))r.kind==="correction"&&r.next===e.startAt&&(r.next=o.startAt);return o}let n=(r,i,s)=>{if(r.kind==="approval")r.onApprove===i&&(r.onApprove=s),r.onReject===i&&(r.onReject=s);else if(r.kind==="condition"){for(let a of r.branches)a.target===i&&(a.target=s);r.otherwise===i&&(r.otherwise=s)}else if(r.kind==="parallel")for(let a of r.branches)a.target===i&&(a.target=s);else"next"in r&&r.next===i&&(r.next=s)};if(t.type==="insert"){let r=o.nodes[t.from];if(!r||o.nodes[t.node.id]||!lr(r).includes(t.target)||!o.nodes[t.target])throw new Error("WORKFLOW_DESIGNER_INSERT_INVALID");if(o.nodes[t.node.id]=structuredClone(t.node),r.kind==="approval"){let i=t.edge==="reject"?"onReject":"onApprove";if(r[i]!==t.target)throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");r[i]=t.node.id}else if(r.kind==="parallel"){if(typeof t.edge!="number"||r.branches[t.edge]?.target!==t.target)throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");r.branches[t.edge].target=t.node.id}else if(r.kind==="condition")if(typeof t.edge=="number"&&r.branches[t.edge]?.target===t.target)r.branches[t.edge].target=t.node.id;else if(t.edge==="default"&&r.otherwise===t.target)r.otherwise=t.node.id;else throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");else if("next"in r)r.next=t.node.id;else throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID")}else if(t.type==="remove_parallel_branch"){let r=o.nodes[t.nodeId];if(r?.kind!=="parallel"||r.branches.length<=2)throw new Error("WORKFLOW_PARALLEL_BRANCH_LIMIT");let s=rt(o).regions.find(a=>a.parallelNodeId===r.id)?.branches.find(a=>a.id===t.branchId);if(!s)throw new Error("WORKFLOW_DESIGNER_PARALLEL_BRANCH_MISSING");r.branches=r.branches.filter(a=>a.id!==t.branchId);for(let a of s.nodeIds)delete o.nodes[a]}else if(t.type==="remove"){let r=o.nodes[t.nodeId];if(r?.kind==="parallel"){let s=o.nodes[r.join],a=rt(o).regions.find(c=>c.parallelNodeId===r.id);if(s?.kind!=="join"||!a)throw new Error("WORKFLOW_DESIGNER_PARALLEL_PAIR_INVALID");let d=new Set([r.id,s.id,...a.branches.flatMap(c=>c.nodeIds)]);for(let c of Object.values(o.nodes))if(!d.has(c.id))for(let l of d)n(c,l,s.next);for(let c of d)delete o.nodes[c];return o.startAt===r.id&&(o.startAt=s.next),o}let i=t.reconnectTo||(r?.kind==="approval"?r.onApprove:r&&"next"in r?r.next:void 0);if(!r||!i||i===r.id||!o.nodes[i]||r.kind==="end"||r.kind==="correction"||r.kind==="join")throw new Error("WORKFLOW_DESIGNER_REMOVE_INVALID");for(let s of Object.values(o.nodes))n(s,r.id,i),(s.kind==="approval"||s.kind==="handle")&&s.returnTargets&&(s.returnTargets=s.returnTargets.filter(a=>a!==r.id)),(s.kind==="approval"||s.kind==="handle")&&s.returnPolicy&&(s.returnPolicy.targets=s.returnPolicy.targets.filter(a=>a.nodeId!==r.id));o.startAt===r.id&&(o.startAt=i),delete o.nodes[r.id]}else{let r=o.nodes[t.nodeId];if(!r)throw new Error("WORKFLOW_DESIGNER_NODE_MISSING");if(t.type==="node"){if("id"in t.patch||"kind"in t.patch)throw new Error("WORKFLOW_DESIGNER_NODE_ID_IMMUTABLE");Object.assign(r,t.patch)}else{if(r.kind!=="condition"||t.index<0||t.index>r.branches.length)throw new Error("WORKFLOW_DESIGNER_BRANCH_INVALID");r.branches[t.index]={when:structuredClone(t.when),target:t.target,...t.label?{label:t.label}:{}}}}return o}var Nc=(e,t)=>t.split(".").reduce((o,n)=>Ne(o)&&Object.hasOwn(o,n)?o[n]:void 0,e),Rc=(e,t)=>t.includes(",")?t.split(",").some(o=>Rc(e,o)):t==="unknown"?!0:t==="null"?e===null:t==="number"||t==="integer"?typeof e=="number"&&Number.isFinite(e)&&(t!=="integer"||Number.isInteger(e)):t==="array"?Array.isArray(e):t==="object"?Ne(e):typeof e===t;function JI(e,t,o){if(o.held)return{outcome:"held",reason:"\u5DF2\u6307\u5B9A\u4FDD\u7559\u5728\u539F\u7248\u672C"};let n=o.activeNodeIds?.length?o.activeNodeIds:o.currentNodeId?[o.currentNodeId]:[];if(!n.length)return{outcome:"excepted",reason:"\u5F53\u524D\u8FD0\u884C\u4F4D\u7F6E\u65E0\u6CD5\u786E\u5B9A"};if(n.some(a=>!t.nodes[a]))return{outcome:"excepted",reason:"\u5F53\u524D\u8282\u70B9\u5DF2\u88AB\u5220\u9664"};if(n.some(a=>e.nodes[a]?.kind!==t.nodes[a]?.kind))return{outcome:"excepted",reason:"\u5F53\u524D\u8282\u70B9\u7C7B\u578B\u5DF2\u6539\u53D8"};if((o.returnTargetNodeIds||[]).some(a=>!t.nodes[a]))return{outcome:"excepted",reason:"\u6B63\u5728\u9000\u56DE\u7684\u76EE\u6807\u8282\u70B9\u5DF2\u88AB\u5220\u9664"};if(!Fe(e.subject,t.subject)||!Fe(e.inputSchema,t.inputSchema))return{outcome:"excepted",reason:"\u7533\u8BF7\u6570\u636E\u6216\u53D8\u91CF\u5B9A\u4E49\u5DF2\u6539\u53D8\uFF0C\u9700\u8981\u660E\u786E\u7684\u6570\u636E\u8F6C\u6362"};if(o.forkNodeId){let a=e.nodes[o.forkNodeId],d=t.nodes[o.forkNodeId];if(a?.kind!=="parallel"||d?.kind!=="parallel"||a.join!==d.join)return{outcome:"excepted",reason:"\u6B63\u5728\u8FD0\u884C\u7684\u5E76\u884C\u5206\u652F\u6216\u6C47\u5408\u70B9\u5DF2\u6539\u53D8"};let c=rt(e).regions.find(f=>f.parallelNodeId===a.id),l=rt(t).regions.find(f=>f.parallelNodeId===d.id);for(let f of o.unarrivedBranchIds||[]){let p=l?.branches.find(m=>m.id===f);if(!p||n.some(m=>c?.branches.find(A=>A.id===f)?.nodeIds.includes(m)&&!p.nodeIds.includes(m)))return{outcome:"excepted",reason:"\u5C1A\u672A\u5B8C\u6210\u7684\u5E76\u884C\u5206\u652F\u6216\u5176\u5F53\u524D\u8282\u70B9\u5DF2\u6539\u53D8"}}}if(o.businessStepPending)return{outcome:"deferred",reason:"\u4E1A\u52A1\u6B65\u9AA4\u6267\u884C\u4E2D\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u66F4\u65B0"};let r=new Set,i=[...n];for(;i.length;){let a=i.pop();r.has(a)||(r.add(a),i.push(...lr(t.nodes[a]||{}).filter(d=>!!t.nodes[d])))}let s=Mo(t,"preview");for(let a of Object.values(t.nodes)){if(!r.has(a.id))continue;let d=a.kind==="condition"?a.branches.map(c=>c.when):a.kind==="action"?Object.values(a.inputs).filter(c=>c.source==="fact").map(c=>({op:"path",path:c.path})):[];for(let c of d)for(let l of Fn(c).paths){let f=s.variables.find(m=>m.path===l),p=Nc(o.facts,l);if(p===void 0&&f?.source.kind==="step_output"&&r.has(f.source.nodeId)&&!n.includes(f.source.nodeId)){let m=new Set,A=[...n];for(;A.length;){let I=A.pop();I===f.source.nodeId||m.has(I)||(m.add(I),A.push(...lr(t.nodes[I]||{}).filter(O=>!!t.nodes[O])))}if(!m.has(a.id))continue}if(!(p===void 0&&f&&!f.required&&(f.source.kind!=="step_output"||Ne(Nc(o.facts,`steps.${f.source.nodeId}`))))&&(p===void 0||f&&!Rc(p,f.type)))return{outcome:"excepted",reason:`\u540E\u7EED\u6761\u4EF6\u9700\u8981\u7684\u6570\u636E\u5728\u8BE5\u7533\u8BF7\u4E2D\u4E0D\u5B58\u5728\u6216\u7C7B\u578B\u4E0D\u517C\u5BB9\uFF1A${f?.label||l}`}}}return{outcome:"eligible"}}function as(e){if(!Ne(e?.nodes))return["WORKFLOW_DESIGNER_DOCUMENT_INVALID"];let t=[];t.push(...vo(e),...Po(e),...ko(e),...yc(e),...Qn(e));let o=Object.values(e.nodes);if(o.length>200||!o.length)return["WORKFLOW_DESIGNER_NODE_LIMIT"];for(let c of o)!Ne(c)||!["approval","handle","condition","cc","action","correction","end","parallel","join"].includes(c.kind)?t.push("WORKFLOW_DESIGNER_NODE_INVALID"):c.kind==="condition"&&(!Array.isArray(c.branches)||!c.branches.length||c.branches.length>32||c.branches.some(l=>!Ne(l)||!Ne(l.when)||typeof l.target!="string"))&&t.push(`WORKFLOW_DESIGNER_BRANCH_INVALID:${c.id}`);if(t.length)return[...new Set(t)];let n=Mo(e,"draft").variables,r=0,i=(c,l,f=0)=>{if(!Ne(c)||f>16||++r>4096)return t.push(`WORKFLOW_DESIGNER_EXPRESSION_LIMIT:${l}`),"invalid";if(c.op==="literal"){let p=c.value;return p===null?"null":Array.isArray(p)?"array":typeof p=="object"?"object":typeof p}if(c.op==="path"){let p=n.find(A=>A.path===c.path);(!p||p.type==="unknown")&&t.push(`WORKFLOW_DESIGNER_VARIABLE_UNKNOWN:${l}:${c.path}`);let m=p?.type.split(",").find(A=>A!=="null")||p?.type||"unknown";return m==="integer"?"number":m}if(c.op==="and"||c.op==="or"){if(!Array.isArray(c.values)||c.values.length<1||c.values.length>32)return t.push(`WORKFLOW_DESIGNER_CONDITION_GROUP:${l}`),"invalid";for(let p of c.values)i(p,l,f+1)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${l}`)}else if(c.op==="not"||c.op==="exists"){let p=i(c.value,l,f+1);c.op==="not"&&p!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${l}`)}else if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(c.op)&&"left"in c){let p=i(c.left,l,f+1),m=i(c.right,l,f+1);(c.op==="in"?m==="array":c.op==="contains"?p==="array"||p==="string"&&m==="string":["gt","gte","lt","lte"].includes(c.op)?p===m&&["number","string"].includes(p):p===m||p==="null"||m==="null")||t.push(`WORKFLOW_DESIGNER_CONDITION_TYPE:${l}`)}else t.push(`WORKFLOW_DESIGNER_CONDITION_OPERATOR:${l}`);return"boolean"},s=new Set,a=new Set,d=c=>{if(a.has(c)){t.push(`WORKFLOW_DESIGNER_CYCLE:${c}`);return}if(s.has(c))return;let l=e.nodes[c];if(!l){t.push(`WORKFLOW_DESIGNER_TARGET_MISSING:${c}`);return}a.add(c);for(let f of lr(l))d(f);a.delete(c),s.add(c)};for(let c of o){if((!/^[a-z][a-z0-9_-]{0,127}$/.test(c.id)||e.nodes[c.id]!==c)&&t.push(`WORKFLOW_DESIGNER_NODE_ID:${c.id}`),c.kind==="parallel")for(let l of c.branches)l.when&&i(l.when,c.id)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${c.id}`);if(c.kind==="condition"){(!c.branches.length||c.branches.length>32)&&t.push(`WORKFLOW_DESIGNER_BRANCH_LIMIT:${c.id}`);for(let l of c.branches)i(l.when,c.id)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${c.id}`)}}d(e.startAt);for(let c of o)!s.has(c.id)&&c.kind!=="correction"&&t.push(`WORKFLOW_DESIGNER_UNREACHABLE:${c.id}`);return[...new Set(t)]}function HI(e){let t={...e.readability?.variables},o=(n,r="",i=0)=>{if(!(i>8||!Ne(n)))if(n.type==="object"&&Ne(n.properties))for(let[s,a]of Object.entries(n.properties))o(a,r?`${r}.${s}`:s,i+1);else r&&(t[r]||={label:String(n.title||r)})};o(e.inputSchema);for(let n of Object.values(e.nodes))n.kind==="action"&&o(n.outputSchema,`steps.${n.id}`);return Mo({...e,readability:{...e.readability,variables:t}},"draft").variables.filter(n=>n.type!=="unknown")}function ur(e,t){return(t?(Array.isArray(e)?e:[]).filter(Array.isArray):[Array.isArray(e)?e.filter(n=>!Array.isArray(n)):[]]).map(n=>n[n.length-1]?.value).filter(n=>!!n)}var Tc=["province","city","district","street"];function Cc(e){for(let t=Tc.length-1;t>=0;t-=1){let o=Tc[t],n=o?e?.[o]:void 0;if(o&&n?.value)return{path:`${o}.value`,value:n.value}}}function ds(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&"value"in e)}function cs(e){return ds(e)?String(e.value):e}function Sc(e){return(Array.isArray(e)?e:[e]).map(cs)}function up(e,t,o){let n=new Set(Object.keys(t.fields)),r=s=>{if(!n.has(s))throw new Error(`OPENXIANGDA_RESOURCE_QUERY_FIELD_NOT_DECLARED:${e}:${s}`);return s},i=o.where?[fr(e,t,o.where)]:[];if(o.createdBy!==void 0&&o.createdBy!==""&&i.push({field:"created_by",operator:"eq",value:o.createdBy}),o.keyword?.trim()){let s=(t.list?.searchableFields||[]).filter(a=>n.has(a));s.length&&i.push({or:s.map(a=>({field:r(a),operator:"contains",value:o.keyword.trim()}))})}for(let[s,a]of Object.entries(o.filters||{})){if(a==null||a===""||Array.isArray(a)&&a.length===0||!n.has(s))continue;let d=t.fields[s];if(d)if(d.type==="json")i.push({field:s,operator:"jsonContains",value:a});else if(d.type==="address"){let c=Cc(a);c&&i.push({field:s,operator:"jsonContains",path:c.path,value:c.value})}else if(d.type==="cascade.single"||d.type==="cascade.multiple"){let c=ur(a,d.type==="cascade.multiple");c.length&&i.push({field:s,operator:d.type==="cascade.multiple"?"hasAny":"has",value:d.type==="cascade.multiple"?c:c[0]})}else if((d.type==="date-range"||d.type==="datetime-range")&&a!==null&&typeof a=="object"&&!Array.isArray(a)){let c=a;c.start!==void 0&&c.end!==void 0&&i.push({field:s,operator:"overlaps",value:{start:c.start,end:c.end}})}else if(Array.isArray(a)&&a.length===2&&["date","datetime","number","money","percent"].includes(d.widget))a[0]!==void 0&&a[0]!==null&&a[0]!==""&&i.push({field:s,operator:"gte",value:a[0]}),a[1]!==void 0&&a[1]!==null&&a[1]!==""&&i.push({field:s,operator:"lte",value:a[1]});else if(d.type==="option.multiple"||d.type==="user.multiple"||d.type==="department.multiple"||d.type==="resource-ref.multiple")i.push({field:s,operator:"hasAny",value:Sc(a)});else{let[c]=Sc(a);i.push({field:s,operator:"eq",value:c})}}return i.length?{and:i}:void 0}function fr(e,t,o){if("and"in o)return{and:o.and.map(s=>fr(e,t,s))};if("or"in o)return{or:o.or.map(s=>fr(e,t,s))};if("not"in o)return{not:fr(e,t,o.not)};if(o.path!==void 0)return o;if(o.operator==="isEmpty"||o.operator==="isNotEmpty")return{field:o.field,operator:o.operator};let n=t.fields[o.field];if(o.operator==="has"){let s=n?.type==="cascade.single"&&Array.isArray(o.value)&&o.value.length>0&&o.value.every(ds);return{...o,value:s?ur(o.value,!1)[0]:cs(o.value)}}if(["in","between","hasAny","hasAll"].includes(o.operator)){if(!Array.isArray(o.value))return o;let s=n?.type==="cascade.multiple"&&["hasAny","hasAll"].includes(o.operator)&&o.value.length>0&&o.value.every(a=>Array.isArray(a)&&a.length>0&&a.every(ds));return{...o,value:s?ur(o.value,!0):o.value.map(cs)}}let r=up(e,t,{page:1,pageSize:20,filters:{[o.field]:o.value}}),i=r&&"and"in r?r.and[0]:void 0;return i&&"field"in i?{...i,operator:o.operator}:o}var Jn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Gn=(e,t)=>Jn(e)&&Object.keys(e).every(o=>t.includes(o)),Hn=e=>JSON.parse(JSON.stringify(e));function He(){throw new Error("WORKFLOW_BUNDLE_HANDLING_INVALID")}function ls(e,t){if(Jn(e)||He(),e.kind==="named_people")return(!Gn(e,["kind","count"])||!Number.isSafeInteger(e.count)||e.count<0||e.count>200)&&He(),t?{provider:"fixed_users",users:["source-private-leaf"]}:void 0;(!Gn(e,["kind","binding"])||e.kind!=="binding"||!Jn(e.binding)||["fixed_users","conditional"].includes(e.binding.provider))&&He();let o=e.binding;return ke({provider:"conditional",cases:[{when:{op:"literal",value:!0},assignee:o}],otherwise:o}).length&&He(),Hn(o)}function pr(e,t){if(Jn(e)||He(),e.kind==="roles"){(!Gn(e,["kind","roleCodes"])||!Array.isArray(e.roleCodes))&&He();let s=e.roleCodes.length===1?{provider:"app_role",roleCode:e.roleCodes[0]}:{provider:"app_role",roleCodes:e.roleCodes};return ke({provider:"conditional",cases:[{when:{op:"literal",value:!0},assignee:s}],otherwise:s}).length&&He(),Hn(s)}if(e.kind!=="conditional")return ls(e,t);(!Gn(e,["kind","cases","otherwise"])||!Array.isArray(e.cases)||!e.cases.length||e.cases.length>20)&&He();let o=!1,n=e.cases.map(s=>{Gn(s,["label","when","assignee"])||He();let a=ls(s.assignee,t);return a||(o=!0),{...s.label!==void 0?{label:s.label}:{},when:s.when,assignee:a||{provider:"fixed_users",users:["source-private-leaf"]}}}),r=ls(e.otherwise,t);r||(o=!0);let i={provider:"conditional",cases:n,otherwise:r||{provider:"fixed_users",users:["source-private-leaf"]}};return ke(i).length&&He(),o?void 0:Hn(i)}function oy(e){let t=n=>n.provider==="fixed_users"?{kind:"named_people",count:n.users?.length||0}:{kind:"binding",binding:Hn(n)};if(e.provider==="conditional")return ke(e).length&&He(),{kind:"conditional",cases:e.cases.map(n=>({...n.label!==void 0?{label:n.label}:{},when:Hn(n.when),assignee:t(n.assignee)})),otherwise:t(e.otherwise)};let o=t(e);return pr(o,!0),o}function ry(e){return pr(e,!1)}function iy(e){if(!e)return{present:!1,count:0};pr(e,!0);let o=(e.kind==="conditional"?[...e.cases.map(n=>n.assignee),e.otherwise]:[e]).filter(n=>n.kind==="named_people");return{present:o.length>0,count:o.reduce((n,r)=>n+r.count,0)}}function Dc(e,t,o){try{let n=pr(e,!0);if(!n)return["WORKFLOW_BUNDLE_HANDLING_INVALID"];let r=t.nodes[o];if(!r||!("binding"in r))return["WORKFLOW_BUNDLE_HANDLING_INVALID"];if(n.provider!=="conditional"&&Jn(e)&&e.kind!=="binding")return[];let i=n.provider==="conditional"?n:{provider:"conditional",cases:[{when:{op:"literal",value:!0},assignee:n}],otherwise:n},s="$source-handling-validation",a={...t,nodes:{...t.nodes,[o]:{...r,binding:s}}};return"emptyPolicy"in r&&r.emptyPolicy==="skip"?["WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED"]:Xt(a,{schemaVersion:"openxiangda.workflow-binding/v2",workflowCode:t.code,bindings:{[s]:i}})}catch{return["WORKFLOW_BUNDLE_HANDLING_INVALID"]}}var kc="openxiangda.workflow-source-bundle/v1",us="openxiangda.workflow-source-bundle/v2",fp=3*1024*1024,mt=(e,t)=>e.replace(/^sha256:/,"")===t.replace(/^sha256:/,""),Kt=(e,t)=>mt(e.definitionDigest,t.definitionDigest)&&mt(e.bindingDigest,t.bindingDigest),mr=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Bt=(e,t)=>mr(e)&&Object.keys(e).every(o=>t.includes(o)&&!["__proto__","constructor","prototype"].includes(o)),fs=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(e),pp=e=>typeof e=="string"&&/^(sha256:)?[a-f0-9]{64}$/.test(e);function mp(e,t,o){let n=new Set(Object.values(e.nodes).flatMap(i=>"taskPageCode"in i&&i.taskPageCode?[i.taskPageCode]:[])),r=new Map;for(let i of Object.values(e.nodes))i.kind==="action"&&r.set(`${i.handler.code}@${i.handler.version}`,{code:i.handler.code,version:i.handler.version,digest:o({handler:i.handler,inputSchema:i.inputSchema,outputSchema:i.outputSchema})});return{taskPages:[...n].sort().map(i=>({code:i,digest:o(e.taskPages?.[i])})),steps:[...r.values()].sort((i,s)=>i.code.localeCompare(s.code)||i.version-s.version),bindingKeys:Object.keys(t.bindings).sort(),roles:[...new Set(Object.values(t.bindings).flatMap(i=>ae(i).flatMap(s=>[...Yn(s),...i.provider==="conditional"?Object.values(s.routing?.sources||{}).map(a=>a.roleCode):[]])))].sort()}}function gp(e,t){try{return _p(e,t)}catch{return["WORKFLOW_BUNDLE_CORRUPT"]}}function _p(e,t){let o=[];if(!Bt(e,["schemaVersion","appCode","workflowCode","origin","definition","binding","references","handling"])||![kc,us].includes(e.schemaVersion)||!fs(e.appCode)||!fs(e.workflowCode))return["WORKFLOW_BUNDLE_CORRUPT"];if(new TextEncoder().encode(JSON.stringify(e)).length>fp)return["WORKFLOW_BUNDLE_TOO_LARGE"];let n=e,r=n.origin;if(!Bt(r,["environmentKey","headRevision","definitionVersion","bindingVersion","definitionDigest","bindingDigest","handlingDigest","catalogDigest"])||!["preproduction","production"].includes(r.environmentKey)||![r.headRevision,r.definitionVersion,r.bindingVersion].every(i=>Number.isSafeInteger(i)&&i>=1)||![r.definitionDigest,r.bindingDigest,r.handlingDigest,r.catalogDigest].every(pp))return["WORKFLOW_BUNDLE_CORRUPT"];if(!mr(n.definition?.nodes)||!mr(n.binding?.bindings)||n.definition.code!==n.workflowCode||n.binding.workflowCode!==n.workflowCode)return["WORKFLOW_BUNDLE_CORRUPT"];if(n.schemaVersion===kc&&Object.values(n.binding.bindings).some(i=>i.provider==="conditional"))return["WORKFLOW_SOURCE_CONDITIONAL_EXPORT_UNAVAILABLE"];if(n.schemaVersion===us){o.push(...Xt(n.definition,n.binding));for(let i of Object.values(n.definition.nodes))"binding"in i&&n.binding.bindings[i.binding]?.provider==="conditional"&&"emptyPolicy"in i&&i.emptyPolicy==="skip"&&o.push("WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED")}if(as(n.definition).length&&o.push("WORKFLOW_BUNDLE_DEFINITION_INVALID"),(!mt(t(n.definition),r.definitionDigest)||!mt(t(n.binding),r.bindingDigest)||!mt(t(n.handling),r.handlingDigest)||!mt(t(n.references),r.catalogDigest))&&o.push("WORKFLOW_BUNDLE_CORRUPT"),mt(t(mp(n.definition,n.binding,t)),t(n.references))||o.push("WORKFLOW_BUNDLE_CATALOG_CORRUPT"),!mr(n.handling)||Object.keys(n.handling).length>200)o.push("WORKFLOW_BUNDLE_HANDLING_INVALID");else for(let[i,s]of Object.entries(n.handling)){if(!n.definition.nodes[i]||!Bt(s,["mode","operations","assignee"])){o.push("WORKFLOW_BUNDLE_HANDLING_INVALID");continue}if(s.mode!==void 0&&!["single","any","all","sequence"].includes(s.mode)&&o.push("WORKFLOW_BUNDLE_HANDLING_INVALID"),s.operations!==void 0){let d=["complete","approve","reject","save_form","return","transfer","delegate","add_assignee"];if(!Bt(s.operations,d))o.push("WORKFLOW_BUNDLE_HANDLING_INVALID");else for(let c of Object.values(s.operations))(!Bt(c,["enabled","label","opinion","commentRequired","reasonRequired"])||c.enabled!==void 0&&typeof c.enabled!="boolean"||c.commentRequired!==void 0&&typeof c.commentRequired!="boolean"||c.reasonRequired!==void 0&&typeof c.reasonRequired!="boolean"||c.label!==void 0&&(typeof c.label!="string"||!c.label.trim()||c.label.length>255)||c.opinion!==void 0&&!["none","optional","required"].includes(c.opinion))&&o.push("WORKFLOW_BUNDLE_HANDLING_INVALID")}let a=s.assignee;if(a&&n.schemaVersion===us){let d=n.definition.nodes[i],c={...n.definition,nodes:{...n.definition.nodes,[i]:{...d,..."mode"in d&&s.mode?{mode:s.mode}:{}}}},l=Dc(a,c,i);l.length&&o.push("WORKFLOW_BUNDLE_HANDLING_INVALID",...l)}else a&&(a.kind==="named_people"?!Bt(a,["kind","count"])||!Number.isSafeInteger(a.count)||a.count<0||a.count>200:a.kind!=="roles"||!Bt(a,["kind","roleCodes"])||!Array.isArray(a.roleCodes)||a.roleCodes.length>200||!a.roleCodes.every(fs))&&o.push("WORKFLOW_BUNDLE_HANDLING_INVALID")}return[...new Set(o)]}function py(e){if(!e.head)return"not_active";if(Kt(e.declared,e.head))return"in_sync";let t=e.base||e.activeDeclaration;return t&&Kt(t,e.head)?"ahead":!t||Kt(e.declared,t)?"behind":"diverged"}function my(e){return e.head?Kt(e.declared,e.head)?"reuse":e.activeDeclaration&&Kt(e.declared,e.activeDeclaration)?"preserve":e.base&&Kt(e.base,e.head)||e.activeDeclaration&&Kt(e.activeDeclaration,e.head)?"advance":"diverged":"advance"}function gy(e,t,o,n){let r=gp(o,n);if(r.length)return r;r.push(...wc(e,o.definition,t,o.binding).map(s=>`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:${s}`));for(let s of o.references.taskPages)(!e.taskPages?.[s.code]||!mt(n(e.taskPages[s.code]),s.digest))&&r.push(`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:taskPage:${s.code}`);let i=dr(e,t).steps.map(s=>({code:s.handler.code,version:s.handler.version,digest:n({handler:s.handler,inputSchema:s.inputSchema,outputSchema:s.outputSchema})}));for(let s of o.references.steps)i.some(a=>a.code===s.code&&a.version===s.version&&mt(a.digest,s.digest))||r.push(`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:step:${s.code}@${s.version}`);return[...new Set(r)]}var ps="openxiangda.workflow-definition/v2",ms="openxiangda.workflow-binding/v2";var G={type:"string",minLength:1},Ep={type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},Ye=e=>({type:"string",minLength:1,maxLength:e,pattern:"\\S"}),Lc={type:"array",maxItems:32,uniqueItems:!0,items:Ye(256)},Ip={type:"object",additionalProperties:!1,minProperties:1,properties:{variables:{type:"object",maxProperties:128,propertyNames:Ye(256),additionalProperties:{type:"object",additionalProperties:!1,required:["label"],properties:{label:Ye(160),unit:Ye(32),description:Ye(2e3)}}},logic:{type:"array",maxItems:32,items:{type:"object",additionalProperties:!1,required:["code","title","description","phase","inputPaths"],properties:{code:{type:"string",pattern:"^[a-z][a-z0-9-]{2,63}$"},title:Ye(160),description:Ye(4e3),phase:{enum:["submission","node_input","completion"]},nodeId:Ye(128),inputPaths:Lc,outputPaths:Lc,source:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:Ye(256),symbol:Ye(160),digest:{type:"string",pattern:"^sha256:[a-f0-9]{64}$"}}}}}}}},yp={type:"object",additionalProperties:!1,required:["id","kind","title","binding","next","emptyPolicy"],properties:{id:G,kind:{const:"cc"},title:G,binding:G,next:G,emptyPolicy:{enum:["block","skip"]},notify:{type:"boolean"},administration:{type:"object",additionalProperties:!1,properties:{assigneeProviders:{type:"array",minItems:1,maxItems:3,uniqueItems:!0,items:{enum:["fixed_users","app_role","app_role_in_scope"]}}}}}},gs={type:"object",additionalProperties:!1,required:["afterSeconds","everySeconds","max","to"],properties:{afterSeconds:{type:"integer",minimum:1,maximum:2592e3},everySeconds:{type:"integer",minimum:1,maximum:2592e3},max:{type:"integer",minimum:1,maximum:10},to:{type:"array",minItems:1,maxItems:1,items:{const:"handlers"}}}},Op={type:"object",additionalProperties:!1,required:["id","kind","title","next","handler","inputSchema","outputSchema","inputs"],properties:{id:G,kind:{const:"action"},title:G,next:G,handler:{type:"object",additionalProperties:!1,required:["code","version","mode"],properties:{code:{type:"string",pattern:"^[a-z][a-z0-9-]{0,100}$"},version:{type:"integer",minimum:1,maximum:1e6},mode:{enum:["pure","reconciled-effect"]},dataTransaction:{const:!0}},allOf:[{if:{required:["dataTransaction"]},then:{properties:{mode:{const:"reconciled-effect"}}}}]},notification:{type:"object",additionalProperties:!1,required:["template","recipients"],properties:{template:{const:"workflow_message"},recipients:{oneOf:[{type:"object",additionalProperties:!1,required:["provider"],properties:{provider:{const:"initiator"}}},{type:"object",additionalProperties:!1,required:["provider","users"],properties:{provider:{const:"fixed_users"},users:{type:"array",minItems:1,maxItems:50,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:255}}}},{type:"object",additionalProperties:!1,required:["provider","roleCode"],properties:{provider:{const:"app_role"},roleCode:G}},{type:"object",additionalProperties:!1,required:["provider","inputPath"],properties:{provider:{const:"form_field_users"},inputPath:G}}]}}},inputSchema:{type:"object"},outputSchema:{type:"object"},inputs:{type:"object",maxProperties:32,additionalProperties:{oneOf:[{type:"object",additionalProperties:!1,required:["source","path"],properties:{source:{const:"fact"},path:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["source","value"],properties:{source:{const:"literal"},value:{}}}]}}}},vc={type:"object",additionalProperties:!1,required:["targets"],properties:{targets:{type:"array",maxItems:20,items:{type:"object",additionalProperties:!1,required:["nodeId","routes","defaultRoute"],properties:{nodeId:G,routes:{type:"array",minItems:1,maxItems:2,uniqueItems:!0,items:{enum:["replay","resume"]}},defaultRoute:{enum:["replay","resume"]}}}}}},bp={oneOf:[{type:"object",additionalProperties:!1,required:["id","kind","title","binding","mode","next","allowedOperations","requiredOperations"],properties:{id:G,kind:{const:"handle"},title:G,reminders:gs,binding:G,mode:{enum:["single","any","all","sequence"]},next:G,emptyPolicy:{const:"block"},taskPageCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},allowedOperations:{type:"array",uniqueItems:!0,items:{enum:["complete","save_form","return","transfer","delegate"]}},requiredOperations:{type:"array",uniqueItems:!0,items:{enum:["complete","save_form","return","transfer","delegate"]}},returnPolicy:vc,returnTargets:{type:"array",items:G,uniqueItems:!0},operationPolicy:{type:"object",additionalProperties:!1,properties:Object.fromEntries(["complete","save_form","return","transfer","delegate"].map(e=>[e,{type:"object",additionalProperties:!1,minProperties:1,properties:{label:{type:"string",minLength:1,maxLength:40},...e!=="save_form"?{opinion:{enum:["none","optional","required"]},minimumOpinion:{enum:["none","optional","required"]}}:{},...e==="complete"?{commentRequired:{type:"boolean"}}:{},...["return","transfer","delegate"].includes(e)?{reasonRequired:{type:"boolean"}}:{}}}]))},administration:{type:"object",additionalProperties:!1,properties:{modes:{type:"array",uniqueItems:!0,minItems:1,maxItems:4,items:{enum:["single","any","all","sequence"]}},assigneeProviders:{type:"array",uniqueItems:!0,minItems:1,maxItems:3,items:{enum:["fixed_users","app_role","app_role_in_scope"]}},operations:{type:"array",uniqueItems:!0,minItems:1,maxItems:5,items:{enum:["complete","save_form","return","transfer","delegate"]}}}},fieldPolicy:{type:"object",additionalProperties:!1,properties:{default:{enum:["hidden","readonly","edit","edit_required"]},fields:{type:"object",additionalProperties:{enum:["hidden","readonly","edit","edit_required"]}}}}}},{type:"object",additionalProperties:!1,required:["id","kind","title","binding","mode","onApprove","onReject"],properties:{id:G,kind:{const:"approval"},reminders:gs,title:G,binding:G,mode:{enum:["single","any","all","sequence"]},emptyPolicy:{enum:["block","skip"]},initiatorApprovalPolicy:{enum:["manual","auto_approve"]},completionDeadline:{type:"object",additionalProperties:!1,required:["afterSeconds","action"],properties:{afterSeconds:{type:"integer",minimum:1,maximum:2592e3},action:{const:"approve"}}},onApprove:G,onReject:G,taskPageCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},operationPolicy:{type:"object",additionalProperties:!1,properties:Object.fromEntries(Nt.map(e=>[e,{type:"object",additionalProperties:!1,minProperties:1,properties:{label:{type:"string",minLength:1,maxLength:40,pattern:"^(?!.*[\\u0000-\\u001f\\u007f])(?=.*\\S).*$"},...e!=="save_form"?{opinion:{enum:["none","optional","required"]},minimumOpinion:{enum:["none","optional","required"]}}:{},...["complete","approve","reject"].includes(e)?{commentRequired:{type:"boolean"}}:{},...["transfer","delegate","add_assignee","return"].includes(e)?{reasonRequired:{type:"boolean"}}:{}}}]))},administration:{type:"object",additionalProperties:!1,properties:{modes:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:["single","any","all","sequence"]}},assigneeProviders:{type:"array",minItems:1,maxItems:3,uniqueItems:!0,items:{enum:["fixed_users","app_role","app_role_in_scope"]}},operations:{type:"array",minItems:1,maxItems:8,uniqueItems:!0,items:{enum:[...Nt]}}}},requiredOperations:{type:"array",minItems:1,maxItems:7,uniqueItems:!0,items:{enum:[...Nt]}},allowedOperations:{type:"array",uniqueItems:!0,items:{enum:["approve","reject","return","transfer","delegate","add_assignee","resubmit","save_form","admin_reassign","admin_override"]}},returnPolicy:vc,returnTargets:{type:"array",uniqueItems:!0,items:G},fieldPolicy:{type:"object",additionalProperties:!1,properties:{default:{enum:["hidden","readonly","edit","edit_required"]},fields:{type:"object",additionalProperties:{enum:["hidden","readonly","edit","edit_required"]}}}}}},{type:"object",additionalProperties:!1,required:["id","kind","branches","otherwise"],properties:{id:G,kind:{const:"condition"},title:{type:"string"},branches:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["when","target"],properties:{when:kt,target:G,label:{type:"string"}}}},otherwise:G}},{type:"object",additionalProperties:!1,required:["id","kind","title","outcome"],properties:{id:G,kind:{const:"end"},title:G,outcome:G}},yp,Op,{type:"object",additionalProperties:!1,required:["id","kind","title","taskPageCode","next"],properties:{id:G,kind:{const:"correction"},title:G,reminders:gs,taskPageCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},next:G}}]},hp={$id:ps,type:"object",additionalProperties:!1,required:["schemaVersion","code","title","acceptedCommandDeactivationPolicy","subject","startAt","inputSchema","nodes"],properties:{schemaVersion:{const:ps},authoring:{type:"object",additionalProperties:!1,properties:{peopleSources:{type:"array",maxItems:32,items:{type:"object",additionalProperties:!1,required:["code","title","entry","parameters"],properties:{code:{type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$"},title:Ye(160),entry:Dt,parameters:{type:"object",minProperties:1,maxProperties:8,additionalProperties:{oneOf:[{type:"object",additionalProperties:!1,required:["values"],properties:{values:{type:"array",minItems:1,maxItems:32}}},{type:"object",additionalProperties:!1,required:["minimum","maximum"],properties:{minimum:{type:"integer",minimum:1,maximum:200},maximum:{type:"integer",minimum:1,maximum:200}}}]}}}}},businessSteps:{type:"array",maxItems:100,items:{type:"object",additionalProperties:!1,required:["title","handler","inputSchema","outputSchema"],properties:{title:{type:"string",minLength:1,maxLength:160},handler:{type:"object",additionalProperties:!1,required:["code","version","mode"],properties:{code:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},version:{type:"integer",minimum:1},mode:{enum:["pure","reconciled-effect"]},dataTransaction:{const:!0}}},inputSchema:{type:"object"},outputSchema:{type:"object"}}}}}},code:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},title:G,launchPreflight:{type:"object",additionalProperties:!1,required:["requiredApprovalNodes"],properties:{requiredApprovalNodes:{type:"array",minItems:1,maxItems:20,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"}}}},approvedDelegation:{type:"object",additionalProperties:!1,required:["confirmationNodeId","confirmer","requestsField","maxRequests"],properties:{confirmationNodeId:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},confirmer:{enum:["initiator","delegate"]},requestsField:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},maxRequests:{type:"integer",minimum:1,maximum:500}}},commandHandlers:{type:"object",additionalProperties:!1,minProperties:1,properties:Object.fromEntries(["approve","reject","withdraw","resubmit"].map(e=>[e,{type:"object",additionalProperties:!1,required:["operationCode"],properties:{operationCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"},...e==="approve"?{transitionPolicy:{const:"workflow"}}:{},...e==="resubmit"?{derivedSubjectFields:{type:"array",minItems:1,maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"}}}:{}}}]))},taskPages:{type:"object",minProperties:1,maxProperties:16,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},additionalProperties:{type:"object",additionalProperties:!1,required:["title","fields"],properties:{title:{type:"string",minLength:1,maxLength:160},fields:{type:"array",minItems:1,maxItems:200,items:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},readonly:{type:"boolean"},required:{type:"boolean"},visibleWhen:kt,requiredWhen:kt}}}}}},acceptedCommandDeactivationPolicy:{enum:["finish-pinned","cancel-on-deactivate"]},rejectionNotification:{type:"object",additionalProperties:!1,required:["recipient","title","summary"],properties:{recipient:{const:"record_last_modifier"},title:{type:"string",minLength:1,maxLength:160,pattern:"\\S"},summary:{type:"string",minLength:1,maxLength:500,pattern:"\\S"}}},instanceCommands:{type:"object",additionalProperties:!1,minProperties:1,properties:{withdraw:{type:"object",additionalProperties:!1,minProperties:1,properties:{beforeFact:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},reasonRequired:{type:"boolean"}}},terminate:{type:"object",additionalProperties:!1,required:["capability"],properties:{capability:{type:"string",maxLength:255,pattern:"^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$"},beforeFact:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"}}}}},subject:{type:"object",additionalProperties:!1,required:["resourceCode","factProjection","summaryFields"],properties:{resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},factProjection:{type:"object",minProperties:1,maxProperties:64,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_.]{0,127}$"},additionalProperties:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"}},summaryFields:{type:"array",maxItems:16,uniqueItems:!0,items:Ep}}},startAt:G,inputSchema:{type:"object",required:["type","additionalProperties"],properties:{type:{const:"object"},additionalProperties:{const:!1}}},readability:Ip,organizationContext:{type:"object",additionalProperties:!1,properties:{department:{type:"object",additionalProperties:!1,required:["source"],properties:{source:{enum:["none","user_primary_department","choose_if_multiple","always_choose","fixed","from_input","from_role_scope"]},required:{type:"boolean"},value:{type:"string"},path:{type:"string"},dimension:{type:"string"}}}}},nodes:{type:"object",minProperties:1,maxProperties:200,additionalProperties:bp}}},Np={$id:ms,type:"object",additionalProperties:!1,required:["schemaVersion","workflowCode","bindings"],properties:{schemaVersion:{const:ms},workflowCode:G,bindings:{type:"object",maxProperties:200,additionalProperties:{oneOf:[Dt,Sr]}}}};var gr=["definition.read","draft.edit","publication.publish","handling.configure"],Ty=2,wp={memberships:400,grants:512,targets:200,receiptGrantIds:8};function Cy(e){let t=new Set(e.filter(o=>gr.includes(o)));return t.size&&t.add("definition.read"),gr.filter(o=>t.has(o))}function Sy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,o=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,n=/^[a-z][a-z0-9_-]{0,127}$/;return typeof t.subjectRoleCode=="string"&&t.subjectRoleCode.length<=100&&o.test(t.subjectRoleCode)&&typeof t.manageAllWorkflows=="boolean"&&Array.isArray(t.managedWorkflowCodes)&&t.managedWorkflowCodes.length<=wp.targets&&(t.manageAllWorkflows?t.managedWorkflowCodes.length===0:t.managedWorkflowCodes.length>0)&&t.managedWorkflowCodes.every(r=>typeof r=="string"&&n.test(r))&&new Set(t.managedWorkflowCodes).size===t.managedWorkflowCodes.length&&Array.isArray(t.actions)&&t.actions.length>0&&t.actions.length<=gr.length&&t.actions.every(r=>gr.includes(r))&&new Set(t.actions).size===t.actions.length&&typeof t.reason=="string"&&t.reason.trim().length>0&&t.reason.length<=1e3&&Object.keys(t).every(r=>["subjectRoleCode","manageAllWorkflows","managedWorkflowCodes","actions","reason"].includes(r))}var ky=316224e5;function Rp(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===2&&e.kind==="database-accepted-time"&&Object.hasOwn(e,"offsetMilliseconds")&&Number.isSafeInteger(e.offsetMilliseconds)&&Math.abs(e.offsetMilliseconds)<=316224e5}function Ly(e=0){let t={kind:"database-accepted-time",offsetMilliseconds:e};if(!Rp(t))throw new Error("DATA_TRANSACTION_ACCEPTED_TIME_VALUE_INVALID");return t}var Py="1123bb1c3cad888fcfc165693a6ee145809f729d64994e68b55fad023f9cb197";export{Ca as APPLICATION_AGENT_LIMITS_V2,kn as AuthenticatedPublicReadContractError,_o as DATA_AUDIT_METADATA_FIELDS,zE as DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,Xf as DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,qE as DATA_BUSINESS_COMMAND_SCHEMA,zi as DATA_EVENT_TYPES_V2,Lm as DATA_FORM_DRAFT_MAX_BYTES,uo as DATA_RESOURCE_MAX_FIELDS,Fr as DATA_SUBTABLE_DEFAULT_TOTAL_ROWS,lt as DATA_SUBTABLE_MAX_ROWS,en as DATA_SUBTABLE_MAX_TOTAL_ROWS,ml as DATA_SYSTEM_SORT_FIELD_CODES,km as DATA_TRANSACTION_MAX_BYTES,Ks as DATA_TRANSACTION_MAX_OPERATIONS,Zf as DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,ky as DATA_TRANSACTION_TIME_MAX_OFFSET_MILLISECONDS,eA as DATE_EVENT_RESERVED_DATA_FIELDS_V2,yI as DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,OI as DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,fI as DEVELOPMENT_BACKEND_FEATURE,mI as DEVELOPMENT_BACKEND_INVOCATION_FEATURE,gI as DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,_I as DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,np as DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,II as DEVELOPMENT_BACKEND_MAX_INFLIGHT,EI as DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,AI as DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,pI as DEVELOPMENT_BACKEND_SCHEMA,aI as DEVELOPMENT_CONFIGURATION_ENDPOINT,sI as DEVELOPMENT_CONFIGURATION_FEATURE,Ic as DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,ep as DEVELOPMENT_CONFIGURATION_SCHEMA,Ko as DateEventProjectionV2Error,ss as DevelopmentConfigurationContractError,wi as EventWorkerEffectContractError,nu as FIELD_VALUE_SCHEMAS,wn as ManagedConcurrencyContractError,_e as NATIVE_ARTIFACT_CAPACITY_V2,Py as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,q as NATIVE_CONTRACT_CAPACITY_V2,Kg as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Ug as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Mg as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Bg as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,qg as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,gl as NATIVE_DATA_QUERY_OPERATORS_V2,ya as NATIVE_DIRECTORY_ROLE_SOURCE_LIMITS,fn as NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2,$E as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,PE as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,n_ as NATIVE_UNIQUE_KEY_MAX_BYTES,Ba as NATIVE_UNIQUE_KEY_NORMALIZERS,gr as NATIVE_WORKFLOW_MANAGEMENT_ACTIONS,mi as NativeApplicationAgentContractError,Gi as NativeConfigurationCompilerError,We as NativeDataFieldContractV2Error,Dn as NativeDataPolicyExpressionV2Error,rn as NativeDecimalLifecycleContractError,xo as NativeEventActionContractError,Cn as NativeOrganizationAuthorizationError,Te as NativeParentReadPolicyError,es as NativeRoleMembershipBatchInputError,di as NativeScopeSourceFieldPathV2Error,vn as NativeUniqueKeyContractError,rl as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,It as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,Zr as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,zr as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,tn as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,RI as RICH_TEXT_POLICY_V2,Cm as USER_CANDIDATE_MAX_SELECTIONS,nl as USER_CANDIDATE_SCOPE_FIELD_TYPES,$t as UserCandidateContractError,sd as WORKFLOW_APPROVAL_EMPTY_PROVIDERS,H_ as WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,J_ as WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,nd as WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS,od as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,_u as WORKFLOW_AUTOMATIC_CC_PROVIDERS,Ir as WORKFLOW_BUSINESS_STEP_EVENT,Vp as WORKFLOW_BUSINESS_STEP_EVENTS,Wp as WORKFLOW_BUSINESS_STEP_FACTS_KEY,br as WORKFLOW_BUSINESS_STEP_MAX_BYTES,xc as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,yn as WORKFLOW_CONDITIONAL_ASSIGNMENT_LEAF_PROVIDERS,Cr as WORKFLOW_CONDITIONAL_ASSIGNMENT_MAX_BYTES,no as WORKFLOW_CONDITIONAL_ASSIGNMENT_MAX_CASES,Nt as WORKFLOW_CONFIGURABLE_OPERATIONS,Bo as WORKFLOW_CONFIGURABLE_PROVIDERS,Ty as WORKFLOW_DESIGNER_CLIENT_CONTRACT,Mn as WORKFLOW_EVENT_TYPES_V2,Vr as WORKFLOW_LAUNCH_MAX_INPUTS,hu as WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,wp as WORKFLOW_MANAGEMENT_LIMITS,lu as WORKFLOW_PARALLEL_MAX_BRANCHES,cu as WORKFLOW_PARALLEL_MIN_BRANCHES,vp as WORKFLOW_PLATFORM_NOTIFY_CAPABILITY,Fc as WORKFLOW_PLATFORM_NOTIFY_HANDLER,Vc as WORKFLOW_PLATFORM_NOTIFY_INPUT_SCHEMA,Wc as WORKFLOW_PLATFORM_NOTIFY_OUTPUT_SCHEMA,x_ as WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,bu as WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,Sp as WORKFLOW_ROLE_UNION_MAX_ROLES,Jp as WORKFLOW_ROUTING_MAX_BYTES,Gp as WORKFLOW_ROUTING_MAX_MATCHED_RULES,zp as WORKFLOW_ROUTING_MAX_RULES,fp as WORKFLOW_SOURCE_BUNDLE_MAX_BYTES,kc as WORKFLOW_SOURCE_BUNDLE_SCHEMA,us as WORKFLOW_SOURCE_BUNDLE_V2_SCHEMA,kE as WORKFLOW_STEP_DATA_COMMAND_SCHEMA,Gf as WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA,Cu as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,Vi as WORKFLOW_TASK_PAGE_MAX_BYTES,Tu as WORKFLOW_TASK_PAGE_MAX_FIELDS,yd as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,Ed as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,st as WorkflowTaskPageError,Su as applyWorkflowTaskPageValues,iA as applyWorkflowTaskSubtableRows,ou as assertApplicationAgentInstructionPathV2,tp as assertDevelopmentConfigurationManifest,lI as assertDevelopmentConfigurationResult,FE as assertNativeRoleMembershipBatchInput,Hg as assertWorkflowNativeStageGuard,ja as assertWorkflowNativeStagePolicy,Yg as assertWorkflowNativeStageSourceGuard,Go as assertWorkflowOwnedSubjectCreate,wd as assertWorkflowOwnedSubjectCreateResources,up as buildResourceWhere,GE as canonicalDataBusinessIntent,JI as classifyWorkflowAdoption,my as classifyWorkflowSourceDeployment,fr as compileAdvancedWhere,Sa as compileApplicationAgentsV2,Ya as compileEventWorkerEffect,wE as compileNativeApplicationConfiguration,Xa as compileNativeEventAction,ef as compileNativeEventCapturePlansV2,Qu as compileRequiredPlatformCapabilitiesV3,Nr as compileWorkflowBusinessStepHandlers,dI as createDevelopmentConfigurationManifest,cp as createWorkflowHumanNode,fo as dataOwnedRowLimit,Ly as databaseAcceptedTime,tA as dateEventProjectionEnvelopeSchemaV2,Ad as dateEventProjectionFieldsV2,fi as departmentReferenceValueSchema,op as developmentBackendBase64Bytes,ap as developmentBackendInvocationHeadersValid,NI as developmentBackendInvocationRequestValid,hI as developmentBackendInvocationRevision,rp as developmentBackendOperationMatches,cI as developmentConfigurationKey,bg as directoryRoleSourceSchema,lp as editWorkflowDesignerDefinition,vs as evaluateWorkflowExpression,wt as evaluateWorkflowTaskPageExpression,u_ as eventWorkerEffectSignatureContent,Ro as fieldValueSchemaForDefinition,V_ as formatWorkflowCompletionDeadline,jo as formatWorkflowExpression,Kp as formatWorkflowSupervisorChain,Cd as generatedCrudCapabilityOperations,Qs as hasDataAuditReadPolicy,yi as hasNativeParentReadPolicy,rt as inspectWorkflowParallel,Vt as isDataAuditMetadataField,On as isDataOwnedRowLimit,Ao as isDataSystemSortField,Rp as isDataTransactionAcceptedTimeValue,YE as isDataTransactionActorAuthorityGuard,nI as isDataTransactionRecordSetMatchGuard,jm as isNativeDataQueryOperatorV2,go as isNativeMultiValueFieldV2,Sy as isWorkflowManagementGrantRequest,ie as isWorkflowPlatformNotify,j_ as isWorkflowRejectionNotificationSnapshot,XE as matchesDataActorAuthorityMembership,Ig as materializeNativeDataQueryPathTypesV2,Na as nativeAgentFieldHintSchemaV2,au as nativeAgentFieldSelectorV2,an as nativeDataPolicyExpressionLeavesV2,ka as nativeDataPolicyExpressionToCnfV2,yg as nativeDataQueryPathPlanV2,Mm as nativeFieldAggregatePlanV2,dg as nativeFieldColumnDefinitionV2,cg as nativeFieldDefaultSqlV2,lg as nativeFieldHasDefaultV2,mg as nativeFieldIndexStatementsV2,Et as nativeFieldRequiresCreateInputV2,pg as nativeFieldSequenceGrantStatementsV2,fg as nativeFieldSequenceOwnershipStatementsV2,ug as nativeFieldSequenceStatementsV2,oa as nativeFieldSupportsFilterV2,Um as nativeFieldSupportsOperatorV2,Yr as nativeFieldSupportsSearchV2,Nn as nativeFieldSupportsSortV2,na as nativeOperatorsForFieldV2,Vl as nativePhysicalFieldV2,ag as nativePhysicalFieldsV2,yt as nativePhysicalObjectNameV2,Ag as nativeScopeSourceFieldValueV2,Ea as nativeScopeSourceGrantPathSupportedV2,ci as nativeScopeSourceSubjectPathSupportedV2,gg as nativeSubtableConstraintStatementsV2,qa as nativeUniqueKeysContractVersion,o_ as nativeUniqueKeysJsonSchema,Ei as normalizeDataMutationGrants,uA as normalizeWorkflowOwnedSubjectCreate,JE as parseDataBusinessCommandResolution,lo as parseDataFieldUserCandidates,si as parseDecimalReservationLifecycle,bn as parseNativeDataFieldsV2,Zs as parseNativeDataResourceInvariantsV2,pu as parseNativeParentReadPolicy,Ka as parseNativeUniqueKeys,LE as parseWorkflowStepDataResolution,pi as projectDataResourceView,ni as projectNativeDataResourceViewV2,v_ as projectWorkflowConfiguredAssignment,Mo as projectWorkflowGraph,rd as projectWorkflowNodePolicy,oy as projectWorkflowSourceAssignment,FI as pruneWorkflowCanvasBindings,Re as quoteNativeIdentifierV2,sA as refreshWorkflowTaskPageFacts,xr as requiresAggregateOwnedSubtableCapacity,Kr as requiresDateTimeMinutePrecision,bI as requiresDevelopmentBackendCredential,Jo as requiresExtendedArtifactCapacity,Mi as requiresExtendedConfigurationBytes,Ui as requiresExtendedDeclarationCapacity,Wr as requiresExtendedFieldCapacity,jr as requiresExtendedOwnedSubtableCapacity,ji as requiresExtendedRoleCapacity,Ho as requiresHighDensityArtifactCapacity,qr as requiresOwnedSubtableMinimumRows,$r as requiresUserCandidateLaunchScope,kp as requiresWorkflowRoleInputSelection,Dp as requiresWorkflowRoleUnion,$o as resolveNativeParentReadBinding,Rn as resolveNativeScopeSourceFieldPathV2,K_ as resolveWorkflowCommandHandler,ol as resolveWorkflowUserCandidates,ba as resourceReferenceValueSchema,ry as restoreWorkflowSourceAssignment,Xp as selectWorkflowAssignmentRoutingRules,Nm as selectWorkflowConditionalAssignment,vm as serializedDataBytes,Sm as userCandidateScopeValue,li as userReferenceValueSchema,Ma as validateAuthenticatedPublicRead,fa as validateDecimalReservationLifecycles,l_ as validateEventWorkerMutationPlan,c_ as validateEventWorkerQuery,la as validateManagedConcurrency,sa as validateNativeDataDraftStateV2,Xs as validateNativeDataResourceReferencesV2,ti as validateNativeDataResourceSurfaceV2,Oa as validateNativeOrganizationAuthorization,$a as validateNativeParentReadPolicies,Ms as validateUserCandidateReferences,ki as validateWorkflowAdministration,Li as validateWorkflowApprovalEmptyPolicy,gd as validateWorkflowApprovedDelegation,Lr as validateWorkflowAssignmentLeafFacts,Ts as validateWorkflowAssignmentRoutingBindings,Yt as validateWorkflowAssignmentRoutingPolicy,Hp as validateWorkflowAssignmentRoutingRules,Mc as validateWorkflowAuthoringSteps,Si as validateWorkflowAutomaticCc,jp as validateWorkflowBusinessStepHandlerContract,xp as validateWorkflowBusinessStepRequest,jc as validateWorkflowBusinessStepResult,Jt as validateWorkflowBusinessStepSchema,bs as validateWorkflowBusinessStepSubscriptions,eo as validateWorkflowBusinessSteps,hc as validateWorkflowCanvasBinding,bc as validateWorkflowCanvasHuman,fd as validateWorkflowCommandHandlers,cd as validateWorkflowCompletionDeadlines,Zt as validateWorkflowConditionalAssignment,ke as validateWorkflowConditionalAssignmentShape,Xt as validateWorkflowConditionalBindingDefinition,_d as validateWorkflowCorrections,wc as validateWorkflowDesignerCapabilities,as as validateWorkflowDesignerDocument,Po as validateWorkflowHandlingNodes,Vn as validateWorkflowInitiatorApprovalPolicy,Qa as validateWorkflowInstanceCommandPolicies,Pi as validateWorkflowLaunchPreflight,Di as validateWorkflowNodeConfigurationPatch,vo as validateWorkflowParallel,Ls as validateWorkflowPeopleSourceTemplates,Qn as validateWorkflowPlatformNotify,ed as validateWorkflowReadability,ud as validateWorkflowRejectionNotification,Do as validateWorkflowReminders,yc as validateWorkflowReturnEligibility,ko as validateWorkflowReturnPolicies,Xn as validateWorkflowRoleInputSelection,qt as validateWorkflowRoleUnion,Dc as validateWorkflowSourceAssignment,gp as validateWorkflowSourceBundle,Lt as validateWorkflowStandardAssignment,Ht as validateWorkflowSupervisorChainBinding,At as validateWorkflowSupervisorChains,zo as validateWorkflowTaskPages,Bs as validateWorkflowUserCandidateBindings,$_ as workflowApprovalCanSkip,Y_ as workflowApprovedDelegationRequests,co as workflowAssignmentLeafBinding,ae as workflowAssignmentLeaves,Yp as workflowAssignmentRoutingFacts,Rs as workflowAssignmentRoutingPolicySchema,Gc as workflowAssignmentRoutingSemantic,dr as workflowAuthoringCatalog,ad as workflowBindingAllowsEmptyUsers,Yn as workflowBindingRoleCodes,Np as workflowBindingSchema,B_ as workflowBusinessCommandInvocationSchema,_t as workflowBusinessStepFactSchema,BE as workflowBusinessStepHandlerDigest,Up as workflowBusinessStepInput,Uc as workflowBusinessStepPath,ME as workflowBusinessStepReceiptSignatureSuffix,Gt as workflowBusinessStepValueMatches,zn as workflowCanvasBindingKey,so as workflowConditionalAssignmentFact,Sr as workflowConditionalAssignmentSchema,hp as workflowDefinitionSchema,Hf as workflowDelegationMutationRequestSchema,lr as workflowDesignerTargets,HI as workflowDesignerVariables,Fn as workflowExpressionPaths,Lo as workflowForwardTargets,Oc as workflowHumanOperations,w_ as workflowInitiatorApprovalCanComplete,E_ as workflowInstanceCommandDeadlineError,__ as workflowInstanceTerminateCapabilityAllowed,A_ as workflowInstanceWithdrawalReasonRequired,Cy as workflowManagementActions,Xg as workflowNativeStagePolicySchema,cn as workflowNodeAllowedOperations,Ou as workflowNodeAssignmentUsesReleasedSource,Pp as workflowNotificationBinding,Eu as workflowOperationCommentRequired,ln as workflowOperationMinimumOpinion,xt as workflowOperationOpinion,Iu as workflowOperationReasonRequired,lA as workflowOwnedSubjectCreateSchema,io as workflowPeopleSourceTemplateAllows,Xc as workflowPeopleSourceTemplateMatches,Za as workflowPolicyTimestamp,Vg as workflowPositionActive,Bi as workflowProducedEventTypes,dp as workflowReturnEligibility,Pg as workflowReturnTargetPolicy,ot as workflowReturnTargets,_s as workflowRoleCodesSchema,mt as workflowSourceDigestEqual,gy as workflowSourceImportDrift,iy as workflowSourceNamedAssignmentSummary,mp as workflowSourceReferences,py as workflowSourceStatus,hd as workflowTaskPageFieldState,aA as workflowTaskPageReplayCoversInvalidation,L_ as workflowTaskSaveEnabled,rA as workflowTaskSubtableRows,gu as workflowVariableLabel};
8
+ END $native_subtable$`]}function yt(e,...t){return`${e}_${vl("sha256").update(t.join(":")).digest("hex").slice(0,32)}`}function Re(e){if(!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(e))throw new Error("OPENXIANGDA_NATIVE_IDENTIFIER_INVALID");return`"${e}"`}function xl(e,t){return e.type==="subtable"?"none":t?"gin-trigram":e.indexed?["date-range","datetime-range"].includes(e.type)?"gist-range":ai.has(e.type)?"btree-snapshot-expressions":Pl.has(e.type)?"gin-jsonb-path":"btree":"none"}function jl(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 Fl.has(e.type),"jsonb"}}function ga(e,t){if(go(t.type)&&t.type!=="subtable")return"'[]'::jsonb";if(t.type!=="serial-number")return"";let n=pa(t.serial?.prefix||""),o=t.serial?.digits??6;return`(${n} || lpad(nextval(${pa(ho(e,t.code))})::text, ${o}, '0'))`}function Ul(e,t){return ma.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'array')`:$l.has(t.type)?` CHECK (${e} IS NULL OR jsonb_typeof(${e}) = 'object')`:""}function bo(e){return`"app_data".${Re(e)}`}function ho(e,t){let n=yt("seq",e,t);return`"app_data".${Re(n)}`}function pa(e){return`'${e.replace(/'/g,"''")}'`}var _a=new Set(["option.single","option.multiple","user.single","user.multiple","department.single","department.multiple","resource-ref.single","resource-ref.multiple"]),Ml=new Set([..._a,"cascade.single","cascade.multiple","file","image","signature","address","location","json"]),Aa=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Bl=new Set(["__proto__","prototype","constructor"]),di=class extends Error{constructor(n){super("OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID");this.path=n;this.name="NativeScopeSourceFieldPathV2Error"}path;code="OPENXIANGDA_SCOPE_PROJECTION_FIELD_PATH_INVALID"};function Rn(e,t){let n=Ia(e);if(!n)return null;let o=t.get(n[0]);if(!o)return null;let r=n.slice(1).join(".")||void 0;return{field:o,...r?{valuePath:r}:{}}}function ci(e){return!!(e&&e.field.type==="user.single"&&e.valuePath==="value")}function Ea(e,t,n){if(!e||!t||!Kl(e))return!1;let{field:o,valuePath:r}=e;if(!r)return t.valueType==="uuid"?o.type==="uuid":["text.short","text.long","serial-number"].includes(o.type);if(r==="value")return!(t.valueSourceResourceCode&&o.type.startsWith("resource-ref.")&&o.source?.resourceCode!==t.valueSourceResourceCode);let i=r.slice(9),a=n.get(o.source?.resourceCode||"")?.get(i)?.type;return t.valueType==="uuid"?a==="uuid":["text.short","text.long","serial-number"].includes(a||"")}function Ag(e,t){let n=Ia(t);if(!n)throw new di(String(t||""));let o=e;for(let r of n){if(!o||typeof o!="object"||!Object.prototype.hasOwnProperty.call(o,r))return;o=o[r]}return o}function Kl(e){let{field:t,valuePath:n}=e;if(!n)return!Ml.has(t.type);if(n==="value")return _a.has(t.type);if(!n.startsWith("snapshot."))return!1;let o=n.slice(9);return Aa.test(o)&&t.type.startsWith("resource-ref.")&&!!t.source?.snapshotFields?.includes(o)}function Ia(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(n=>!Aa.test(n)||Bl.has(n))||t.length===2&&t[1]!=="value"||t.length===3&&t[1]!=="snapshot"?null:t}var ql=new Set(["option.single","user.single","department.single","resource-ref.single"]),zl=new Set(["text.short","text.long","text.rich","number.integer","number.decimal","boolean","date","time","datetime","uuid","serial-number"]),Gl=new Set(["value","label","description","color"]),Jl=new Set(["avatarUrl","employeeNo","title","mobile","email"]),Hl=new Set(["fullPath","parent.value","parent.label"]),Yl=new Set(["country.value","country.label","province.value","province.label","city.value","city.label","district.value","district.label","street.value","street.label","detail","fullAddress"]),Xl=new Set(["longitude","latitude","accuracy"]),Zl=new Set(["address","name","province","city","district","source"]);function Ig(e){let t=new Map(e.map(n=>[n.code,new Map(n.schema.fields.map(o=>[o.code,o]))]));return e.map(n=>({...n,schema:{...n.schema,fields:n.schema.fields.map(o=>{let r=Ql(o,t);if(!Object.keys(r).length)return o;let i={...o};return Object.defineProperty(i,"queryPathTypes",{configurable:!1,enumerable:!1,writable:!1,value:Object.freeze(r)}),i})}}))}function yg(e,t){if(ql.has(e.type)&&Gl.has(t)||e.type==="user.single"&&Jl.has(t)||e.type==="department.single"&&Hl.has(t))return Tn(t);if(e.type==="resource-ref.single"){let n=e.queryPathTypes?.[t];return n?{parts:t.split("."),type:n}:null}if(e.type==="address"&&Yl.has(t))return Tn(t);if(e.type==="location"){if(Xl.has(t))return{parts:[t],type:"number.decimal"};if(Zl.has(t))return Tn(t);if(t==="capturedAt")return{parts:[t],type:"datetime"}}return null}function Ql(e,t){if(e.type!=="resource-ref.single"||!e.source)return{};let n=t.get(e.source.resourceCode);return n?Object.fromEntries((e.source.snapshotFields||[]).flatMap(o=>{let r=n.get(o);return r?[[`snapshot.${o}`,zl.has(r.type)?r.type:"json"]]:[]})):{}}function Tn(e){return{parts:e.split("."),type:"text.short"}}var ya={sources:32,scopes:16,facts:512},Cn=class extends Error{constructor(n,o){super(n);this.code=n;this.pointer=o}code;pointer},nt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},le=(e,t)=>{throw new Cn(e,t)},sn=(e,t,n=100)=>((typeof e!="string"||e.length>n||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(e))&&le("NATIVE_DIRECTORY_ROLE_IDENTIFIER_INVALID",t),e),bg={type:"object",additionalProperties:!1,required:["code","name","source","roleFactCode","roleCode","scopes","failureMode"],properties:{code:{type:"string",minLength:1,maxLength:100},name:{type:"string",minLength:1,maxLength:255},source:{type:"string",minLength:1,maxLength:64},roleFactCode:{type:"string",minLength:1,maxLength:64},roleCode:{type:"string",minLength:1,maxLength:128},failureMode:{const:"strict"},scopes:{type:"array",maxItems:16,items:{type:"object",additionalProperties:!1,required:["dimensionCode","scopeType","operations"],properties:{dimensionCode:{type:"string",minLength:1,maxLength:100},scopeType:{type:"string",minLength:1,maxLength:64},operations:{type:"array",minItems:1,maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:64}}}}}}};function Oa(e,t="/config"){let n=nt(e),o=nt(n.authz),r=nt(n.data),i=Array.isArray(o.roles)?o.roles.map(nt):[],s=new Map((Array.isArray(o.scopeDimensions)?o.scopeDimensions:[]).map(c=>{let l=nt(c);return[l.code,l]}));for(let[c,l]of i.entries())l.organizationReach!==void 0&&!["self","subtree"].includes(l.organizationReach)&&le("NATIVE_ORGANIZATION_REACH_INVALID",`${t}/authz/roles/${c}/organizationReach`),l.organizationReach!==void 0&&l.code===o.authenticatedUserRoleCode&&le("NATIVE_ORGANIZATION_BASELINE_ROLE_FORBIDDEN",`${t}/authz/authenticatedUserRoleCode`);let a=o.directoryRoleSources;a!==void 0&&(!Array.isArray(a)||a.length>ya.sources)&&le("NATIVE_DIRECTORY_ROLE_SOURCE_CAPACITY",`${t}/authz/directoryRoleSources`);let d=new Set;for(let[c,l]of(a||[]).entries()){let f=nt(l),p=`${t}/authz/directoryRoleSources/${c}`;Object.keys(f).some(O=>!["code","name","source","roleFactCode","roleCode","scopes","failureMode"].includes(O))&&le("NATIVE_DIRECTORY_ROLE_SOURCE_INVALID",p);let m=sn(f.code,`${p}/code`);d.has(m)&&le("NATIVE_DIRECTORY_ROLE_SOURCE_DUPLICATE",`${p}/code`),d.add(m),(typeof f.name!="string"||!f.name.trim()||f.name.length>255||f.failureMode!=="strict")&&le("NATIVE_DIRECTORY_ROLE_SOURCE_INVALID",p),sn(f.source,`${p}/source`,64),sn(f.roleFactCode,`${p}/roleFactCode`,64);let A=i.find(O=>O.code===f.roleCode);(!A||A.organizationReach!=="self")&&le("NATIVE_DIRECTORY_ROLE_REQUIRES_SELF",`${p}/roleCode`),(Array.isArray(o.roleMembershipSources)?o.roleMembershipSources:[]).some(O=>nt(O).roleCode===f.roleCode)&&le("NATIVE_DIRECTORY_ROLE_OWNER_CONFLICT",`${p}/roleCode`),(!Array.isArray(f.scopes)||f.scopes.length>ya.scopes)&&le("NATIVE_DIRECTORY_ROLE_SCOPES_INVALID",`${p}/scopes`);let I=new Set;for(let[O,b]of f.scopes.entries()){let g=nt(b),y=`${p}/scopes/${O}`;Object.keys(g).some(E=>!["dimensionCode","scopeType","operations"].includes(E))&&le("NATIVE_DIRECTORY_ROLE_SCOPES_INVALID",y);let h=sn(g.dimensionCode,`${y}/dimensionCode`),u=s.get(h);(!u||(u.valueType||"string")!=="string"||u.valueSource||u.resourceCode||u.hierarchyMode&&u.hierarchyMode!=="flat")&&le("NATIVE_DIRECTORY_ROLE_STRING_DIMENSION_REQUIRED",`${y}/dimensionCode`),I.has(h)&&le("NATIVE_DIRECTORY_ROLE_SCOPE_DUPLICATE",y),I.add(h),sn(g.scopeType,`${y}/scopeType`,64),(!Array.isArray(g.operations)||!g.operations.length||g.operations.length>16||new Set(g.operations).size!==g.operations.length)&&le("NATIVE_DIRECTORY_ROLE_OPERATIONS_INVALID",`${y}/operations`);for(let[E,w]of g.operations.entries())sn(w,`${y}/operations/${E}`,64)}}for(let[c,l]of(Array.isArray(r.resources)?r.resources:[]).entries()){let f=nt(l),p=f.organization;if(p===void 0)continue;let m=`${t}/data/resources/${c}/organization`;if((!p||typeof p!="object"||Array.isArray(p)||Object.keys(p).some(I=>I!=="mode")||!["none","owned","inherited-down"].includes(p.mode))&&le("NATIVE_ORGANIZATION_POLICY_INVALID",m),p.mode==="none")continue;let A=f.schema?.fields||f.fields||[];A.some(I=>I.code==="organization_id")&&le("NATIVE_ORGANIZATION_COLUMN_RESERVED",m);for(let I of A){if(I.type!=="subtable"||!I.subtable?.resourceCode)continue;let O=r.resources.find(b=>b.code===I.subtable.resourceCode);(!O||!["owned","inherited-down"].includes(O.organization?.mode))&&le("NATIVE_SUBTABLE_ORGANIZATION_POLICY_REQUIRED",m)}for(let I of i){if(I.organizationReach)continue;let O=Array.isArray(I.capabilities)?I.capabilities:[];Object.values(nt(f.capabilities)).some(b=>O.includes(b))&&le("NATIVE_ORGANIZATION_ROLE_REACH_REQUIRED",`${t}/authz/roles/${i.indexOf(I)}/organizationReach`)}(f.surface?.public||f.surface?.publicRead)&&le("NATIVE_ORGANIZATION_PUBLIC_CONTEXT_UNSUPPORTED",m)}}var wo={type:"string",minLength:1},je={type:"object",additionalProperties:!1,required:["label","value"],properties:{label:{type:"string",minLength:1,maxLength:500},value:{type:"string",minLength:1,maxLength:500},description:{type:"string",maxLength:2e3},color:{type:"string",maxLength:64}}},fi={type:"object",additionalProperties:!1,required:["label","value"],properties:{...je.properties,fullPath:{type:"string",maxLength:4e3},path:{type:"array",maxItems:20,items:je},parent:je}},li={type:"object",additionalProperties:!1,required:["label","value"],properties:{...je.properties,avatarUrl:{type:"string",maxLength:4e3},employeeNo:{type:"string",maxLength:200},title:{type:"string",maxLength:500},mobile:{type:"string",maxLength:100},email:{type:"string",maxLength:500},departments:{type:"array",maxItems:20,items:fi}}},ba={type:"object",additionalProperties:!1,required:["label","value","resourceCode"],properties:{...je.properties,resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},snapshot:{type:"object",maxProperties:50,additionalProperties:!0}}},No={type:"object",additionalProperties:!1,required:["schemaVersion","id","name","size","contentType"],properties:{schemaVersion:{const:"openxiangda.data-file-ref/v2"},id:wo,name:{type:"string",minLength:1,maxLength:1e3},size:{type:"integer",minimum:0},contentType:{type:"string",minLength:1,maxLength:500}}},eu={type:"object",additionalProperties:!1,required:["id","name","size","contentType"],properties:{id:wo,name:{type:"string",minLength:1,maxLength:1e3},size:{type:"integer",minimum:0},contentType:{type:"string",minLength:1,maxLength:500}}},ha={type:"object",additionalProperties:!1,required:["start","end"],properties:{start:wo,end:wo}},ui={type:"array",maxItems:100,items:je},tu={longitude:{type:"number",minimum:-180,maximum:180},latitude:{type:"number",minimum:-90,maximum:90},address:{type:"string",maxLength:8e3},name:{type:"string",maxLength:2e3},province:{type:"string",maxLength:500},city:{type:"string",maxLength:500},district:{type:"string",maxLength:500},accuracy:{type:"number",minimum:0},source:{enum:["browser","dingTalk"]},capturedAt:{type:"string",format:"date-time"}},nu={"text.short":{type:"string",maxLength:1e6},"text.long":{type:"string",maxLength:1e6},"text.rich":{type:"string",maxLength:1e6},"number.integer":{type:"integer"},"number.decimal":{type:"number"},boolean:{type:"boolean"},date:{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"},time:{type:"string",pattern:"^(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d)?$"},datetime:{type:"string",format:"date-time"},"date-range":ha,"datetime-range":ha,"option.single":je,"option.multiple":ui,"cascade.single":ui,"cascade.multiple":{type:"array",maxItems:100,items:ui},"user.single":li,"user.multiple":{type:"array",maxItems:100,items:li},"department.single":fi,"department.multiple":{type:"array",maxItems:100,items:fi},"resource-ref.single":ba,"resource-ref.multiple":{type:"array",maxItems:100,items:ba},image:{type:"array",maxItems:100,items:{...No,required:[...No.required,"width","height","thumbnailUrl","previewUrl"],properties:{...No.properties,width:{type:"integer",minimum:1},height:{type:"integer",minimum:1},thumbnailUrl:{type:"string",maxLength:4e3},previewUrl:{type:"string",maxLength:4e3}}}},signature:{type:"object",additionalProperties:!1,required:["file","signedAt","hash"],properties:{file:eu,signer:li,signedAt:{type:"string",format:"date-time"},points:{type:"array",maxItems:2e4,items:{type:"object",additionalProperties:!1,required:["x","y","t"],properties:{x:{type:"number"},y:{type:"number"},t:{type:"number"}}}},hash:{type:"string",pattern:"^[0-9a-f]{64}$"}}},address:{type:"object",additionalProperties:!1,properties:{country:je,province:je,city:je,district:je,street:je,detail:{type:"string",maxLength:4e3},fullAddress:{type:"string",maxLength:8e3}}},location:{type:"object",additionalProperties:!1,required:["source","longitude","latitude"],properties:tu},uuid:{type:"string",format:"uuid"},json:{},file:{type:"array",maxItems:100,items:No},"serial-number":{type:"string",minLength:1,maxLength:255},subtable:{type:"array",maxItems:lt,items:{type:"object",additionalProperties:!0}}};function Ro(e){if(e.type==="number.decimal"&&e.exactDecimal===!0){let r=e.precision,i=e.scale;if(typeof r=="number"&&typeof i=="number"&&Number.isInteger(r)&&Number.isInteger(i)&&r>=1&&i>=0&&i<=r){let s=Math.max(1,r-i),a=i>0?`(?:\\.[0-9]{1,${i}})?`:"";return{type:"string",pattern:`^-?(?:0|[1-9][0-9]{0,${s-1}})${a}$`,maxLength:s+(i>0?i+1:0)+1}}return{type:"string",pattern:"^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?$"}}let t=JSON.parse(JSON.stringify(nu[e.type]));if(e.type!=="date-range"&&e.type!=="datetime-range")return t;if(!["closed","half-open"].includes(String(e.rangeBoundary)))throw new Error("DATA_RESOURCE_FIELD_RANGE_BOUNDARY_REQUIRED");let n=e.rangeBoundary;t["x-openxiangda-range-boundary"]=n;let o=e.type==="date-range"?{type:"string",pattern:"^\\d{4}-\\d{2}-\\d{2}$"}:{type:"string",format:"date-time"};return t.properties={start:o,end:o},t.description=n==="closed"?"Closed interval: start <= end; both start and end are included.":"Half-open interval: start < end; start is included and end is excluded.",t}function pi(e,t){if(t===void 0)return e;let n=e.views?.find(s=>s.code===t);if(!n)throw new Error(`DATA_RESOURCE_VIEW_NOT_FOUND: ${t}`);let o=new Map(n.sections?.flatMap(s=>s.fields.map(a=>[a,s.title]))),{views:r,...i}=e;return{...i,generated:n.generated,list:n.list,form:n.form,detail:n.detail,mobile:n.mobile,fields:Object.fromEntries(Object.entries(e.fields).map(([s,a])=>{let{section:d,...c}=a,l=o.get(s);return[s,{...c,...l?{section:l}:{},list:n.list.fieldOrder?.includes(s)??!1}]}))}}var Ca=Object.freeze({agents:20,tasks:20,fields:20,instructions:16e3,instructionBytes:64e3,arrayItems:50,pages:10}),mi=class extends Error{constructor(n,o,r){super(`${n}: ${o}: ${r}`);this.code=n;this.pointer=o;this.name="NativeApplicationAgentContractError"}code;pointer};function z(e,t,n){throw new mi(`NATIVE_APPLICATION_AGENT_${e}`,t,n)}function gi(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&z("OBJECT_REQUIRED",t,"\u9700\u8981\u5BF9\u8C61"),e}function _i(e,t,n){for(let o of Object.keys(e))t.includes(o)||z("PROPERTY_UNSUPPORTED",`${n}/${o}`,"\u672A\u77E5\u5C5E\u6027")}function Ot(e,t,n){return(typeof e!="string"||!e.trim()||e.length>t)&&z("TEXT_INVALID",n,`\u9700\u8981\u975E\u7A7A\u5B57\u7B26\u4E32\uFF0C\u6700\u591A ${t} \u5B57\u7B26`),e}function To(e,t){let n=Ot(e,100,t);return/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/.test(n)||z("CODE_INVALID",t,"\u9700\u8981\u7A33\u5B9A\u7F16\u7801"),n}function Co(e,t,n,o){if(e===void 0)return[];(!Array.isArray(e)||e.length>t)&&z("ARRAY_LIMIT",o,`\u6700\u591A ${t} \u9879`);let r=e.map((i,s)=>Ot(i,n,`${o}/${s}`));return new Set(r).size!==r.length&&z("DUPLICATE",o,"\u4E0D\u80FD\u91CD\u590D"),r}function ou(e,t="/agents/instructions/file"){let n=Ot(e,500,t),o=n.split("/");return(!/\.(md|txt)$/i.test(n)||o.some(r=>!r||r.startsWith(".")||/[\\:\p{Cc}]/u.test(r)||/^(?:\.\.?|AGENTS\.md|CLAUDE\.md|SKILL\.md|credentials.*|secrets?.*|.*\.pem|.*\.key)$/i.test(r)))&&z("INSTRUCTION_PATH_INVALID",t,"\u9700\u8981\u5DE5\u4F5C\u533A\u5185\u7684\u666E\u901A md/txt \u6587\u4EF6\uFF0C\u4E0D\u80FD\u5F15\u7528\u534F\u4F5C\u8BF4\u660E\u6216\u51ED\u636E"),n}function ru(e,t,n){if(typeof e=="string")return Ot(e,Ca.instructions,t);let o=gi(e,t);_i(o,["file"],t);let r=ou(o.file,`${t}/file`);return n||z("INSTRUCTIONS_NOT_INLINED",t,"\u6587\u4EF6\u6307\u4EE4\u5FC5\u987B\u5148\u7531\u5DE5\u4F5C\u533A\u52A0\u8F7D\u5668\u5185\u8054"),{file:r}}var So={type:"object",additionalProperties:!1,required:["label"],properties:{label:{type:"string",minLength:1,maxLength:500}}},iu=/^(option|user|department|resource-ref)\.(single|multiple)$/,su=new Set(["file","image","signature","subtable","text.rich","json","serial-number"]);function au(e,t,n){if(t.type.startsWith("user."))return{selector:{owner:t.userCandidates?"user-candidates":"directory"}};if(t.type.startsWith("department."))return{selector:{owner:"directory"}};if(t.type.startsWith("resource-ref."))return{selector:{owner:"field-source"}};if(t.type.startsWith("option.")||t.type.startsWith("cascade."))return{selector:{owner:"options"}};if(!["text.short","uuid"].includes(t.type))return{};let o=n?.dataPolicies?.find(a=>a.code===e.dataPolicyCode&&a.resourceCode===e.code),r=[...o?.rules||[]],i=o?.readExpression?[o.readExpression]:[];for(;i.length;){let a=i.shift();r.length+i.length>2e3&&z("SELECTOR_POLICY_LIMIT",`/data/resources/${e.code}`,"\u8303\u56F4\u8DEF\u7531\u8D85\u8FC7\u89C4\u5219\u9884\u7B97"),a?.allOf?i.push(...a.allOf):a?.anyOf?i.push(...a.anyOf):r.push(a)}let s=new Set(r.flatMap(a=>a&&"dimensionCode"in a&&a.field===t.code&&n?.scopeDimensions?.some(d=>d.code===a.dimensionCode&&d.valueSource)?[a.dimensionCode]:[]));return s.size===1?{selector:{owner:"scope",dimensionCode:[...s][0]}}:s.size>1?{ambiguousScope:!0}:{}}function Na(e,t=!1,n){if(n?.ambiguousScope)return;if(n?.selector?.owner==="scope")return!t&&e.nullable!==!1?{anyOf:[So,{type:"null"}]}:So;if(iu.test(e.type)){let r=e.type.endsWith(".multiple")?{type:"array",minItems:t?1:0,maxItems:50,items:So}:So;return!t&&e.nullable!==!1?{anyOf:[r,{type:"null"}]}:r}if(!["text.short","text.long","number.integer","number.decimal","boolean","date","time","datetime"].includes(e.type))return;let o=Ro(e);return e.type==="datetime"&&(o={...o,pattern:"(?:Z|[+-]\\d{2}:\\d{2})$"}),t&&["number.integer","number.decimal","date","datetime"].includes(e.type)?{oneOf:[o,{type:"object",additionalProperties:!1,minProperties:1,properties:{from:o,to:o}}]}:!t&&e.nullable!==!1?{anyOf:[o,{type:"null"}]}:o}function Ge(e,t=[]){return{type:"object",additionalProperties:!1,properties:e,...t.length?{required:t}:{}}}function wa(e,t){return[...((t.source||e.surface?.fields[t.code]?.source)?.filters||[]).flatMap(o=>"binding"in o?[o.binding.field]:[]),...t.userCandidates?.scope?.field?[t.userCandidates.scope.field]:[]]}var Ra={type:"object",additionalProperties:!1,required:["handle"],properties:{handle:{type:"string",minLength:1,maxLength:80}}},Ta={type:"object",additionalProperties:!1,properties:{columns:{type:"array",maxItems:500,items:Ge({code:{type:"string"},label:{type:"string"}},["code","label"])},items:{type:"array",maxItems:100,items:Ge({handle:{type:"string"},title:{type:"string"},fields:{type:"array",maxItems:500,items:Ge({code:{type:"string"},label:{type:"string"},value:{type:"string"}},["code","label","value"])}},["handle","fields"])},more:{type:"boolean"},total:{type:"integer",minimum:0},continuation:{type:"string",maxLength:80},summary:{type:"string"},filter_ambiguous:{type:"boolean"},field:{type:"string",maxLength:100},labels:{type:"array",maxItems:20,items:Ge({label:{type:"string"},description:{type:"string"}},["label"])}}};function du(e,t,n,o,r,i){let s=o.find(h=>h&&typeof h=="object"&&h.code===n.resource&&h.status!=="retired");(!s?.surface||!s.surface.fields||!Array.isArray(s.schema?.fields)||s.schema.fields.some(h=>!h||typeof h.code!="string"||typeof h.type!="string"))&&z("RESOURCE_UNAVAILABLE",`${r}/resource`,"\u9700\u8981\u5F53\u524D\u6A21\u578B\u53CA\u6807\u51C6\u89C6\u56FE");try{bn(s.schema.fields,`${r}/resource/schema/fields`)}catch(h){if(!(h instanceof We))throw h;z("RESOURCE_SCHEMA_INVALID",`${r}/resource`,h.message)}s.surface.views!==void 0&&!Array.isArray(s.surface.views)&&z("VIEW_UNKNOWN",`${r}/view`,"\u9700\u8981\u5DF2\u9A8C\u8BC1\u7684\u6807\u51C6\u89C6\u56FE"),!s.surface.views?.some(h=>h.code===n.view)&&!(n.view==="default"&&!s.surface.views?.length)&&z("VIEW_UNKNOWN",`${r}/view`,"\u89C6\u56FE\u4E0D\u5B58\u5728");let a=n.view==="default"&&!s.surface.views?.length?s.surface:pi(s.surface,n.view),d=new Map(s.schema.fields.map(h=>[h.code,h])),c=new Map(s.schema.fields.map(h=>[h.code,au(s,h,i)])),l=h=>[...new Set(h)].flatMap(u=>{let E=d.get(u),w=c.get(u);if(!E||!w)return[];let S=!!E.userCandidates?.scope?.field;return[{field:u,...w.selector?{selector:w.selector}:{},create:n.kind==="form"&&n.action==="create"&&!S,update:n.kind==="form"&&n.action==="update",filter:n.kind==="view"&&(n.filters??a.list?.filterFields??[]).includes(u)&&!w.ambiguousScope,output:w.ambiguousScope?"page":w.selector?"label":"value",...w.ambiguousScope?{reason:"multiple-scope-dimensions"}:S?{reason:"saved-scope-required"}:{}}]}),f={code:`${e}.agent.${t}.${n.code}`,appCode:e,name:n.name||`${s.name}${n.kind==="view"?"\u67E5\u8BE2":n.action==="create"?"\u65B0\u589E":"\u4FEE\u6539"}`.slice(0,80),description:n.description||`\u901A\u8FC7${s.name}\u7684${n.view}\u6807\u51C6\u89C6\u56FE${n.kind==="view"?"\u67E5\u8BE2":"\u586B\u5199"}\uFF0C\u9075\u5B88\u5F53\u524D\u7528\u6237\u6743\u9650`,kind:"nativeTask",resources:[s.code],limits:{timeoutMs:1e4},agent:{visibility:"task",...n.examples?.length?{examples:[...n.examples]}:{}}};if(n.kind==="view"){a.generated?.list===!1&&z("LIST_DISABLED",r,"\u8BE5\u89C6\u56FE\u672A\u751F\u6210\u5217\u8868");let h=n.filters??a.list?.filterFields??[];h.some(T=>!a.list?.filterFields?.includes(T))&&z("FILTER_WIDENING",`${r}/filters`,"\u4EFB\u52A1\u53EA\u80FD\u7F29\u5C0F\u89C6\u56FE\u7B5B\u9009\u5B57\u6BB5");let u=h.filter(T=>!c.get(T)?.ambiguousScope),E=Object.fromEntries(u.map(T=>{let C=d.get(T),v=C&&Na(C,!0,c.get(T));return v||z("FILTER_TYPE_UNSUPPORTED",`${r}/filters`,`\u5B57\u6BB5 ${T} \u6682\u4E0D\u652F\u6301\u6A21\u578B\u7B5B\u9009\u63D0\u793A`),[T,v]})),w=(a.list?.fieldOrder||[]).filter(T=>s.surface.fields[T]?.sortable);a.list?.defaultSort&&!w.includes(a.list.defaultSort.field)&&w.push(a.list.defaultSort.field);let S=Ge({...a.list?.searchableFields?.length?{keyword:{type:"string",maxLength:200}}:{},...u.length?{filters:Ge(E)}:{},...w.length?{sort:Ge({field:{enum:w},order:{enum:["asc","desc"]}},["field"])}:{},limit:{type:"integer",minimum:1,maximum:100},continue:{type:"string",minLength:1,maxLength:80},record:Ra});return{...f,operation:"query",inputSchema:{type:"object"},outputSchema:Ta,authorization:{capabilities:[s.capabilities.read]},risk:"read",confirmation:"none",idempotency:"none",concurrency:"none",sideEffects:[],limits:{...f.limits,maxRows:100},binding:{kind:"native-view",resourceCode:s.code,viewCode:n.view,filterFields:u},agent:{...f.agent,nativeTask:{contractVersion:2,agentCode:t,taskCode:n.code,hintSchema:S,coverage:l([...h,...a.list?.fieldOrder||[],...a.detail?.fieldOrder||[]])}}}}((s.surface.mutationOwner||"native")!=="native"||a.generated?.[n.action]===!1)&&z("MUTATION_NOT_NATIVE",r,"\u53EA\u80FD\u7ED1\u5B9A\u5DF2\u751F\u6210\u7684\u666E\u901A\u539F\u751F create/update");let p=n.fields;p.length||z("FIELDS_REQUIRED",`${r}/fields`,"\u9700\u8981\u81F3\u5C11\u4E00\u4E2A\u8868\u5355\u5B57\u6BB5");for(let h of p){let u=d.get(h),E=s.surface.fields[h];(!u||!a.form?.fieldOrder?.includes(h)||!E||E.system||E.hidden||Vt(h)||Ao(h)||su.has(u.type))&&z("FORM_FIELD_UNSUPPORTED",`${r}/fields`,`\u5B57\u6BB5 ${h} \u4E0D\u5C5E\u4E8E\u53EF\u7F16\u8F91\u7684\u6807\u51C6\u5355\u63A7\u4EF6\u8868\u5355`),(!Array.isArray(E[`${n.action}Capabilities`])||E[`${n.action}Capabilities`].length===0)&&z("FORM_FIELD_UNWRITABLE",`${r}/fields`,`\u5B57\u6BB5 ${h} \u672A\u63D0\u4F9B ${n.action} \u6743\u9650`),n.action==="create"&&u.userCandidates?.scope?.field&&z("CANDIDATE_CREATE_OWNER_REQUIRED",`${r}/fields`,`\u4EFB\u52A1 ${n.code} \u5B57\u6BB5 ${h} (user-candidates) \u7684\u8303\u56F4\u53D6\u81EA\u8BB0\u5F55\u5B57\u6BB5\uFF0C\u65B0\u5EFA\u9700\u901A\u8FC7\u6D41\u7A0B\u53D1\u8D77\u6216 Nest \u4E1A\u52A1\u64CD\u4F5C\u529E\u7406`)}let m=new Set(p);if(n.action==="create"){for(let h of s.schema.fields)Et(h,s.surface.fields[h.code])&&!m.has(h.code)&&z("CREATE_FIELD_REQUIRED",`${r}/fields`,`\u5FC5\u987B\u5305\u542B\u65B0\u589E\u5FC5\u586B\u5B57\u6BB5 ${h.code}`);for(let h of p)for(let u of wa(s,d.get(h)))m.has(u)||z("CREATE_BINDING_REQUIRED",`${r}/fields`,`${h} \u4F9D\u8D56 ${u}\uFF0C\u5FC5\u987B\u5305\u542B\u7ED1\u5B9A\u5B57\u6BB5`)}else for(let h of s.schema.fields)wa(s,h).some(u=>m.has(u))&&!m.has(h.code)&&z("UPDATE_DEPENDENT_REQUIRED",`${r}/fields`,`\u4FEE\u6539\u7ED1\u5B9A\u5B57\u6BB5\u65F6\u5FC5\u987B\u5305\u542B\u4F9D\u8D56\u9009\u62E9\u5668 ${h.code}`);let A=p.map(h=>d.get(h)),I=n.action==="create"?A.filter(h=>Et(h,s.surface.fields[h.code])).map(h=>h.code):[],O=Ge(Object.fromEntries(A.map(h=>[h.code,h.nullable===!1?Ro(h):{anyOf:[Ro(h),{type:"null"}]}])),I),b=Object.fromEntries(A.flatMap(h=>{let u=Na(h,!1,c.get(h.code));return u?[[h.code,u]]:[]})),g={kind:"native-form",resourceCode:s.code,viewCode:n.view,action:n.action,fields:[...p]},y=Ge({data:O,...n.action==="update"?{id:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1}}:{}},["data",...n.action==="update"?["id","expectedRevision"]:[]]);return{...f,operation:n.action,inputSchema:y,outputSchema:Ta,authorization:{capabilities:[s.capabilities[n.action]]},risk:"write",confirmation:n.confirmation||"required",idempotency:"required",concurrency:n.action==="update"?"revision":"none",sideEffects:[`${s.code}:${n.action}`],reconcile:{kind:"platform-transaction"},binding:g,agent:{...f.agent,nativeTask:{contractVersion:2,agentCode:t,taskCode:n.code,hintSchema:Ge({data:Ge(b),...n.action==="update"?{record:Ra}:{}}),coverage:l(p),form:{contractVersion:2,action:n.action,title:f.name,submitLabel:"\u63D0\u4EA4",resource:s.code,view:n.view,fields:A.map(h=>({path:h.code,label:s.surface.fields[h.code].label,fieldType:h.type,required:Et(h,s.surface.fields[h.code]),source:{resource:s.code,field:h.code},...c.get(h.code)?.selector?{selector:c.get(h.code).selector}:{}}))}}}}}function Sa(e,t,n,o={}){let r={schemaVersion:"openxiangda.application-agent-definitions/v2",appCode:e,agents:[]},i=[];if(t===void 0)return{definitions:r,capabilities:i};Array.isArray(n)||z("RESOURCES_INVALID","/data/resources","\u9700\u8981\u5DF2\u9A8C\u8BC1\u7684\u6A21\u578B\u5217\u8868"),(!Array.isArray(t)||t.length>Ca.agents)&&z("AGENT_LIMIT","/agents","\u6700\u591A 20 \u4E2A\u52A9\u624B");let s=new Set;for(let a=0;a<t.length;a++){let d=`/agents/${a}`,c=gi(t[a],d);_i(c,["code","name","purpose","instructions","starters","tasks"],d);let l=To(c.code,`${d}/code`);s.has(l)&&z("CODE_DUPLICATE",`${d}/code`,"\u52A9\u624B\u4EE3\u7801\u91CD\u590D"),s.add(l);let f=Ot(c.name,80,`${d}/name`),p=Ot(c.purpose,1e3,`${d}/purpose`),m=ru(c.instructions,`${d}/instructions`,o.allowInstructionFiles===!0),A=Co(c.starters,12,160,`${d}/starters`);(!Array.isArray(c.tasks)||c.tasks.length<1||c.tasks.length>20)&&z("TASK_LIMIT",`${d}/tasks`,"\u9700\u8981 1\u201320 \u4E2A\u4EFB\u52A1");let I=new Set,O=c.tasks.map((g,y)=>{let h=`${d}/tasks/${y}`,u=gi(g,h);["view","form"].includes(u.kind)||z("TASK_KIND_INVALID",`${h}/kind`,"\u53EA\u652F\u6301 view/form"),_i(u,["code","kind","name","description","resource","view","examples",...u.kind==="view"?["filters"]:["action","fields","confirmation"]],h);let E=To(u.code,`${h}/code`);return I.has(E)&&z("TASK_CODE_DUPLICATE",`${h}/code`,"\u4EFB\u52A1\u4EE3\u7801\u91CD\u590D"),I.add(E),To(u.resource,`${h}/resource`),To(u.view,`${h}/view`),u.name!==void 0&&Ot(u.name,80,`${h}/name`),u.description!==void 0&&Ot(u.description,1e3,`${h}/description`),Co(u.examples,12,160,`${h}/examples`),u.kind==="view"?Co(u.filters,20,100,`${h}/filters`):(["create","update"].includes(u.action)||z("FORM_ACTION_INVALID",`${h}/action`,"\u53EA\u652F\u6301 create/update"),u.confirmation!==void 0&&!["none","required"].includes(u.confirmation)&&z("CONFIRMATION_INVALID",`${h}/confirmation`,"\u786E\u8BA4\u7B56\u7565\u65E0\u6548"),Array.isArray(u.fields)||z("FIELDS_REQUIRED",`${h}/fields`,"\u9700\u8981\u5B57\u6BB5\u5217\u8868"),Co(u.fields,20,100,`${h}/fields`)),du(e,l,u,n,h,o.authz)}),b={code:l,name:f,purpose:p,instructions:typeof m=="string"?m:"",starters:A,tasks:O.map(g=>({code:g.agent.nativeTask.taskCode,capabilityCode:g.code}))};r.agents.push({...b,digest:ee({...b,capabilities:O})}),i.push(...O)}return r.agents.sort((a,d)=>a.code<d.code?-1:a.code>d.code?1:0),i.sort((a,d)=>a.code<d.code?-1:a.code>d.code?1:0),{definitions:r,capabilities:i}}function Do(e){let t=[];for(let[n,o]of Object.entries(e?.nodes||{})){if(o?.reminders===void 0)continue;let r=o.reminders;(!["approval","handle","correction"].includes(o.kind)||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length!==4||Object.keys(r).some(i=>!["afterSeconds","everySeconds","max","to"].includes(i))||!Number.isInteger(r.afterSeconds)||r.afterSeconds<1||r.afterSeconds>2592e3||!Number.isInteger(r.everySeconds)||r.everySeconds<1||r.everySeconds>2592e3||!Number.isInteger(r.max)||r.max<1||r.max>10||!Array.isArray(r.to)||r.to.length!==1||r.to[0]!=="handlers")&&t.push(`WORKFLOW_REMINDERS_INVALID:${n}`)}return t}function ot(e){return e.returnPolicy?Array.isArray(e.returnPolicy.targets)?e.returnPolicy.targets.filter(t=>typeof t?.nodeId=="string").map(t=>t.nodeId):[]:Array.isArray(e.returnTargets)?[...e.returnTargets]:[]}function Pg(e,t,n){if(t.returnPolicy)return Array.isArray(t.returnPolicy.targets)?t.returnPolicy.targets.find(o=>o.nodeId===n):void 0;if(t.returnTargets?.includes(n))return{nodeId:n,routes:e.nodes[n]?.kind==="correction"?["replay"]:["replay","resume"],defaultRoute:"replay"}}function ko(e){let t=[];for(let[n,o]of Object.entries(e?.nodes||{})){let r=o?.returnPolicy;if(r===void 0)continue;if(!["approval","handle"].includes(o.kind)||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(s=>s!=="targets")||!Array.isArray(r.targets)||r.targets.length>20){t.push(`WORKFLOW_RETURN_POLICY_INVALID:${n}`);continue}let i=new Set;for(let s of r.targets)(!s||typeof s!="object"||Object.keys(s).some(a=>!["nodeId","routes","defaultRoute"].includes(a))||typeof s.nodeId!="string"||s.nodeId===n||i.has(s.nodeId)||!["approval","handle","correction"].includes(e.nodes?.[s.nodeId]?.kind))&&t.push(`WORKFLOW_RETURN_TARGET_INVALID:${n}`),s?.nodeId&&i.add(s.nodeId),(!Array.isArray(s?.routes)||s.routes.length<1||s.routes.length>2||new Set(s.routes).size!==s.routes.length||s.routes.some(a=>!["replay","resume"].includes(a))||!s.routes.includes(s.defaultRoute))&&t.push(`WORKFLOW_RETURN_ROUTES_INVALID:${n}`);o.returnTargets&&(o.returnTargets.length!==i.size||o.returnTargets.some(s=>!i.has(s)))&&t.push(`WORKFLOW_RETURN_TARGETS_CONFLICT:${n}`)}return t}var cu=2,lu=8,Ai=e=>!!e&&typeof e=="object"&&!Array.isArray(e),uu=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(e),Da=(e,t)=>e===t||e.startsWith(`${t}.`)||t.startsWith(`${e}.`);function Lo(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="condition"?[...(Array.isArray(e.branches)?e.branches:[]).map(t=>t?.target),e.otherwise]:e.kind==="parallel"?[...(Array.isArray(e.branches)?e.branches:[]).map(t=>t?.target),e.join]:"next"in e?[e.next]:[]}function rt(e){let t=[],n=[];if(!Ai(e?.nodes))return{regions:n,errors:["WORKFLOW_PARALLEL_DOCUMENT_INVALID"]};let o=e.nodes;if(!Object.values(o).some(s=>s?.kind==="parallel"||s?.kind==="join"))return{regions:n,errors:t};if(Object.keys(o).length>200)return{regions:n,errors:["WORKFLOW_PARALLEL_NODE_LIMIT"]};let r=new Map,i=new Set;for(let s of Object.values(o)){if(s?.kind!=="parallel")continue;let a=o[s.join];if(a?.kind!=="join"||a.parallel!==s.id||i.has(s.join)){t.push(`WORKFLOW_PARALLEL_PAIR_INVALID:${s.id}`);continue}if(i.add(a.id),o[a.next]||t.push(`WORKFLOW_PARALLEL_TARGET_MISSING:${a.id}`),!Array.isArray(s.branches)||s.branches.length<cu||s.branches.length>lu){t.push(`WORKFLOW_PARALLEL_BRANCH_LIMIT:${s.id}`);continue}let d={parallelNodeId:s.id,joinNodeId:a.id,branches:[]},c=new Set,l=new Set;for(let f of s.branches){if(!Ai(f)||!uu(f.id)||typeof f.title!="string"||!f.title.trim()||f.title.length>255||c.has(f.id)){t.push(`WORKFLOW_PARALLEL_BRANCH_INVALID:${s.id}`);continue}c.add(f.id);let p=new Set,m=new Set,A=new Set,I=b=>{if(b===a.id)return;let g=o[b];if(!g){t.push(`WORKFLOW_PARALLEL_TARGET_MISSING:${s.id}:${b}`);return}if(g.kind==="end"){g.outcome!=="rejected"?t.push(`WORKFLOW_PARALLEL_BRANCH_END_INVALID:${s.id}:${f.id}:${b}`):l.add(b);return}if(g.kind==="parallel"||g.kind==="join"){t.push(`WORKFLOW_PARALLEL_NESTING_FORBIDDEN:${s.id}:${b}`);return}if(m.has(b)){t.push(`WORKFLOW_PARALLEL_CYCLE:${s.id}:${b}`);return}if(A.has(b))return;p.add(b),m.add(b);let y=Lo(g);y.length||t.push(`WORKFLOW_PARALLEL_BRANCH_DANGLING:${s.id}:${b}`);for(let h of y)I(h);m.delete(b),A.add(b)};I(f.target);let O=new Set;for(let b of p){r.get(b)?t.push(`WORKFLOW_PARALLEL_BODY_OVERLAP:${s.id}:${f.id}:${b}`):r.set(b,{parallel:s.id,branch:f.id});let y=o[b];if(y.kind==="approval"||y.kind==="handle")for(let h of e.taskPages?.[y.taskPageCode||""]?.fields||[]){let u=y.fieldPolicy?.fields?.[h.code]||y.fieldPolicy?.default||"readonly";h.readonly!==!0&&(u==="edit"||u==="edit_required")&&O.add(h.code)}}d.branches.push({id:f.id,target:f.target,nodeIds:[...p].sort(),writableFields:[...O].sort()})}l.size>1&&t.push(`WORKFLOW_PARALLEL_REJECT_END_NOT_SHARED:${s.id}`),n.push(d)}for(let s of Object.values(o))s?.kind==="join"&&!i.has(s.id)&&t.push(`WORKFLOW_PARALLEL_JOIN_ORPHAN:${s.id}`);r.has(e.startAt)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_ENTRY:${e.startAt}`);for(let[s,a]of Object.entries(o))if(Ai(a)){for(let d of Lo(a)){let c=r.get(d),l=r.get(s),f=c&&o[c.parallel],p=f?.kind==="parallel"&&s===f.id&&f.branches.some(m=>m.id===c.branch&&m.target===d);if(c&&!p&&(!l||l.parallel!==c.parallel||l.branch!==c.branch)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_ENTRY:${s}:${d}`),o[d]?.kind==="join"&&a.kind!=="parallel"){let m=o[d];(!l||l.parallel!==m.parallel)&&t.push(`WORKFLOW_PARALLEL_EXTERNAL_JOIN:${s}:${d}`)}}if(a.kind==="approval"||a.kind==="handle"){let d=r.get(s);for(let c of ot(a)){let l=r.get(c);d&&(!l||l.parallel!==d.parallel||l.branch!==d.branch)&&t.push(`WORKFLOW_PARALLEL_RETURN_CROSSES_BRANCH:${s}:${c}`),!d&&l&&t.push(`WORKFLOW_PARALLEL_RETURN_ENTERS_BRANCH:${s}:${c}`)}}}for(let s of n)for(let a of s.branches){let d=s.branches.filter(l=>l.id!==a.id);for(let l of a.writableFields)d.some(f=>f.writableFields.includes(l))&&t.push(`WORKFLOW_PARALLEL_SHARED_WRITABLE_FIELD:${s.parallelNodeId}:${l}`);let c=d.flatMap(l=>[...Object.entries(e.subject?.factProjection||{}).filter(([,f])=>l.writableFields.some(p=>Da(p,f))).map(([f])=>f),...l.nodeIds.filter(f=>o[f]?.kind==="action").map(f=>`steps.${f}`)]);for(let l of a.nodeIds){let f=o[l];if(f.kind==="action")for(let p of Object.values(f.inputs||{}))p.source==="fact"&&c.some(m=>Da(m,p.path))&&t.push(`WORKFLOW_PARALLEL_SIBLING_INPUT:${l}:${p.path}`)}}return{regions:n,errors:[...new Set(t)]}}function vo(e){return rt(e).errors}function Vg(e){if(!["running","returned"].includes(e.status))return!1;if(!e.forkVisitId&&!e.branchId)return e.currentNodeId===e.nodeId;let t=e.fork;return!!t&&e.forkVisitId===t.forkVisitId&&e.branchId===t.branchId&&t.status==="active"&&e.currentNodeId===t.parallelNodeId&&t.activation.includes(e.branchId)&&!t.arrived.includes(e.branchId)&&e.activeToken}function Po(e){let t=[];for(let[n,o]of Object.entries(e?.nodes||{})){if(o?.kind!=="handle"){o?.allowedOperations?.includes("complete")&&t.push(`WORKFLOW_HANDLE_COMMAND_ONLY:${n}`);continue}(!o.next||!e.nodes?.[o.next])&&t.push(`WORKFLOW_HANDLE_TARGET_MISSING:${n}`),(["onApprove","onReject","initiatorApprovalPolicy","completionDeadline"].some(r=>r in o)||o.emptyPolicy==="skip")&&t.push(`WORKFLOW_HANDLE_APPROVAL_POLICY_FORBIDDEN:${n}`),(!Array.isArray(o.allowedOperations)||!o.allowedOperations.includes("complete")||o.allowedOperations.some(r=>!["complete","save_form","transfer","delegate","return"].includes(r)))&&t.push(`WORKFLOW_HANDLE_OPERATIONS_INVALID:${n}`),(!Array.isArray(o.requiredOperations)||!o.requiredOperations.includes("complete"))&&t.push(`WORKFLOW_HANDLE_COMPLETE_REQUIRED:${n}`)}return t}function Ei(e,t){let n=()=>{throw Object.assign(new Error("DATA_MUTATION_GRANT_INVALID"),{code:"DATA_MUTATION_GRANT_INVALID"})};if(!Array.isArray(e)||e.length<1||e.length>32)return n();let o=new Set;return e.map(i=>!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(s=>!["resourceCode","operations","fieldCodes","maxOperations","allowRuntimeWorker"].includes(s))||typeof i.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.resourceCode)||i.allowRuntimeWorker!==void 0&&i.allowRuntimeWorker!==!0||o.has(i.resourceCode)||t&&!t.has(i.resourceCode)||!Array.isArray(i.operations)||i.operations.length<1||i.operations.length>4||new Set(i.operations).size!==i.operations.length||i.operations.some(s=>!["create","update","delete","increment"].includes(s))||!Array.isArray(i.fieldCodes)||i.fieldCodes.length>128||new Set(i.fieldCodes).size!==i.fieldCodes.length||i.operations.some(s=>s!=="delete")&&!i.fieldCodes.length||i.fieldCodes.some(s=>typeof s!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(s)||t&&!t.get(i.resourceCode)?.has(s))||!Number.isSafeInteger(i.maxOperations)||i.maxOperations<1||i.maxOperations>1e3?n():(o.add(i.resourceCode),{resourceCode:i.resourceCode,operations:[...i.operations].sort(),fieldCodes:[...i.fieldCodes].sort(),maxOperations:i.maxOperations,...i.allowRuntimeWorker?{allowRuntimeWorker:!0}:{}})).sort((i,s)=>i.resourceCode.localeCompare(s.resourceCode))}var Ug=5,Mg=20,Bg=50,Kg=50,qg=100,Dn=class extends Error{constructor(n,o){super(n);this.code=n;this.pointer=o;this.name="NativeDataPolicyExpressionV2Error"}code;pointer};function an(e,t){let n=[],o=(r,i,s)=>{s>5&&Sn("NATIVE_DATA_POLICY_EXPRESSION_DEPTH_EXCEEDED",i);let a=La(r,i),d=["allOf","anyOf"].filter(f=>f in a);if(d.length===0){n.push({rule:a,pointer:i}),n.length>50&&Sn("NATIVE_DATA_POLICY_EXPRESSION_LEAVES_EXCEEDED",i);return}let c=d[0],l=a[c];(d.length!==1||Object.keys(a).length!==1||!Array.isArray(l)||l.length<1||l.length>20)&&Sn("NATIVE_DATA_POLICY_EXPRESSION_GROUP_INVALID",i),l.forEach((f,p)=>o(f,`${i}/${c}/${p}`,s+1))};return o(e,t,1),n}function ka(e,t){an(e,t);let n=(o,r)=>{let i=La(o,r);if(Array.isArray(i.allOf))return Ii(i.allOf.flatMap((s,a)=>n(s,`${r}/allOf/${a}`)),r);if(Array.isArray(i.anyOf)){let s=[[]];return i.anyOf.forEach((a,d)=>{let c=n(a,`${r}/anyOf/${d}`);s=Ii(s.flatMap(l=>c.map(f=>[...l,...f])),r)}),s}return[[i]]};return Ii(n(e,t),t)}function Ii(e,t){let n=e.reduce((o,r)=>o+r.length,0);return(e.length>50||n>100)&&Sn("NATIVE_DATA_POLICY_EXPRESSION_EXPANSION_EXCEEDED",t),e}function La(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&Sn("NATIVE_DATA_POLICY_EXPRESSION_NODE_INVALID",t),e}function Sn(e,t){throw new Dn(e,t)}var Te=class extends Error{constructor(n,o){super(`${n}: ${o}`);this.code=n;this.pointer=o}code;pointer},fu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,va=/^[A-Za-z_][A-Za-z0-9_]{0,127}$/;function pu(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Te("NATIVE_PARENT_READ_INVALID",t);let n=e;if(Object.keys(n).some(o=>!["resourceCode","subtableFieldCode"].includes(o))||typeof n.resourceCode!="string"||n.resourceCode.length>64||!fu.test(n.resourceCode)||typeof n.subtableFieldCode!="string"||!va.test(n.subtableFieldCode))throw new Te("NATIVE_PARENT_READ_INVALID",t);return{resourceCode:n.resourceCode,subtableFieldCode:n.subtableFieldCode}}function Pa(e,t){return[...(Array.isArray(e.rules)?e.rules:[]).map((n,o)=>({rule:n,pointer:`${t}/rules/${o}`,base:!0})),...e.readExpression===void 0?[]:an(e.readExpression,`${t}/readExpression`).map(n=>({...n,base:!1}))]}function $o(e,t,n,o){let r=pu(n,o),i=e.find(m=>m.code===r.resourceCode),s=e.find(m=>m.code===t),d=(Array.isArray(i?.schema?.fields)?i.schema.fields:[]).find(m=>m.code===r.subtableFieldCode);if(!i||!s||i.code===s.code||d?.type!=="subtable"||d.subtable?.resourceCode!==t)throw new Te("NATIVE_PARENT_READ_BINDING_INVALID",o);if(e.flatMap(m=>(Array.isArray(m.schema?.fields)?m.schema.fields:[]).filter(A=>A.type==="subtable"&&A.subtable?.resourceCode===t).map(A=>({resource:m,field:A}))).length!==1)throw new Te("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",o);let l=d.subtable.foreignKey,p=(Array.isArray(s.schema?.fields)?s.schema.fields:[]).find(m=>m.code===l);if(typeof l!="string"||!va.test(l)||p?.type!=="uuid")throw new Te("NATIVE_PARENT_READ_FOREIGN_KEY_INVALID",o);return{...r,childResourceCode:t,foreignKey:l,...d.subtable.orderField?{orderField:d.subtable.orderField}:{}}}function $a(e,t,n="/config/authz/dataPolicies"){let o=new Map;for(let[r,i]of t.entries())for(let s of Pa(i,`${n}/${r}`)){if(s.rule.parentRead===void 0)continue;if(Object.keys(s.rule).some(l=>!["parentRead","roleCodes"].includes(l)))throw new Te("NATIVE_PARENT_READ_RULE_KEYS_INVALID",s.pointer);if(s.base&&(i.operations?.length!==1||i.operations[0]!=="read"))throw new Te("NATIVE_PARENT_READ_READ_ONLY",s.pointer);if(e.find(l=>l.code===i.resourceCode)?.dataPolicyCode!==i.code)throw new Te("NATIVE_PARENT_READ_POLICY_BINDING_INVALID",s.pointer);let d=$o(e,i.resourceCode,s.rule.parentRead,`${s.pointer}/parentRead`),c=o.get(i.resourceCode);if(c&&c!==d.resourceCode)throw new Te("NATIVE_PARENT_READ_PARENT_AMBIGUOUS",s.pointer);o.set(i.resourceCode,d.resourceCode)}for(let[r,i]of o)if(o.has(i))throw new Te("NATIVE_PARENT_READ_MULTI_HOP_FORBIDDEN",`${n}/${t.findIndex(s=>s.resourceCode===r)}`)}function yi(e){return Pa(e,"/dataPolicy").some(t=>t.rule.parentRead!==void 0)}var Wa=e=>!!e&&typeof e=="object"&&!Array.isArray(e),xa=(e,t)=>Object.keys(e).length===t.length&&Object.keys(e).every(n=>t.includes(n)),Fa=e=>typeof e=="string"&&/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(e)&&e.length<=100,Va=e=>typeof e=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e);function Oi(e){throw new Error(`OPENXIANGDA_WORKFLOW_STAGE_${e}`)}function ja(e){(!Wa(e)||!xa(e,["workflowCode","resourceCode","actor","runningNodeIds","allowedStatuses"])||!Fa(e.workflowCode)||!Fa(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)&&Oi("POLICY_INVALID")}function Hg(e){(!Wa(e)||!xa(e,["instanceId","subjectRecordId","expectedInstanceSequence"])||!Va(e.instanceId)||!Va(e.subjectRecordId)||!Number.isSafeInteger(e.expectedInstanceSequence)||e.expectedInstanceSequence<0)&&Oi("GUARD_INVALID")}function Yg(e,t,n){n?.some(o=>(o.kind==="record-match"||o.kind==="record-assert")&&o.resourceCode===e.resourceCode&&o.id.toLowerCase()===t.subjectRecordId.toLowerCase()&&o.assertions.some(r=>r.kind==="value"&&r.field==="revision"&&r.operator==="eq"&&Number.isSafeInteger(r.value)&&Number(r.value)>0))||Oi("SOURCE_GUARD_REQUIRED")}var Xg={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 kn=class extends Error{constructor(n,o){super(n);this.code=n;this.pointer=o}code;pointer},ke=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Ua=(e,t)=>e===t||e==="*"||e.endsWith(":*")&&t.startsWith(e.slice(0,-1));function Ma(e){let{policy:t,resource:n,baselineRoleCode:o,baselineCapabilities:r,pointer:i}=e,s=I=>I===void 0||I===!0||Array.isArray(I)&&I.length>0&&I.every(O=>typeof O=="string"&&O.length>0&&!e.baselineDeniedCapabilities?.some(b=>Ua(b,O))&&r.some(b=>Ua(b,O))),a=(I,O="")=>{throw new kn(I,`${i}/publicRead${O}`)},d=ke(t.publicRead);(!t.publicRead||Object.keys(d).length!==1||!Object.hasOwn(d,"fields")||!Array.isArray(d.fields)||d.fields.length<1||d.fields.length>1e3||d.fields.some(I=>typeof I!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(I))||new Set(d.fields).size!==d.fields.length)&&a("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)&&a("AUTHENTICATED_PUBLIC_READ_POLICY_NOT_READ_ONLY"),(!o||!n||n.code!==t.resourceCode||n.dataPolicyCode!==t.code||!s([ke(n.capabilities).read]))&&a("AUTHENTICATED_PUBLIC_READ_BASELINE_OR_RESOURCE_INVALID");let c=ke(n),l=ke(c.schema).fields;(!Array.isArray(l)||!l.length)&&a("AUTHENTICATED_PUBLIC_READ_RESOURCE_FIELDS_MISSING");let f=new Map(l.map(I=>[String(ke(I).code),ke(I)])),p=new Set(d.fields),m=ke(c.fieldPolicies);for(let I of p){let O=ke(f.get(I));(!f.has(I)||O.system===!0||ke(ke(c.surface).fields)[I]?.system===!0||tn.has(I))&&a("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_DECLARED",`/fields/${I}`),(O.type==="subtable"||O.subtable!==void 0)&&a("AUTHENTICATED_PUBLIC_READ_SUBTABLE_UNSUPPORTED",`/fields/${I}`),s(ke(m[I]).read)||a("AUTHENTICATED_PUBLIC_READ_FIELD_NOT_BASELINE_READABLE",`/fields/${I}`)}let A=[...f.keys()].filter(I=>!p.has(I));for(let I of A)s(ke(m[I]).read)&&a("AUTHENTICATED_PUBLIC_READ_PRIVATE_FIELD_ACCESSIBLE",`/fields/${I}`);A.length&&_o.some(I=>s(ke(m[I]).read))&&a("AUTHENTICATED_PUBLIC_READ_PRIVATE_HISTORY_ACCESSIBLE")}var Ba=["exact-v1","nfkc-space-v1","nfkc-upper-ascii-v1"],n_=256,vn=class extends Error{constructor(n,o){super(`\u6761\u4EF6\u552F\u4E00\u952E\u58F0\u660E\u65E0\u6548\uFF1A${o}\uFF08${n}\uFF09`);this.pointer=n;this.reason=o}pointer;reason;code="NATIVE_UNIQUE_KEY_INVALID"},bi=e=>!!(e&&typeof e=="object"&&!Array.isArray(e)),ge=(e,t)=>{throw new vn(e,t)},Fo=(e,t)=>e<t?-1:e>t?1:0,Ln=(e,t,n)=>{Object.keys(e).some(o=>!t.includes(o))&&ge(n,"\u4E0D\u652F\u6301\u672A\u77E5\u5C5E\u6027")};function Ka(e,t,n="/uniqueKeys"){if(e===void 0)return;if(!Array.isArray(e)||e.length>8)return ge(n,"\u6BCF\u8D44\u6E90\u6700\u591A 8 \u6761\u89C4\u5219");let o=new Map(t.map(i=>[i.code,i])),r=new Set;return e.map((i,s)=>{let a=`${n}/${s}`;if(!bi(i))return ge(a,"\u89C4\u5219\u5FC5\u987B\u662F\u5BF9\u8C61");if(Ln(i,["code","fields","when"],a),typeof i.code!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(i.code)||i.code.length>20||r.has(i.code))return ge(`${a}/code`,"\u9700\u8981\u4E0D\u91CD\u590D\u4E14\u4E0D\u8D85\u8FC7 20 \u5B57\u7B26\u7684 lower-kebab-case \u6807\u8BC6");if(r.add(i.code),!Array.isArray(i.fields)||i.fields.length<1||i.fields.length>4)return ge(`${a}/fields`,"\u5FC5\u987B\u9009\u62E9 1 \u5230 4 \u4E2A\u5B57\u6BB5");let d=new Set,c=i.fields.map((m,A)=>{let I=`${a}/fields/${A}`;if(!bi(m))return ge(I,"\u5B57\u6BB5\u5FC5\u987B\u662F\u5BF9\u8C61");Ln(m,["fieldCode","normalizer"],I);let O=o.get(m.fieldCode);if(!O||!["text.short","uuid","option.single","resource-ref.single","user.single"].includes(O.type)||d.has(m.fieldCode))return ge(`${I}/fieldCode`,"\u9700\u8981\u4E0D\u91CD\u590D\u7684\u77ED\u6587\u672C\u3001UUID\u3001\u5355\u9009\u3001\u5355\u8BB0\u5F55\u5F15\u7528\u6216\u5355\u4EBA\u5B57\u6BB5");d.add(m.fieldCode);let b=m.normalizer===void 0?"exact-v1":m.normalizer;return!Ba.includes(b)||O.type!=="text.short"&&b!=="exact-v1"?ge(`${I}/normalizer`,"\u5F52\u4E00\u5316\u65B9\u5F0F\u4E0D\u652F\u6301\u6216\u4E0E\u5B57\u6BB5\u7C7B\u578B\u4E0D\u7B26"):{fieldCode:O.code,normalizer:b}}).sort((m,A)=>Fo(m.fieldCode,A.fieldCode)),l=i.when===void 0?[]:i.when;if(!Array.isArray(l)||l.length>4)return ge(`${a}/when`,"\u6700\u591A 4 \u4E2A\u5408\u53D6\u6761\u4EF6");let f=new Set,p=l.map((m,A)=>{let I=`${a}/when/${A}`;if(!bi(m))return ge(I,"\u6761\u4EF6\u5FC5\u987B\u662F\u5BF9\u8C61");let O=o.get(m.fieldCode);if(!O)return ge(`${I}/fieldCode`,"\u5B57\u6BB5\u4E0D\u5B58\u5728");let b;if(m.operator==="empty"||m.operator==="nonempty"){if(Ln(m,["fieldCode","operator"],I),O.type!=="text.short")return ge(I,"\u7A7A\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u77ED\u6587\u672C");b={fieldCode:O.code,operator:m.operator}}else if(m.operator==="in"||m.operator==="notIn"){Ln(m,["fieldCode","operator","values"],I);let y=new Set((O.options??[]).map(h=>h.value));if(O.type!=="option.single"||!Array.isArray(m.values)||m.values.length<1||m.values.length>16||m.values.some(h=>typeof h!="string"||h.length<1||h.length>128||!y.has(h))||new Set(m.values).size!==m.values.length)return ge(I,"\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:m.operator,values:[...m.values].sort(Fo)}}else if(m.operator==="eq"||m.operator==="ne"){if(Ln(m,["fieldCode","operator","value"],I),O.type!=="boolean"||typeof m.value!="boolean")return ge(I,"\u7B49\u503C\u6761\u4EF6\u4EC5\u652F\u6301\u5E03\u5C14\u5B57\u6BB5\u548C\u5E03\u5C14\u503C");b={fieldCode:O.code,operator:m.operator,value:m.value}}else return ge(`${I}/operator`,"\u53EA\u652F\u6301 empty\u3001nonempty\u3001in\u3001notIn \u548C\u5E03\u5C14 eq\u3001ne");let g=JSON.stringify(b);return f.has(g)?ge(I,"\u6761\u4EF6\u4E0D\u80FD\u91CD\u590D"):(f.add(g),b)}).sort((m,A)=>Fo(JSON.stringify(m),JSON.stringify(A)));return{code:i.code,fields:c,when:p}}).sort((i,s)=>Fo(i.code,s.code))}function qa(e,t){let n=new Set(e.filter(o=>o.type==="user.single").map(o=>o.code));return t?.some(o=>o.fields.some(r=>n.has(r.fieldCode))||o.when?.some(r=>r.operator==="eq"||r.operator==="ne"))?"1.1.0":"1.0.0"}var Vo={type:"string",pattern:"^[A-Za-z_][A-Za-z0-9_]{0,62}$"},o_={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:Vo,normalizer:{enum:[...Ba]}}}},when:{type:"array",maxItems:4,uniqueItems:!0,items:{oneOf:[{type:"object",additionalProperties:!1,required:["fieldCode","operator"],properties:{fieldCode:Vo,operator:{enum:["empty","nonempty"]}}},{type:"object",additionalProperties:!1,required:["fieldCode","operator","values"],properties:{fieldCode:Vo,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:Vo,operator:{enum:["eq","ne"]},value:{type:"boolean"}}}]}}}}};var za={"openxiangda.workflow.instance.completed.v2":"commit","openxiangda.workflow.instance.rejected.v2":"release","openxiangda.workflow.instance.withdrawn.v2":"release"};function Ga(e,t){let n=()=>{throw new Error("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID")},o=p=>!p||typeof p!="object"||Array.isArray(p)?n():p,r=o(e);if(Object.keys(r).some(p=>!["resourceCode","workflowCode","outcomes"].includes(p))||typeof r.resourceCode!="string"||!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(r.resourceCode)||typeof r.workflowCode!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(r.workflowCode)||t.execution!==void 0||!Array.isArray(r.outcomes)||!r.outcomes.length||r.outcomes.length>3)return n();let i=t.resources.find(p=>p.code===r.resourceCode),s=t.reservations.find(p=>p.mode==="reserve"&&p.resourceCode===r.resourceCode),a=t.workflows.find(p=>p.code===r.workflowCode);if(!i||!s||!a||a.resourceCode!==i.code)return n();let d=i.fields.find(p=>p.code===s.statusFieldCode);if(d?.type!=="option.single")return n();let c=new Set(d.options?.map(p=>p.value)),l=new Set,f=r.outcomes.map(p=>{let m=o(p),A=m.eventType;return Object.keys(m).some(I=>!["eventType","mode","eligibleChildStatuses"].includes(I))||typeof A!="string"||!Object.prototype.hasOwnProperty.call(za,A)||!t.eventTypes.includes(A)||l.has(A)||m.mode!==za[A]||!Array.isArray(m.eligibleChildStatuses)||!m.eligibleChildStatuses.length||m.eligibleChildStatuses.length>16||new Set(m.eligibleChildStatuses).size!==m.eligibleChildStatuses.length||m.eligibleChildStatuses.some(I=>typeof I!="string"||!/^[A-Za-z0-9._:-]{1,128}$/.test(I)||!c.has(I))?n():(l.add(A),{eventType:A,mode:m.mode,eligibleChildStatuses:[...m.eligibleChildStatuses].sort()})}).sort((p,m)=>p.eventType.localeCompare(m.eventType));return{resourceCode:r.resourceCode,workflowCode:r.workflowCode,outcomes:f}}function Ja(e,t){let n=o=>Array.isArray(o)?o.filter(r=>r&&typeof r=="object"&&!Array.isArray(r)):[];return{eventTypes:Array.isArray(t.eventTypes)?t.eventTypes:[],execution:t.execution,resources:n(e.data?.resources).map(o=>({code:o.code,fields:n(o.schema?.fields).map(r=>({code:r.code,type:r.type,options:n(r.options).map(i=>({value:i.value}))}))})),reservations:n(e.backend?.operations).flatMap(o=>o.platformAccess?.decimalReservation?[o.platformAccess.decimalReservation]:[]),workflows:n(e.workflows?.definitions).map(o=>({code:o.definition?.code,resourceCode:o.definition?.subject?.resourceCode}))}}var Wo=new Set(["eq","neq","gt","gte","lt","lte","contains","startsWith","endsWith","in","between","has","hasAny","hasAll","overlaps","containedBy","jsonContains","isEmpty","isNotEmpty"]),Ha=new Set(["isEmpty","isNotEmpty"]);var wi=class extends Error{constructor(n,o){super(n);this.code=n;this.pointer=o}code;pointer},U=(e,t="EVENT_WORKER_EFFECT_INVALID")=>{throw new wi(t,e)},Ue=(e,t,n)=>((!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(o=>!t.includes(o)))&&U(n),e),hi=e=>typeof e=="string"&&/^[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(e),bt=(e,t,n,o)=>((typeof e!="number"||!Number.isSafeInteger(e)||e<t||e>n)&&U(o),e),Pn=(e,t,n)=>((!Array.isArray(e)||e.length>t||e.some(o=>typeof o!="string"||!o||o.length>255)||new Set(e).size!==e.length)&&U(n),[...e].sort()),Ni=(e,t,n)=>{(typeof e!="string"||!e||e.length>t||e.trim()!==e)&&U(n)},Ti=(e,t)=>{let n;try{n=JSON.stringify(e)}catch{U(t)}(!n||Buffer.byteLength(n)>65536)&&U(t,"EVENT_WORKER_EFFECT_SIZE_EXCEEDED")};function Ya(e,t,n,o=[],r="/execution"){let i=Ue(e,["kind","version","resources","emitEventTypes","maxOperations","maxGuards","maxQueryRecords","maxIntentsPerEvent"],r);(i.kind!=="worker-effect"||i.version!==1||!Array.isArray(i.resources)||!i.resources.length||i.resources.length>16)&&U(r);let s=new Map(t.map(p=>[p.code,p])),a=new Set,d={},c=i.resources.map((p,m)=>{let A=`${r}/resources/${m}`,I=Ue(p,["resourceCode","readFields","writeOperations","writeFields"],A),O=s.get(I.resourceCode);(!O||a.has(I.resourceCode))&&U(A,"EVENT_WORKER_EFFECT_RESOURCE_INVALID"),a.add(I.resourceCode);let b=new Map((O.schema?.fields||[]).map(u=>[u.code,u])),g=Pn(I.readFields,64,`${A}/readFields`),y=Pn(I.writeFields,64,`${A}/writeFields`),h=Pn(I.writeOperations,2,`${A}/writeOperations`);return(h.some(u=>!["create","update"].includes(u))||!!h.length!=!!y.length)&&U(A),(!g.length||g.some(u=>!["id","revision","created_at"].includes(u)&&!b.has(u)))&&U(`${A}/readFields`,"EVENT_WORKER_EFFECT_FIELD_INVALID"),y.some(u=>!b.has(u)||b.get(u).type==="serial-number"||["id","revision","tenant_id","app_code","environment_key","created_at","created_by","updated_at","updated_by"].includes(u))&&U(`${A}/writeFields`,"EVENT_WORKER_EFFECT_FIELD_INVALID"),h.length&&o.includes(I.resourceCode)&&U(A,"EVENT_WORKER_EFFECT_WORKFLOW_RESOURCE_FORBIDDEN"),d[I.resourceCode]=ee(O),{resourceCode:I.resourceCode,readFields:g,writeFields:y,writeOperations:h}}).sort((p,m)=>p.resourceCode.localeCompare(m.resourceCode)),l=Pn(i.emitEventTypes,16,`${r}/emitEventTypes`);l.some(p=>!n.includes(p)||p.startsWith("openxiangda."))&&U(`${r}/emitEventTypes`,"EVENT_WORKER_EFFECT_EVENT_INVALID");let f={kind:"worker-effect",version:1,resources:c,emitEventTypes:l,resourceDigests:d,maxOperations:bt(i.maxOperations,1,8,`${r}/maxOperations`),maxGuards:bt(i.maxGuards,1,24,`${r}/maxGuards`),maxQueryRecords:bt(i.maxQueryRecords,1,500,`${r}/maxQueryRecords`),maxIntentsPerEvent:bt(i.maxIntentsPerEvent,1,100,`${r}/maxIntentsPerEvent`)};return Ti(f,r),{...f,digest:ee(f)}}function Ri(e,t,n){let o=e.resources.find(r=>r.resourceCode===t);return o||U(n,"EVENT_WORKER_EFFECT_RESOURCE_FORBIDDEN"),o}function $n(e,t,n,o=0){o>12&&U(n);let r=Ue(e,["field","operator","value","path","and","or","not"],n);if(r.field!==void 0){(!Wo.has(r.operator)||r.path!==void 0&&(typeof r.path!="string"||!/^(value|label|snapshot\.[A-Za-z][A-Za-z0-9_]{0,62}|[A-Za-z][A-Za-z0-9_]{0,62})$/.test(r.path)))&&U(n),t.includes(r.field)||U(n,"EVENT_WORKER_EFFECT_FIELD_FORBIDDEN"),(r.and!==void 0||r.or!==void 0||r.not!==void 0)&&U(n);return}if(Object.keys(r).length!==1&&U(n),r.not!==void 0)return $n(r.not,t,`${n}/not`,o+1);let s=r.and!==void 0?"and":"or",a=r[s];(!Array.isArray(a)||!a.length||a.length>100)&&U(n),a.forEach((d,c)=>$n(d,t,`${n}/${s}/${c}`,o+1))}function c_(e,t,n){let o=Ue(n,["schemaVersion","select","where","order","limit","offset"],"/query");o.schemaVersion!=="openxiangda.data-query/v2"&&U("/query");let r=Ri(e,t,"/resourceCode"),i=Pn(o.select,64,"/query/select");return(!i.length||i.some(s=>!r.readFields.includes(s)))&&U("/query/select","EVENT_WORKER_EFFECT_FIELD_FORBIDDEN"),bt(o.limit,1,e.maxQueryRecords,"/query/limit"),bt(o.offset??0,0,1e4,"/query/offset"),o.where!==void 0&&$n(o.where,r.readFields,"/query/where"),o.order!==void 0&&((!Array.isArray(o.order)||o.order.length>8)&&U("/query/order"),o.order.forEach((s,a)=>{let d=Ue(s,["field","direction"],`/query/order/${a}`);(!r.readFields.includes(d.field)||!["asc","desc"].includes(d.direction))&&U("/query/order","EVENT_WORKER_EFFECT_FIELD_FORBIDDEN")})),Ti(n,"/query"),n}function l_(e,t){let n=Ue(t,["guards","operations"],"/plan");return Ti(n,"/plan"),(!Array.isArray(n.operations)||!n.operations.length||n.operations.length>e.maxOperations||!Array.isArray(n.guards)||!n.guards.length||n.guards.length>e.maxGuards)&&U("/plan"),n.operations.forEach((o,r)=>{let i=`/plan/operations/${r}`,s=Ue(o,["operation","resourceCode","id","expectedRevision","data","eventType","subject"],i);if(s.operation==="emitEvent"){(s.resourceCode!==void 0||s.id!==void 0||s.expectedRevision!==void 0||!e.emitEventTypes.includes(s.eventType))&&U(i,"EVENT_WORKER_EFFECT_EVENT_INVALID"),s.subject!==void 0&&Ni(s.subject,255,`${i}/subject`),Ue(s.data,Object.keys(s.data||{}),`${i}/data`);return}(!["create","update"].includes(s.operation)||s.eventType!==void 0||s.subject!==void 0)&&U(i);let a=Ri(e,s.resourceCode,i);a.writeOperations.includes(s.operation)||U(i,"EVENT_WORKER_EFFECT_OPERATION_FORBIDDEN");let d=Ue(s.data,a.writeFields,`${i}/data`);Object.keys(d).length||U(`${i}/data`),s.operation==="update"?(hi(s.id)||U(`${i}/id`),bt(s.expectedRevision,1,Number.MAX_SAFE_INTEGER,`${i}/expectedRevision`)):(s.id!==void 0||s.expectedRevision!==void 0)&&U(i)}),n.guards.forEach((o,r)=>{let i=`/plan/guards/${r}`,s=o,a=s?.kind==="record-set-match"?["kind","resourceCode","errorCode","records","where"]:["kind","resourceCode","errorCode","id","assertions","lockKey","where"],d=Ue(o,a,i);["query-empty","record-match","record-assert","record-exists","record-set-match"].includes(d.kind)||U(i,"EVENT_WORKER_EFFECT_GUARD_FORBIDDEN");let c=Ri(e,d.resourceCode,i);if(Ni(d.errorCode,128,`${i}/errorCode`),d.kind==="record-set-match"){(!Array.isArray(d.records)||d.records.length>500||new Set(d.records.map(l=>l?.id)).size!==d.records.length)&&U(i),d.records.forEach(l=>{let f=Ue(l,["id","expectedRevision"],i);hi(f.id)||U(i),bt(f.expectedRevision,1,Number.MAX_SAFE_INTEGER,i)}),d.where!==void 0&&$n(d.where,c.readFields,`${i}/where`);return}if(Ni(d.lockKey,255,`${i}/lockKey`),d.kind==="query-empty"){(d.id!==void 0||d.assertions!==void 0)&&U(i),$n(d.where,c.readFields,`${i}/where`);return}if((!hi(d.id)||d.where!==void 0)&&U(i),d.kind==="record-exists"){d.assertions!==void 0&&U(i);return}(!Array.isArray(d.assertions)||!d.assertions.length||d.assertions.length>32)&&U(i),d.assertions.forEach(l=>{let f=Ue(l,["kind","field","operator","value","path","leftField","rightField"],i);["value","field","database-now"].includes(f.kind)||U(i),(f.kind==="field"?[f.leftField,f.rightField]:[f.field]).some(m=>!c.readFields.includes(m))&&U(i,"EVENT_WORKER_EFFECT_FIELD_FORBIDDEN")})}),t}function u_(e,t){return[e.schemaVersion,t,ee(e)].join(`
9
+ `)}var xo=class extends Error{constructor(n,o){super(o);this.pointer=n}pointer;code="NATIVE_EVENT_ACTION_INVALID"};function Xa(e,t,n="/events/subscriptions",o){if(e.execution===void 0)return;if(e.execution?.kind==="worker-effect"){if(e.platformAccess)throw new xo(`${n}/platformAccess`,"Worker effect grants cannot be combined with other runtime capabilities");return{execution:Ya(e.execution,t,o?.emitEventTypes||[],o?.workflowResources||[],`${n}/execution`),payload:e.payload}}let r=(O,b)=>{throw new xo(`${n}${O}`,b)},i=(O,b,g)=>((!O||typeof O!="object"||Array.isArray(O)||Object.keys(O).some(y=>!g.includes(y)))&&r(b,"Invalid action object or unsupported property"),O),s=i(e.execution,"/execution",["kind","version","operations"]);(s.kind!=="native-data"||s.version!==1)&&r("/execution","Expected native-data version 1"),e.platformAccess&&r("/platformAccess","Native actions do not use application runtime capabilities"),(!Array.isArray(e.eventTypes)||!e.eventTypes.length||e.eventTypes.some(O=>!/^openxiangda\.data\.record\.(created|updated|deleted)\.v2$/.test(O)))&&r("/eventTypes","Native data actions require declared data events");let a=e.filter?.resourceCodes;(!Array.isArray(a)||!a.length||a.length>20)&&r("/filter/resourceCodes","Native actions require explicit source resources");let d=new Map(t.map(O=>[O.code,O])),c=a.map(O=>{let b=d.get(O);return b||r("/filter/resourceCodes","Unknown source resource"),new Set((b.schema?.fields||[]).map(g=>g.code))}),l=new Set(e.payload?.fields||[]),f=e.payload?.includeChanges===!0,p=(O,b)=>{let g=i(O,b,["source","path","value"]);if(g.source==="literal"){(!Object.hasOwn(g,"value")||Object.hasOwn(g,"path"))&&r(b,"Literal binding requires only value");let E;try{E=JSON.stringify(g.value)}catch{r(b,"Literal must be JSON")}return(E===void 0||Buffer.byteLength(E)>65536)&&r(b,"Literal is too large or not JSON"),{source:"literal",value:JSON.parse(E)}}(g.source!=="event"||typeof g.path!="string"||Object.hasOwn(g,"value"))&&r(b,"Expected a literal or event binding");let y=g.path.split(".");(y.length>8||y.some(E=>!/^[A-Za-z0-9_-]+$/.test(E)||["__proto__","prototype","constructor"].includes(E)))&&r(b,"Invalid event path");let h=/^data\.projection\.([A-Za-z][A-Za-z0-9_]{0,62})$/.exec(g.path),u=/^data\.changes\.([A-Za-z][A-Za-z0-9_]{0,62})\.(before|after)$/.exec(g.path);if(h||u){let E=(h||u)[1];c.some(w=>!w.has(E))&&r(b,"Source field must exist on every filtered resource"),l.add(E),u&&(f=!0)}else["id","time","type","subject","data.recordId","data.revision","data.operation","data.resourceCode"].includes(g.path)||r(b,"Event path is not part of the data event contract");return{source:"event",path:g.path}};(!Array.isArray(s.operations)||s.operations.length<1||s.operations.length>16)&&r("/execution/operations","Expected 1 to 16 operations");let m={},A=s.operations.map((O,b)=>{let g=`/execution/operations/${b}`,y=i(O,g,["operation","resourceCode","data","id","expectedRevision"]);["create","update","delete"].includes(y.operation)||r(g,"Unsupported Native operation");let h=d.get(y.resourceCode);h||r(g,"Unknown action target resource");let u=new Map((h.schema?.fields||[]).map(w=>[w.code,w])),E=y.data===void 0?{}:i(y.data,`${g}/data`,[...u.keys()]);return Object.keys(E).length>32&&r(g,"Maximum 32 mapped fields per operation"),y.operation==="create"&&(y.id!==void 0||y.expectedRevision!==void 0)&&r(g,"Create does not accept id or expectedRevision"),y.operation==="delete"&&y.data!==void 0&&r(g,"Delete does not accept data"),Object.keys(E).some(w=>u.get(w)?.type==="serial-number")&&r(g,"Generated fields cannot be assigned"),m[y.resourceCode]=ee(h),{operation:y.operation,resourceCode:y.resourceCode,...y.operation==="create"?{}:{id:p(y.id,`${g}/id`),expectedRevision:p(y.expectedRevision,`${g}/expectedRevision`)},...y.operation==="delete"?{}:{data:Object.fromEntries(Object.entries(E).map(([w,S])=>[w,p(S,`${g}/data/${w}`)]))}}});(l.size>32||[...l].some(O=>c.some(b=>!b.has(O))))&&r("/payload/fields","Payload must contain at most 32 declared source fields");let I={kind:"native-data",version:1,operations:A,resourceDigests:m};return Buffer.byteLength(JSON.stringify(I))>65536&&r("/execution","Action plan exceeds 64 KiB"),{execution:{...I,digest:ee(I)},payload:{includeChanges:f,fields:[...l].sort()}}}function ht(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function Qa(e,t){if(e?.instanceCommands===void 0)return[];let n=ht(e.instanceCommands);if(!n||!Object.keys(n).length||Object.keys(n).some(r=>!["withdraw","terminate"].includes(r)))return["WORKFLOW_INSTANCE_COMMAND_POLICIES_INVALID"];let o=[];for(let[r,i]of Object.entries(n)){let s=ht(i),a=r==="withdraw"?["beforeFact","reasonRequired"]:["beforeFact","capability"];if(!s||!Object.keys(s).length||Object.keys(s).some(d=>!a.includes(d))||Object.hasOwn(s,"reasonRequired")&&typeof s.reasonRequired!="boolean"){o.push(`WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID:${r}`);continue}if(r==="terminate"){let d=s.capability;(typeof d!="string"||d.length>255||!/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(d)||t&&(!d.startsWith(`app:${t.appCode}:`)||!t.capabilities.includes(d)))&&o.push("WORKFLOW_INSTANCE_TERMINATE_CAPABILITY_INVALID")}if(Object.hasOwn(s,"beforeFact")){let d=s.beforeFact,c=ht(e.inputSchema),l=ht(ht(c?.properties)?.[d]),f=ht(ht(e.subject)?.factProjection)?.[d],p=t?.fields.get(f);(typeof d!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(d)||!Array.isArray(c?.required)||!c.required.includes(d)||l?.type!=="string"||l?.format!=="date-time"||typeof f!="string"||t&&(p?.type!=="datetime"||p.nullable===!0))&&o.push(`WORKFLOW_INSTANCE_COMMAND_DEADLINE_FACT_INVALID:${r}`)}}return o}function __(e,t){let n=e?.terminate?.capability;return typeof n=="string"&&/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$/.test(n)&&t.includes(n)}function A_(e){return e?.withdraw?.reasonRequired!==!1}function Za(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[,n,o,r,i,s,a]=t,d=t[8],c=new Date(Date.UTC(Number(n),Number(o),0)).getUTCDate();if(Number(o)<1||Number(o)>12||Number(r)<1||Number(r)>c||Number(i)>23||Number(s)>59||Number(a)>59||d!=="Z"&&(Number(d.slice(1,3))>23||Number(d.slice(4))>59))return null;let l=Date.parse(e);return Number.isFinite(l)?l:null}function E_(e,t,n,o){let r=e?.[t];if(!r||r.beforeFact===void 0)return null;let i=r.beforeFact,s=ht(n),a=i&&s&&Object.hasOwn(s,i)?Za(s[i]):null,d=o instanceof Date?o.getTime():Za(o);return a===null||d===null||!Number.isFinite(d)?"WORKFLOW_V2_CANCELLATION_DEADLINE_INVALID":d<a?null:"WORKFLOW_V2_CANCELLATION_DEADLINE_PASSED"}var Le=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Wt=(e,t)=>typeof e=="string"&&!!e.trim()&&e.length<=t,mu=/^[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*){0,15}$/,Ci=e=>typeof e=="string"&&e.length<=256&&mu.test(e)&&!e.split(".").some(t=>["__proto__","prototype","constructor"].includes(t));function Uo(e,t){let n=Le(e),o=!0;for(let r of t.split(".")){o&&=Array.isArray(n.required)&&n.required.includes(r);let i=Le(n.properties)[r];if(!i||typeof i!="object")return null;n=Le(i)}return{schema:n,required:o}}function Fn(e){let t=new Set,n=[],o=2048,r=(i,s)=>{if(--o<0||s>20){n.push("WORKFLOW_EXPRESSION_BUDGET_EXCEEDED");return}let a=Le(i);if(a.op==="path")Ci(a.path)?t.add(a.path):n.push("WORKFLOW_EXPRESSION_PATH_INVALID");else{if(a.op==="literal")return;if(a.op==="and"||a.op==="or")if(!Array.isArray(a.values)||!a.values.length||a.values.length>128)n.push("WORKFLOW_EXPRESSION_GROUP_INVALID");else for(let d of a.values){if(o<0)break;r(d,s+1)}else a.op==="not"||a.op==="exists"?r(a.value,s+1):["eq","neq","gt","gte","lt","lte","in","contains"].includes(String(a.op))?(r(a.left,s+1),r(a.right,s+1)):n.push("WORKFLOW_EXPRESSION_OPERATOR_INVALID")}};return r(e,0),{paths:[...t],errors:[...new Set(n)]}}function ed(e){if(e?.readability===void 0)return[];let t=[],n=_t(e),o=Le(e.readability);(Object.keys(o).some(a=>!["variables","logic"].includes(a))||!Object.keys(o).length)&&t.push("WORKFLOW_READABILITY_INVALID");let r=Le(o.variables);o.variables!==void 0&&(typeof o.variables!="object"||Array.isArray(o.variables)||o.variables===null)&&t.push("WORKFLOW_VARIABLES_INVALID"),Object.keys(r).length>128&&t.push("WORKFLOW_VARIABLE_LIMIT_EXCEEDED");for(let[a,d]of Object.entries(r)){let c=Le(d);(!Ci(a)||!Uo(n,a))&&t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${a}`),(!Wt(c.label,160)||Object.keys(c).some(l=>!["label","unit","description"].includes(l))||c.unit!==void 0&&!Wt(c.unit,32)||c.description!==void 0&&!Wt(c.description,2e3))&&t.push(`WORKFLOW_VARIABLE_METADATA_INVALID:${a}`)}let i=o.logic===void 0?[]:o.logic;(!Array.isArray(i)||i.length>32)&&t.push("WORKFLOW_LOGIC_LIMIT_INVALID");let s=new Set;for(let a of Array.isArray(i)?i.slice(0,32):[]){let d=Le(a),c=String(d.code||"");e.approvedDelegation&&c==="kernel-approved-delegation"&&t.push("WORKFLOW_LOGIC_PLATFORM_CODE_RESERVED"),(!/^[a-z][a-z0-9-]{2,63}$/.test(c)||s.has(c)||!Wt(d.title,160)||!Wt(d.description,4e3)||Object.keys(d).some(l=>!["code","title","description","phase","nodeId","inputPaths","outputPaths","source"].includes(l)))&&t.push(`WORKFLOW_LOGIC_METADATA_INVALID:${c}`),s.add(c),(!["submission","node_input","completion"].includes(String(d.phase))||d.phase==="node_input"&&!Le(e.nodes)[String(d.nodeId)]||d.phase!=="node_input"&&d.nodeId!==void 0)&&t.push(`WORKFLOW_LOGIC_ANCHOR_INVALID:${c}`);for(let l of["inputPaths","outputPaths"]){let f=d[l];if(!(l==="outputPaths"&&f===void 0))if(!Array.isArray(f)||f.length>32||new Set(f).size!==f.length)t.push(`WORKFLOW_LOGIC_PATHS_INVALID:${c}:${l}`);else for(let p of f)(!Ci(p)||!Uo(n,p))&&t.push(`WORKFLOW_LOGIC_SOURCE_UNKNOWN:${c}:${String(p)}`)}if(d.source!==void 0){let l=Le(d.source);(!Wt(l.path,256)||String(l.path).startsWith("/")||String(l.path).includes("..")||String(l.path).includes("://")||!/^sha256:[a-f0-9]{64}$/.test(String(l.digest))||l.symbol!==void 0&&!Wt(l.symbol,160)||Object.keys(l).some(f=>!["path","symbol","digest"].includes(f)))&&t.push(`WORKFLOW_LOGIC_SOURCE_REFERENCE_INVALID:${c}`)}}for(let a of Object.values(Le(e.nodes))){let d=Le(a),c=Array.isArray(d.branches)?d.branches:[];for(let l of c){if(!l.when)continue;let f=Fn(l.when);t.push(...f.errors.map(p=>`${p}:${d.id}`));for(let p of f.paths)Uo(n,p)||t.push(`WORKFLOW_VARIABLE_SOURCE_UNKNOWN:${d.id}:${p}`)}}return[...new Set(t)]}function Mo(e,t){let n=_t(e),o=rt(e).regions,r=[],i=new Map,s=[];for(let l of Object.values(e.nodes)){if(l.kind==="approval")for(let[f,p,m]of[["approve",l.onApprove,"\u540C\u610F"],["reject",l.onReject,"\u62D2\u7EDD"]])p&&r.push({id:`${l.id}:${f}`,from:l.id,to:p,kind:f,label:m,variablePaths:[]});if(l.kind==="approval"||l.kind==="handle")for(let f of new Set(ot(l)))e.nodes[f]?.kind==="correction"&&r.push({id:`${l.id}:return:${f}`,from:l.id,to:f,kind:"return",label:"\u9000\u56DE\u53D1\u8D77\u4EBA\u8865\u6B63",variablePaths:[]});if(l.kind==="parallel")for(let[f,p]of(l.branches||[]).entries()){let m=p.when?Fn(p.when):{paths:[],errors:[]};for(let A of m.paths)i.has(A)||i.set(A,new Set),i.get(A).add(l.id);r.push({id:`${l.id}:parallel:${p.id}`,from:l.id,to:p.target,kind:"branch",parallelBranch:!0,label:p.title||`\u5206\u652F ${f+1}`,priority:f+1,...p.when?{expression:p.when}:{},variablePaths:m.paths})}if(l.kind==="join"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u5168\u90E8\u5206\u652F\u5B8C\u6210\u540E\u7EE7\u7EED",variablePaths:[]}),l.kind==="handle"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u529E\u7406\u5B8C\u6210",variablePaths:[]}),l.kind==="correction"&&l.next&&r.push({id:`${l.id}:resubmit`,from:l.id,to:l.next,kind:"resubmit",label:"\u91CD\u65B0\u63D0\u4EA4\uFF0C\u6309\u9000\u56DE\u8BBE\u7F6E\u7EE7\u7EED",variablePaths:[]}),l.kind==="cc"&&l.next&&r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:"\u6284\u9001\u540E\u7EE7\u7EED",variablePaths:[]}),l.kind==="action"&&l.next){let f=Object.values(l.inputs||{}).flatMap(p=>p.source==="fact"?[p.path]:[]);for(let p of f)i.has(p)||i.set(p,new Set),i.get(p).add(l.id);r.push({id:`${l.id}:next`,from:l.id,to:l.next,kind:"next",label:ie(l)?"\u53D1\u9001\u540E\u7EE7\u7EED":"\u6210\u529F\u56DE\u6267\u540E\u7EE7\u7EED",variablePaths:f})}if(l.kind==="condition"){for(let[f,p]of(l.branches||[]).entries()){let m=Fn(p.when);for(let A of m.paths)i.has(A)||i.set(A,new Set),i.get(A).add(l.id);r.push({id:`${l.id}:branch:${f}`,from:l.id,to:p.target,kind:"branch",label:p.label||`\u6761\u4EF6 ${f+1}`,priority:f+1,expression:p.when,variablePaths:m.paths}),s.push(...m.errors.map(A=>({code:A,path:l.id})))}l.otherwise&&r.push({id:`${l.id}:default`,from:l.id,to:l.otherwise,kind:"default",label:"\u5747\u4E0D\u6EE1\u8DB3\u65F6",variablePaths:[]})}}let a=[...e.readability?.logic||[]];if(e.approvedDelegation){let l=e.approvedDelegation,f=l.confirmer==="initiator"?"\u7533\u8BF7\u4EBA\u672C\u4EBA":"\u6240\u9009\u4EE3\u7406\u4EBA";a.push({code:"kernel-approved-delegation",title:"\u6279\u51C6\u540E\u6574\u6279\u6388\u6743\u4EE3\u7406",phase:"completion",inputPaths:[l.requestsField],description:`\u6279\u51C6\u65F6\u6838\u9A8C${f}\u5728\u5F53\u524D\u9000\u56DE\u5468\u671F\u5B8C\u6210\u201C${e.nodes[l.confirmationNodeId]?.title||l.confirmationNodeId}\u201D\u7684\u4EBA\u5DE5\u786E\u8BA4\uFF1B\u968F\u540E\u91CD\u65B0\u6838\u9A8C\u53CC\u65B9\u5F53\u524D\u8D26\u53F7\u3001\u804C\u8D23\u3001\u4FEE\u8BA2\u3001\u8303\u56F4\u4E0E\u5B8C\u6574\u6709\u6548\u671F\uFF0C\u6574\u6279\u6388\u6743\uFF08\u6700\u591A${l.maxRequests}\u884C\uFF09\u3002\u4EFB\u4E00\u884C\u5931\u8D25\uFF0C\u6279\u51C6\u4E0E\u5168\u90E8\u6388\u6743\u4E00\u8D77\u56DE\u6EDA\uFF1B\u539F\u547D\u4EE4\u6062\u590D\u4E0D\u91CD\u65B0\u6FC0\u6D3B\u5DF2\u64A4\u9500\u6388\u6743\u3002`})}let c=[...new Set([...i.keys(),...Object.keys(e.readability?.variables||{}),...a.flatMap(l=>[...l.inputPaths,...l.outputPaths||[]])])].slice(0,128).map(l=>{let f=Uo(n,l),p=e.readability?.variables?.[l],m=l.split("."),A=e.subject?.factProjection[m[0]],I=m[0]==="steps"?e.nodes[m[1]]:void 0;return f||s.push({code:"WORKFLOW_VARIABLE_SOURCE_UNKNOWN",path:l}),{path:l,label:p?.label||String(f?.schema.title||l),type:String(f?.schema.type||"unknown"),...p,required:f?.required||!1,usedBy:[...i.get(l)||[]],source:f&&I?.handler?{kind:"step_output",nodeId:I.id,handlerCode:I.handler.code,handlerVersion:I.handler.version}:f&&A&&e.subject?{kind:"subject_field",resourceCode:e.subject.resourceCode,fieldPath:[A,...m.slice(1)].join(".")}:{kind:f?"input":"unknown"}}});return{schemaVersion:"openxiangda.workflow-graph/v2",workflowCode:e.code,definitionDigest:t,startAt:e.startAt,fixedTopology:!0,branchStrategy:"first_match",nodes:Object.values(e.nodes).map(l=>({id:l.id,kind:l.kind,title:l.title||l.id,...l.kind==="parallel"?{parallel:{joinNodeId:l.join,branchNodeIds:o.find(f=>f.parallelNodeId===l.id)?.branches.flatMap(f=>f.nodeIds)||[],branchCount:l.branches?.length||0}}:{},...l.binding?{binding:l.binding}:{},...l.mode?{mode:l.mode}:{},...l.outcome?{outcome:l.outcome}:{},...l.kind==="cc"?{emptyPolicy:l.emptyPolicy,notify:l.notify!==!1}:{},...l.kind==="approval"?{emptyPolicy:l.emptyPolicy||"block",initiatorApprovalPolicy:l.initiatorApprovalPolicy||"manual",...l.completionDeadline?{completionDeadline:{...l.completionDeadline}}:{}}:{},...ie(l)?{presentation:"notification"}:{},...l.kind==="action"&&l.handler&&!ie(l)?{businessStep:{handler:l.handler,inputs:l.inputs||{},outputPaths:Object.keys(Le(l.outputSchema).properties||{}).map(f=>`steps.${l.id}.${f}`)}}:{}})),edges:r,variables:c,logic:a,diagnostics:s}}function gu(e,t=[]){let n=r=>{let i=t.find(s=>s.path===r)?.label;return i&&i!==r?i:void 0},o=n(e);if(o)return o;for(let r=e.lastIndexOf(".");r>0;r=e.lastIndexOf(".",r-1)){let i=n(e.slice(0,r));if(!i)continue;let s=e.slice(r+1);return s==="value"?`${i}\uFF08\u503C\uFF09`:s==="label"?`${i}\uFF08\u663E\u793A\u540D\u79F0\uFF09`:`${i}.${s}`}return e}function jo(e,t=[],n=0){if(!e||n>20)return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";if(e.op==="path")return gu(e.path,t);if(e.op==="literal")return JSON.stringify(e.value)??"\u7F3A\u503C";if(e.op==="and"||e.op==="or")return e.values.slice(0,128).map(s=>`\uFF08${jo(s,t,n+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${jo(e.value,t,n+1)}\uFF09`;if(!("left"in e))return"\u65E0\u6CD5\u8BC6\u522B\u7684\u6761\u4EF6";let o={eq:"=",neq:"\u2260",gt:">",gte:"\u2265",lt:"<",lte:"\u2264",in:"\u5C5E\u4E8E",contains:"\u5305\u542B"},r=e.left.op==="path"?e.left.path:void 0,i=r&&e.right.op==="literal"&&typeof e.right.value=="number"?t.find(s=>s.path===r)?.unit:void 0;return`${jo(e.left,t,n+1)} ${o[e.op]} ${jo(e.right,t,n+1)}${i?` ${i}`:""}`}function td(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!1:e.every(n=>{if(!n||typeof n!="object"||Array.isArray(n)||n.readonlyWhen!==void 0)return!1;if(n.subtable!==void 0){let o=n.subtable;return o&&o.create===!1&&o.delete===!1&&o.reorder===!1&&td(o.fields,t+1)}return n.readonly===!0})}function Vn(e){let t=[];for(let[n,o]of Object.entries(e?.nodes||{}))if(o.initiatorApprovalPolicy!==void 0){if(o.kind!=="approval"||!["manual","auto_approve"].includes(o.initiatorApprovalPolicy)){t.push(`WORKFLOW_INITIATOR_APPROVAL_POLICY_INVALID:${n}`);continue}o.initiatorApprovalPolicy==="auto_approve"&&((o.taskPageCode!==void 0&&(typeof o.taskPageCode!="string"||!td(e.taskPages?.[o.taskPageCode]?.fields))||[o.fieldPolicy?.default,...Object.values(o.fieldPolicy?.fields||{})].some(r=>r==="edit"||r==="edit_required"))&&t.push(`WORKFLOW_INITIATOR_APPROVAL_INPUT_REQUIRED:${n}`),(o.operationPolicy?.approve?.opinion==="required"||o.operationPolicy?.approve?.commentRequired===!0)&&t.push(`WORKFLOW_INITIATOR_APPROVAL_COMMENT_REQUIRED:${n}`))}return t}function w_(e,t,n,o,r){return e.kind==="approval"&&e.initiatorApprovalPolicy==="auto_approve"&&Vn({nodes:{node:e},...r?{taskPages:r}:{}}).length===0&&t!=="return_review"&&!!n&&o.user_id===n&&o.status==="active"&&o.participant_kind==="primary"&&["resolution","resolution_retry"].includes(o.source||"")&&!o.source_participant_id&&!o.delegate_authorization_id}var nd=20,od=200,_u=["fixed_users","initiator","input_users","form_field_users","app_role","app_role_in_scope","previous_node_actor"];function Si(e,t){let n=[];for(let[o,r]of Object.entries(e?.nodes||{})){if(r?.kind!=="cc"||((Object.keys(r).some(d=>!["id","kind","title","binding","next","emptyPolicy","notify","administration"].includes(d))||typeof r.title!="string"||!r.title.trim()||r.title.length>255||typeof r.binding!="string"||!r.binding.trim()||r.binding.length>255||typeof r.next!="string"||!r.next.trim()||!e.nodes?.[r.next]||!["block","skip"].includes(r.emptyPolicy)||r.notify!==void 0&&typeof r.notify!="boolean")&&n.push(`WORKFLOW_CC_NODE_INVALID:${o}`),!t))continue;let i=t.bindings?.[r.binding];if(!i){n.push(`WORKFLOW_CC_BINDING_NOT_FOUND:${o}`);continue}_u.includes(i.provider)||n.push(`WORKFLOW_CC_PROVIDER_INVALID:${o}`);let s=i.min??1,a=i.max??20;(!Number.isSafeInteger(s)||!Number.isSafeInteger(a)||s<1||a<s||a>200||i.provider==="fixed_users"&&(!Array.isArray(i.users)||!i.users.length||i.users.length>a))&&n.push(`WORKFLOW_CC_RECIPIENT_LIMIT_INVALID:${o}`)}return[...new Set(n)]}var Nt=["complete","approve","reject","save_form","return","transfer","delegate","add_assignee"],Bo=["fixed_users","app_role","app_role_in_scope"],Au=["single","any","all","sequence"],ft=e=>!!e&&typeof e=="object"&&!Array.isArray(e),it=(e,t)=>Object.keys(e).every(n=>t.includes(n)),Wn=(e,t,n)=>Array.isArray(e)&&e.length>0&&e.length<=n&&new Set(e).size===e.length&&e.every(o=>typeof o=="string"&&t.includes(o));function cn(e){return e.allowedOperations||(e.kind==="handle"?["complete","save_form","return","transfer","delegate"]:Nt.filter(t=>t!=="complete")).filter(t=>t!=="save_form"||!!e.taskPageCode)}function Eu(e,t){return t?.opinion!==void 0?t.opinion==="required":t?.commentRequired??e==="reject"}function Iu(e,t){return["transfer","delegate","add_assignee","return"].includes(e)?t?.opinion!==void 0?t.opinion==="required":t?.reasonRequired!==!1:!0}var dn=["none","optional","required"];function xt(e,t){return e==="save_form"?"none":t?.opinion?t.opinion:(["complete","approve","reject"].includes(e)?Eu(e,t):Iu(e,t))?"required":"optional"}function ln(e,t){return t?.minimumOpinion??(xt(e,t)==="required"?"required":"none")}function L_(e){return e.hasTaskPage&&(e.operationModel==null||e.operationModel==="configured-v1"&&e.allowedOperations?.includes("save_form")===!0)}function id(e,t,n={},o=!1){let r=["label","commentRequired","reasonRequired","opinion"];if(!ft(e)||!Object.keys(e).length||!it(e,o?[...r,"enabled"]:[...r,"minimumOpinion"])||e.label!==void 0&&(typeof e.label!="string"||!e.label.trim()||e.label.length>40||/[\u0000-\u001f\u007f]/.test(e.label))||e.enabled!==void 0&&(typeof e.enabled!="boolean"||t==="approve"&&!e.enabled)||e.opinion!==void 0&&(!dn.includes(e.opinion)||t==="save_form")||e.minimumOpinion!==void 0&&(!dn.includes(e.minimumOpinion)||t==="save_form")||e.commentRequired!==void 0&&(typeof e.commentRequired!="boolean"||!["complete","approve","reject"].includes(t))||e.reasonRequired!==void 0&&(typeof e.reasonRequired!="boolean"||!["transfer","delegate","add_assignee","return"].includes(t))||e.opinion!==void 0&&[e.commentRequired,e.reasonRequired].some(i=>i!==void 0&&i!==(e.opinion==="required")))return!1;if(o&&(e.opinion!==void 0||e.commentRequired!==void 0||e.reasonRequired!==void 0)){let i=e.opinion??(e.commentRequired??e.reasonRequired?"required":"optional");if(dn.indexOf(i)<dn.indexOf(ln(t,n)))return!1}return!(!o&&e.minimumOpinion!==void 0&&dn.indexOf(xt(t,e))<dn.indexOf(e.minimumOpinion))}function yu(e){if(e.provider!=="conditional")return!!e.scope;try{return ae(e).some(t=>"scope"in t&&!!t.scope)}catch{return!1}}function ki(e,t){let n=[];for(let[o,r]of Object.entries(e?.nodes||{})){if(!ft(r))continue;let i=r.administration,s=r.operationPolicy;if(r.kind==="approval"||r.kind==="handle"){let d=cn(r);d.includes(r.kind==="handle"?"complete":"approve")||n.push(`WORKFLOW_NODE_FORWARD_OPERATION_REQUIRED:${o}`),d.includes("save_form")&&!r.taskPageCode&&n.push(`WORKFLOW_NODE_SAVE_PAGE_REQUIRED:${o}`),r.requiredOperations!==void 0&&(!Wn(r.requiredOperations,Nt,8)||r.requiredOperations.some(c=>!d.includes(c)))&&n.push(`WORKFLOW_NODE_REQUIRED_OPERATIONS_INVALID:${o}`)}if(r.kind==="cc"){(s!==void 0||i!==void 0&&(!ft(i)||!it(i,["assigneeProviders"])))&&n.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${o}`),i?.assigneeProviders!==void 0&&!Wn(i.assigneeProviders,Bo,3)&&n.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${o}`),i?.assigneeProviders?.includes("app_role_in_scope")&&t&&!t.bindings[r.binding||""]?.scope&&n.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${o}`);continue}if(!["approval","handle"].includes(r.kind)){(i!==void 0||s!==void 0)&&n.push(`WORKFLOW_NODE_ADMINISTRATION_APPROVAL_REQUIRED:${o}`);continue}if(s!==void 0&&(!ft(s)||Object.keys(s).length>8||Object.entries(s).some(([d,c])=>!Nt.includes(d)||!cn(r).includes(d)||!id(c,d)))&&n.push(`WORKFLOW_NODE_OPERATION_POLICY_INVALID:${o}`),i===void 0)continue;if(!ft(i)||!it(i,["modes","assigneeProviders","operations"])){n.push(`WORKFLOW_NODE_ADMINISTRATION_INVALID:${o}`);continue}i.modes!==void 0&&(!Wn(i.modes,Au,4)||!i.modes.includes(r.mode))&&n.push(`WORKFLOW_NODE_ADMINISTRATION_MODES_INVALID:${o}`),i.assigneeProviders!==void 0&&!Wn(i.assigneeProviders,Bo,3)&&n.push(`WORKFLOW_NODE_ADMINISTRATION_PROVIDERS_INVALID:${o}`);let a=t?.bindings[r.binding||""];a&&Array.isArray(i.assigneeProviders)&&i.assigneeProviders.includes("app_role_in_scope")&&!yu(a)&&n.push(`WORKFLOW_NODE_ADMINISTRATION_SCOPE_REQUIRED:${o}`),i.operations!==void 0&&(!Wn(i.operations,Nt,8)||i.operations.some(d=>!cn(r).includes(d)))&&n.push(`WORKFLOW_NODE_ADMINISTRATION_OPERATIONS_INVALID:${o}`)}return n}function Di(e,t,n,o,r){let i=[];if(!e||!ft(n)||!Object.keys(n).length||!it(n,["title","description","assignee","mode","operations"]))return["WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID"];let s=n;if(s.assignee===void 0&&s.mode!==void 0&&t?.provider==="conditional")return Di(e,t,{...s,assignee:t},o,r);!s.assignee&&t?.provider==="supervisor_chain"&&t.continuous!==!1&&(s.mode||e.mode)!=="sequence"&&i.push("WORKFLOW_SUPERVISOR_CHAIN_SEQUENCE_REQUIRED"),Object.entries(s.operations||{}).some(([d,c])=>c?.enabled===!1&&e.requiredOperations?.includes(d))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_REQUIRED_OPERATION");for(let d of["title","description"])s[d]!==void 0&&(typeof s[d]!="string"||s[d].length>(d==="title"?255:1e3)||d==="title"&&!s[d].trim())&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PATCH_INVALID");let a=e.administration;if(s.mode!==void 0&&(!["approval","handle"].includes(e.kind)||!a?.modes?.includes(s.mode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_MODE_READONLY"),s.operations!==void 0&&(!["approval","handle"].includes(e.kind)||!ft(s.operations)||!Object.keys(s.operations).length||Object.keys(s.operations).length>8||Object.entries(s.operations).some(([d,c])=>!a?.operations?.includes(d)||!cn(e).includes(d)||!id(c,d,e.operationPolicy?.[d],!0)))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_OPERATION_INVALID"),s.assignee!==void 0){let d=s.assignee,c=a?.assigneeProviders||((e.kind==="approval"||e.kind==="handle")&&t&&Bo.includes(t.provider)?[t.provider]:[]);if(d?.provider==="conditional")if(e.emptyPolicy==="skip"&&i.push("WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED"),!r||!t)i.push("WORKFLOW_V2_NODE_CONFIGURATION_CONDITIONAL_CONTEXT_REQUIRED");else{let l=r.definition.nodes[r.nodeId];if(!l||!("binding"in l)||l.kind!==e.kind||l.binding!==e.binding)i.push("WORKFLOW_V2_NODE_CONFIGURATION_CONDITIONAL_CONTEXT_INVALID");else{"emptyPolicy"in l&&l.emptyPolicy==="skip"&&i.push("WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED"),i.push(...Di(l,void 0,{...s,assignee:void 0},r.definition.taskPages));let f="administration"in l?l.administration?.assigneeProviders:void 0;i.push(...Zt(d,{...r,definition:{...r.definition,nodes:{...r.definition.nodes,[r.nodeId]:{...l,..."mode"in l?{mode:s.mode||l.mode}:{}}}},frozenDefault:t,standardProviders:f||((l.kind==="approval"||l.kind==="handle")&&Bo.includes(t.provider)?[t.provider]:[])}))}}else if(ft(d)&&(!["fixed_users","app_role","app_role_in_scope"].includes(d.provider)||!it(d,d.provider==="fixed_users"?["provider","users"]:["provider","roleCode","roleCodes"])))if(!r||!t||!["approval","handle"].includes(e.kind))i.push("WORKFLOW_V2_NODE_CONFIGURATION_CONDITIONAL_CONTEXT_REQUIRED");else{let l=r.definition.nodes[r.nodeId];!l||!("binding"in l)||l.kind!==e.kind||l.binding!==e.binding?i.push("WORKFLOW_V2_NODE_CONFIGURATION_CONDITIONAL_CONTEXT_INVALID"):(i.push(...Di(l,void 0,{...s,assignee:void 0},r.definition.taskPages)),i.push(...Zt({provider:"conditional",cases:[{when:{op:"literal",value:!1},assignee:d}],otherwise:d},{...r,definition:{...r.definition,nodes:{...r.definition.nodes,[r.nodeId]:{...l,..."mode"in l?{mode:s.mode||l.mode}:{}}}},frozenDefault:t,standardProviders:l.kind==="approval"||l.kind==="handle"?l.administration?.assigneeProviders||[]:[]})))}else if(t?.selectedInputPath&&!["app_role","app_role_in_scope"].includes(d?.provider||"")&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY"),!ft(d)||!["approval","handle","cc"].includes(e.kind)||!c.includes(d.provider)||d.provider==="app_role_in_scope"&&!t?.scope)i.push("WORKFLOW_V2_NODE_CONFIGURATION_PROVIDER_READONLY");else if(d.provider==="fixed_users"){let l=e.kind==="cc"?t?.min??1:e.emptyPolicy==="skip"?0:1,f=e.kind==="cc"?Math.min(t?.max??20,200):200;(!it(d,["provider","users"])||!Array.isArray(d.users)||d.users.length<l||d.users.length>f||new Set(d.users).size!==d.users.length||d.users.some(p=>typeof p!="string"||!p.trim()||p.length>255))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_USERS_INVALID")}else d.roleCodes!==void 0?(!it(d,["provider","roleCodes"])||qt({...d,...d.provider==="app_role_in_scope"?{scope:t?.scope}:{}}).length)&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID"):(!it(d,["provider","roleCode"])||typeof d.roleCode!="string"||!/^[a-z][a-z0-9_-]{0,127}$/.test(d.roleCode))&&i.push("WORKFLOW_V2_NODE_CONFIGURATION_ROLE_INVALID")}return i.push(...Vn({nodes:{node:{...e,operationPolicy:rd(e,s).operationPolicy}},...o?{taskPages:o}:{}})),e.completionDeadline&&rd(e,s).operationPolicy.approve?.commentRequired===!0&&i.push("WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:node"),i}function rd(e,t){let n=Object.fromEntries(cn(e).flatMap(o=>{let r=o,i=t?.operations?.[r],s={...e.operationPolicy?.[r],...i?.label!==void 0?{label:i.label}:{},...i?.commentRequired!==void 0?{commentRequired:i.commentRequired}:{},...i?.reasonRequired!==void 0?{reasonRequired:i.reasonRequired}:{},...i?.opinion!==void 0?{opinion:i.opinion}:{}};return i?.opinion===void 0&&(i?.commentRequired!==void 0||i?.reasonRequired!==void 0)&&s.opinion!==void 0&&(s.opinion=i.commentRequired??i.reasonRequired?"required":"optional"),s.opinion!==void 0&&(["complete","approve","reject"].includes(r)&&(s.commentRequired=s.opinion==="required"),["transfer","delegate","add_assignee","return"].includes(r)&&(s.reasonRequired=s.opinion==="required")),Object.keys(s).length?[[r,s]]:[]}));return{mode:t?.mode||e.mode,initiatorApprovalPolicy:e.initiatorApprovalPolicy||"manual",allowedOperations:cn(e).filter(o=>t?.operations?.[o]?.enabled!==!1),operationPolicy:n,fieldPolicy:{default:e.fieldPolicy?.default||"readonly",fields:{...e.fieldPolicy?.fields}}}}function Ou(e){return e?e.provider==="fixed_users"?!it(e,["provider","users"]):e.provider==="app_role"||e.provider==="app_role_in_scope"?!it(e,["provider","roleCode","roleCodes"]):!0:!1}function v_(e,t){return Ou(t)?structuredClone(t):{...structuredClone(t),...e.selectedInputPath!==void 0?{selectedInputPath:e.selectedInputPath}:{},...e.min!==void 0?{min:e.min}:{},...e.max!==void 0?{max:e.max}:{},...e.delegatable!==void 0?{delegatable:e.delegatable}:{},...e.routing?{routing:structuredClone(e.routing)}:{},...t.provider==="app_role_in_scope"&&e.scope?{scope:structuredClone(e.scope)}:{}}}var sd=["supervisor_chain","fixed_users","input_users","form_field_users","app_role","app_role_in_scope"];function Li(e,t){let n=[];for(let[o,r]of Object.entries(e?.nodes||{}))r.kind==="cc"||r.emptyPolicy===void 0||(r.kind!=="approval"||!["block","skip"].includes(r.emptyPolicy)?n.push(`WORKFLOW_APPROVAL_EMPTY_POLICY_INVALID:${o}`):r.emptyPolicy==="skip"&&t&&!sd.includes(t.bindings?.[r.binding||""]?.provider)&&n.push(`WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED:${o}`));return n}function $_(e,t){return e.kind==="approval"&&e.emptyPolicy==="skip"&&t?.emptyResult==="no_candidates"&&sd.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 ad(e,t){let n=Object.values(e.nodes||{}).filter(o=>o.binding===t);return n.length>0&&n.every(o=>o.kind==="approval"&&o.emptyPolicy==="skip")}function dd(e,t=0){return!Array.isArray(e)||e.length>64||t>1?!0:e.some(n=>!n||typeof n!="object"||Array.isArray(n)||n.required===!0||n.requiredWhen!==void 0||n.subtable!==void 0&&(!n.subtable||dd(n.subtable.fields,t+1)))}function V_(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 cd(e){let t=[];for(let[n,o]of Object.entries(e?.nodes||{})){if(!o||typeof o!="object"||o.completionDeadline===void 0)continue;let r=o.completionDeadline;if(o.kind!=="approval"||!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).length!==2||Object.keys(r).some(s=>!["afterSeconds","action"].includes(s))||r.action!=="approve"||!Number.isInteger(r.afterSeconds)||r.afterSeconds<1||r.afterSeconds>2592e3){t.push(`WORKFLOW_COMPLETION_DEADLINE_INVALID:${n}`);continue}o.allowedOperations&&!o.allowedOperations.includes("approve")&&t.push(`WORKFLOW_COMPLETION_DEADLINE_APPROVE_UNAVAILABLE:${n}`);let i=o.taskPageCode?e.taskPages?.[o.taskPageCode]:void 0;(o.taskPageCode&&(!i||dd(i.fields))||[o.fieldPolicy?.default,...Object.values(o.fieldPolicy?.fields||{})].includes("edit_required")||o.operationPolicy?.approve?.opinion==="required"||o.operationPolicy?.approve?.commentRequired===!0||e.commandHandlers?.approve!==void 0)&&t.push(`WORKFLOW_COMPLETION_DEADLINE_INPUT_REQUIRED:${n}`)}return t}var bu="openxiangda.workflow-rejection-notification/v1",x_=4096;function ld(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function un(e,t){return typeof e=="string"&&e.trim().length>0&&e.length<=t}function vi(e,t){return Object.keys(e).sort().join(",")===t.sort().join(",")}function ud(e){let t=e?.rejectionNotification;return t===void 0?[]:!ld(t)||!vi(t,["recipient","title","summary"])||t.recipient!=="record_last_modifier"||!un(t.title,160)||!un(t.summary,500)?["WORKFLOW_REJECTION_NOTIFICATION_INVALID"]:un(e.subject?.resourceCode,63)?[]:["WORKFLOW_REJECTION_NOTIFICATION_SUBJECT_REQUIRED"]}function j_(e){if(!ld(e)||e.schemaVersion!==bu||e.recipient!=="record_last_modifier"||!un(e.title,160)||!un(e.summary,500))return!1;let t=["schemaVersion","recipient","title","summary","status","sourceRevision"];if(e.status==="ready"){if(!vi(e,[...t,"userId"])||!un(e.userId,255)||!Number.isSafeInteger(e.sourceRevision)||Number(e.sourceRevision)<1)return!1}else if(e.status==="skipped"){if(!vi(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 fd(e,t){let n=e.commandHandlers;if(n===void 0)return[];if(!n||typeof n!="object"||Array.isArray(n)||!Object.keys(n).length||Object.keys(n).some(r=>!["approve","reject","withdraw","resubmit"].includes(r)))return["WORKFLOW_BUSINESS_COMMAND_HANDLERS_INVALID"];let o=[];n.resubmit&&!Object.values(e.nodes||{}).some(r=>r.kind==="correction")&&o.push("WORKFLOW_BUSINESS_CORRECTION_REQUIRED");for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object"||Array.isArray(i)||Object.keys(i).some(a=>!["operationCode","transitionPolicy","derivedSubjectFields"].includes(a))||i.transitionPolicy!==void 0&&(r!=="approve"||i.transitionPolicy!=="workflow")||!/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/.test(i.operationCode||"")){o.push("WORKFLOW_BUSINESS_COMMAND_HANDLER_INVALID");continue}if(i.derivedSubjectFields!==void 0){let a=i.derivedSubjectFields,d=new Set(Object.values(e.subject?.factProjection||{}));(r!=="resubmit"||!Array.isArray(a)||a.length<1||a.length>32||new Set(a).size!==a.length||a.some(c=>typeof c!="string"||!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(c)||!d.has(c)||tn.has(c)||["createdBy","updatedBy","createdAt","updatedAt"].includes(c)||Object.values(e.taskPages||{}).some(l=>l.fields?.some(f=>f.code===c&&f.readonly!==!0))))&&o.push("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID")}if(!t)continue;let s=t.find(a=>a.code===i.operationCode);if(!s){o.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_MISSING");continue}(s.method!=="POST"||s.browser?.exposure!=="authenticated"||s.browser.behavior!=="controlled"||s.browser.idempotency!=="required"||s.browser.fileIntent||s.browser.subject?.resourceCode!==e.subject?.resourceCode||s.browser.subject?.inputField!=="recordId"||!s.platformAccess?.workflow?.codes?.includes(e.code)||!s.platformAccess.workflow.businessCommands?.includes(r))&&o.push("WORKFLOW_BUSINESS_COMMAND_OPERATION_INVALID")}return["approve","reject","withdraw"].some(r=>Object.hasOwn(n,r))&&Object.values(e.nodes||{}).some(r=>r.kind==="approval"&&(r.emptyPolicy==="skip"||r.initiatorApprovalPolicy==="auto_approve"))&&o.push("WORKFLOW_BUSINESS_COMMAND_AUTOMATIC_DECISION_FORBIDDEN"),[...new Set(o)]}var B_={type:"object",additionalProperties:!1,required:["workflowCode","target","recordId","expectedRevision","commandToken","idempotencyKey","input"],properties:{workflowCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},target:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"task"},id:{type:"string",format:"uuid"},command:{enum:["approve","reject","resubmit"]}}},{type:"object",additionalProperties:!1,required:["kind","id","command"],properties:{kind:{const:"instance"},id:{type:"string",format:"uuid"},command:{const:"withdraw"}}}]},recordId:{type:"string",format:"uuid"},expectedRevision:{type:"integer",minimum:1},commandToken:{type:"string",pattern:"^[A-Za-z0-9_-]{43}$"},idempotencyKey:{type:"string",minLength:1,maxLength:128},input:{type:"object",maxProperties:64}}};function K_(e,t,n){if(!(t==="resubmit"&&n===!1))return e.commandHandlers?.[t]}var hu=["fixed_users","initiator","app_role","app_role_in_scope"],Nu=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Pi(e,t){let n=e?.launchPreflight;if(n===void 0)return[];if(!Nu(n)||Object.keys(n).join(",")!=="requiredApprovalNodes"||!Array.isArray(n.requiredApprovalNodes)||n.requiredApprovalNodes.length<1||n.requiredApprovalNodes.length>20||new Set(n.requiredApprovalNodes).size!==n.requiredApprovalNodes.length||n.requiredApprovalNodes.some(r=>typeof r!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(r)))return["WORKFLOW_LAUNCH_PREFLIGHT_INVALID"];let o=[];for(let r of n.requiredApprovalNodes){let i=e.nodes?.[r];if(!i||i.kind!=="approval"){o.push(`WORKFLOW_LAUNCH_PREFLIGHT_NODE_INVALID:${r}`);continue}if(!t)continue;let s=t.bindings?.[i.binding||""];if(!s||s.provider==="conditional"&&De(s).length){o.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${r}`);continue}ae(s).some(a=>!hu.includes(a.provider)||a.candidateField!==void 0)&&o.push(`WORKFLOW_LAUNCH_PREFLIGHT_PROVIDER_UNSUPPORTED:${r}`)}return o}var $i=e=>!!e&&typeof e=="object"&&!Array.isArray(e),wu=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,md=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,pd=/^membership:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,J_=500,H_=262144;function gd(e){if(e?.approvedDelegation===void 0)return[];let t=e.approvedDelegation;if(!$i(t)||Object.keys(t).some(d=>!["confirmationNodeId","confirmer","requestsField","maxRequests"].includes(d))||!md.test(t.confirmationNodeId||"")||!["initiator","delegate"].includes(t.confirmer)||!wu.test(t.requestsField||"")||!Number.isSafeInteger(t.maxRequests)||t.maxRequests<1||t.maxRequests>500)return["WORKFLOW_APPROVED_DELEGATION_POLICY_INVALID"];let n=[],o=e.nodes?.[t.confirmationNodeId];(!o||o.kind!=="approval"||o.mode!=="single"||o.emptyPolicy==="skip"||o.initiatorApprovalPolicy==="auto_approve"||o.completionDeadline||o.administration?.assigneeProviders?.length||o.administration?.modes?.some(d=>d!=="single")||o.allowedOperations?.some(d=>["transfer","delegate","add_assignee","admin_override"].includes(d)))&&n.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_INVALID");let r=e.inputSchema?.properties?.[t.requestsField];(!r||r.type!=="array"||!Number.isSafeInteger(r.maxItems)||r.maxItems<1||r.maxItems>t.maxRequests||!r.items||r.items.type!=="object"||r.items.additionalProperties!==!1||!e.subject?.factProjection?.[t.requestsField])&&n.push("WORKFLOW_APPROVED_DELEGATION_REQUEST_SCHEMA_INVALID"),Object.values(e.nodes||{}).some(d=>d.kind==="end"&&d.outcome==="approved")||n.push("WORKFLOW_APPROVED_DELEGATION_APPROVED_END_REQUIRED");let s=[e.startAt],a=new Set;for(;s.length;){let d=s.pop();if(d===t.confirmationNodeId||a.has(d))continue;a.add(d);let c=e.nodes?.[d];c&&(c.kind==="end"&&c.outcome==="approved"&&n.push("WORKFLOW_APPROVED_DELEGATION_CONFIRMATION_BYPASS"),c.kind==="approval"&&s.push(c.onApprove,c.onReject),c.kind==="condition"&&s.push(c.otherwise,...(c.branches||[]).map(l=>l.target)),(c.kind==="cc"||c.kind==="action")&&s.push(c.next))}return[...new Set(n)]}function Y_(e,t){let n=t?.data?.[e.requestsField],o=()=>{throw new Error("WORKFLOW_APPROVED_DELEGATION_REQUEST_INVALID")};(!Array.isArray(n)||!n.length||n.length>e.maxRequests||n.length>500||new TextEncoder().encode(JSON.stringify(n)).byteLength>262144)&&o();let r=["key","delegatorRoleSubjectKey","delegatorRoleSubjectRevision","delegate","delegateRoleSubjectKey","expectedDelegateRevision","workflowCode","nodeId","validFrom","validTo","reason"],i=(d,c)=>typeof d=="string"&&d.trim().length>0&&d.length<=c,s=d=>{if(typeof d!="string")return!1;let c=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.\d{1,3})?(?:Z|[+-](\d\d):(\d\d))$/.exec(d);if(!c)return!1;let[,l,f,p,m,A,I,O,b]=c,g=Number(l),y=Number(f),h=Number(p),E=[31,g%4===0&&(g%100!==0||g%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return y>=1&&y<=12&&h>=1&&h<=E[y-1]&&Number(m)<=23&&Number(A)<=59&&Number(I)<=59&&(O===void 0||Number(O)<=23&&Number(b)<=59)&&Number.isFinite(Date.parse(d))},a=n.map(d=>$i(d)?((Object.keys(d).some(c=>!r.includes(c))||!i(d.delegatorRoleSubjectKey,255)||!pd.test(d.delegatorRoleSubjectKey)||!i(d.delegateRoleSubjectKey,255)||!pd.test(d.delegateRoleSubjectKey)||!Number.isSafeInteger(d.delegatorRoleSubjectRevision)||d.delegatorRoleSubjectRevision<1||!Number.isSafeInteger(d.expectedDelegateRevision)||d.expectedDelegateRevision<1||!$i(d.delegate)||Object.keys(d.delegate).some(c=>!["value","label"].includes(c))||!i(d.delegate.value,255)||!i(d.delegate.label,200)||!(d.workflowCode===null||i(d.workflowCode,128)&&md.test(d.workflowCode))||!(d.nodeId===null||i(d.nodeId,128)&&/^[A-Za-z0-9._:-]{1,128}$/.test(d.nodeId)&&d.workflowCode)||!s(d.validFrom)||!s(d.validTo)||Date.parse(d.validFrom)>=Date.parse(d.validTo)||!i(d.reason,4e3)||d.key!==void 0&&!i(d.key,128))&&o(),{...d,delegate:{value:d.delegate.value,label:d.delegate.label},validFrom:new Date(d.validFrom).toISOString(),validTo:new Date(d.validTo).toISOString()}):o());return e.confirmer==="delegate"&&new Set(a.map(d=>d.delegate.value)).size!==1&&o(),a}var Ru=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e));function _d(e){let t=e?.nodes||{},n=Object.values(t).filter(a=>a?.kind==="correction");if(!n.length)return[];let o=[],r=a=>a?.kind==="approval"?[a.onApprove,a.onReject]:a?.kind==="parallel"?(Array.isArray(a.branches)?a.branches:[]).map(d=>d.target):a?.kind==="condition"?[...(Array.isArray(a.branches)?a.branches:[]).map(d=>d.target),a.otherwise]:a?.kind==="action"||a?.kind==="cc"||a?.kind==="handle"||a?.kind==="join"?[a.next]:[],i=new Set,s=[e.startAt];for(;s.length;){let a=s.pop();i.has(a)||(i.add(a),s.push(...r(t[a])))}for(let a of n){(!Ru(a)||Object.keys(a).some(c=>!["id","kind","title","taskPageCode","next","reminders"].includes(c))||typeof a.id!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(a.id)||["__proto__","prototype","constructor"].includes(a.id)||t[a.id]!==a||typeof a.title!="string"||!a.title.trim()||a.title.length>255||typeof a.taskPageCode!="string"||!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(a.taskPageCode))&&o.push("WORKFLOW_CORRECTION_NODE_INVALID"),(a.next!==e.startAt||t[a.next]?.kind==="correction")&&o.push("WORKFLOW_CORRECTION_REPLAY_TARGET_INVALID"),(i.has(a.id)||Object.values(t).some(c=>r(c).includes(a.id)))&&o.push("WORKFLOW_CORRECTION_FORWARD_ENTRY_FORBIDDEN"),Object.values(t).some(c=>(c?.kind==="approval"||c?.kind==="handle")&&i.has(c.id)&&ot(c).includes(a.id))||o.push("WORKFLOW_CORRECTION_RETURN_SOURCE_REQUIRED");let d=e.taskPages?.[a.taskPageCode];!d||!Array.isArray(d.fields)?o.push("WORKFLOW_CORRECTION_PAGE_REQUIRED"):d.fields.some(c=>c?.subtable&&Object.values(e.subject?.factProjection||{}).some(l=>l===c.code||l.startsWith(`${c.code}.`)))&&o.push("WORKFLOW_CORRECTION_OWNED_FACTS_UNSUPPORTED")}return[...new Set(o)]}var Ko=class extends Error{constructor(n){super(n);this.code=n}code},eA=["projection","triggerCode","resourceCode","recordId","recordRevision","field","dueAt"];function Ad(e,t,n){let o=i=>{throw new Ko(i)};t.length>100&&o("DATE_TRIGGER_PROJECTION_LIMIT");let r=new Set;for(let i of t){let s=i.filter?.resourceCodes||[];if(Array.isArray(s)||o("DATE_TRIGGER_PROJECTION_INVALID"),s.length&&!s.includes(e))continue;let a=i.payload?.fields||[];(!Array.isArray(a)||a.length>32)&&o("DATE_TRIGGER_PROJECTION_LIMIT");for(let d of a)(typeof d!="string"||!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(d)||["__proto__","constructor","prototype"].includes(d))&&o("DATE_TRIGGER_PROJECTION_FIELD_INVALID"),r.add(d)}if(r.size>64&&o("DATE_TRIGGER_PROJECTION_LIMIT"),n!==void 0){let i=n?.schema?.fields??n?.fields;Array.isArray(i)||o("DATE_TRIGGER_PROJECTION_RESOURCE_INVALID");let s=new Map(i.map(a=>[a.code,a]));for(let a of r){let d=s.get(a);d||o("DATE_TRIGGER_PROJECTION_FIELD_UNKNOWN"),d.type==="subtable"&&o("DATE_TRIGGER_PROJECTION_SUBTABLE_FORBIDDEN"),n.fieldPolicies?.[a]?.mask==="omit"&&o("DATE_TRIGGER_PROJECTION_FIELD_SENSITIVE")}}return[...r].sort()}function tA(e,t){if(!t.length)return e;let n=e?.properties?.projection;if(n?.type!=="object"||!n.properties||typeof n.properties!="object"||Array.isArray(n.properties)||n.additionalProperties!==!1||n.required!==void 0&&!Array.isArray(n.required)||t.some(o=>!Object.hasOwn(n.properties,o))||(n.required||[]).some(o=>!t.includes(o)))throw new Ko("DATE_TRIGGER_PROJECTION_SCHEMA_INVALID");return{...e,properties:{...e.properties,projection:{}}}}var Tu=200,Vi=1024*1024,Cu=65536,yd=lt,Ed=en,jt=new Set(["__proto__","prototype","constructor"]),Od=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,jn=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,Id=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,he=e=>!!e&&typeof e=="object"&&!Array.isArray(e)&&[null,Object.prototype].includes(Object.getPrototypeOf(e)),pt=(e,t)=>he(e)&&Object.keys(e).every(n=>t.includes(n)&&!jt.has(n)),qo=e=>{try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 1/0}},bd=e=>e==null||typeof e=="string"&&!e.trim()||Array.isArray(e)&&e.length===0;function Rt(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((o,r)=>Rt(o,t[r]));if(!he(e)||!he(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(o=>Object.hasOwn(t,o)&&Rt(e[o],t[o]))}function Fi(e,t){let n=t.split(".");if(!(n.some(o=>!Od.test(o)||jt.has(o))||n.length>12))return n.reduce((o,r)=>he(o)&&Object.hasOwn(o,r)?o[r]:void 0,e)}function wt(e,t){switch(e.op){case"literal":return e.value;case"path":return Fi({values:t},e.path);case"and":return e.values.every(n=>!!wt(n,t));case"or":return e.values.some(n=>!!wt(n,t));case"not":return!wt(e.value,t);case"exists":return!bd(wt(e.value,t));default:{let n=wt(e.left,t),o=wt(e.right,t);return e.op==="eq"?Rt(n,o):e.op==="neq"?!Rt(n,o):e.op==="in"?Array.isArray(o)&&o.some(r=>Rt(r,n)):e.op==="contains"?Array.isArray(n)?n.some(r=>Rt(r,o)):typeof n=="string"&&typeof o=="string"&&n.includes(o):typeof n!="number"||typeof o!="number"||!Number.isFinite(n)||!Number.isFinite(o)?!1:e.op==="gt"?n>o:e.op==="gte"?n>=o:e.op==="lt"?n<o:n<=o}}}function xn(e,t,n=0,o={nodes:0}){if(n>8||++o.nodes>64||!he(e))return!1;if(e.op==="literal")return pt(e,["op","value"])&&Object.hasOwn(e,"value")&&qo(e.value)<=4096&&Un(e.value);if(e.op==="path"){if(!pt(e,["op","path"])||typeof e.path!="string")return!1;let r=e.path.split(".");return r[0]==="values"&&r.length>=2&&r.length<=8&&t.has(r[1])&&r.every(i=>jn.test(i)&&!jt.has(i))}return["not","exists"].includes(e.op)?pt(e,["op","value"])&&xn(e.value,t,n+1,o):["and","or"].includes(e.op)?pt(e,["op","values"])&&Array.isArray(e.values)&&e.values.length>0&&e.values.length<=16&&e.values.every(r=>xn(r,t,n+1,o)):["eq","neq","gt","gte","lt","lte","in","contains"].includes(e.op)&&pt(e,["op","left","right"])&&xn(e.left,t,n+1,o)&&xn(e.right,t,n+1,o)}function zo(e,t,n,o=Ed){let r=[],i=e.taskPages;if(i!==void 0&&(!he(i)||Object.keys(i).length===0||Object.keys(i).length>16||qo(i)>Cu))return["WORKFLOW_TASK_PAGES_INVALID"];for(let[s,a]of Object.entries(i||{})){let d=`taskPages.${s}`;if(!Od.test(s)||jt.has(s)||!pt(a,["title","fields"])||typeof a.title!="string"||!a.title.trim()||a.title.length>160||!Array.isArray(a.fields)||!a.fields.length||a.fields.length>Tu){r.push(`WORKFLOW_TASK_PAGE_INVALID:${d}`);continue}let c=new Set(a.fields.map(p=>p?.code));c.size!==a.fields.length&&r.push(`WORKFLOW_TASK_PAGE_DUPLICATE_FIELD:${d}`);let l=0,f=new Set;for(let p of a.fields){if(!pt(p,["code","readonly","required","visibleWhen","requiredWhen","subtable"])||!jn.test(p.code)||jt.has(p.code)||["readonly","required"].some(m=>p[m]!==void 0&&typeof p[m]!="boolean")||p.readonly&&(p.required||p.requiredWhen)){r.push(`WORKFLOW_TASK_PAGE_FIELD_INVALID:${d}`);continue}for(let m of["visibleWhen","requiredWhen"])p[m]!==void 0&&!xn(p[m],c)&&r.push(`WORKFLOW_TASK_PAGE_EXPRESSION_INVALID:${d}.${p.code}.${m}`);if(t){let m=t.get(p.code);if((!m||m.system||m.hidden||m.type==="serial-number"||!p.readonly&&m.widget==="readonly"||!p.readonly&&m.type==="subtable"&&!p.subtable||p.subtable&&m.type!=="subtable")&&r.push(`WORKFLOW_TASK_PAGE_RESOURCE_FIELD_INVALID:${d}.${p.code}`),p.subtable&&m?.subtable){let A=m.subtable;l+=A.maxRows??20,(f.has(A.resourceCode)||!Number.isSafeInteger(A.maxRows??20)||(A.maxRows??20)<1||(A.maxRows??20)>yd||!jn.test(A.foreignKey)||!jn.test(A.orderField)||A.foreignKey===A.orderField)&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`),f.add(A.resourceCode);let I=n?.get(A.resourceCode);n&&(!I||!["uuid","resource-ref.single"].includes(I.get(A.foreignKey)?.type||"")||I.get(A.orderField)?.type!=="number.integer")&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`);for(let O of Array.isArray(p.subtable.fields)?p.subtable.fields:[]){if(!O||typeof O.code!="string")continue;let b=I?.get(O.code);(O.code===A.foreignKey||O.code===A.orderField||I&&(!b||b.system||b.hidden||b.type==="subtable"||!O.readonly&&(b.widget==="readonly"||b.type==="serial-number")))&&r.push(`WORKFLOW_TASK_SUBTABLE_FIELD_UNSUPPORTED:${d}.${p.code}.${O.code}`)}}else p.subtable&&t&&r.push(`WORKFLOW_TASK_SUBTABLE_RELATION_INVALID:${d}.${p.code}`)}p.subtable&&(p.readonly||!pt(p.subtable,["fields","create","delete","reorder"])||["create","delete","reorder"].some(m=>p.subtable?.[m]!==void 0&&typeof p.subtable[m]!="boolean")||!Array.isArray(p.subtable.fields)||p.subtable.fields.some(m=>m?.subtable)?r.push(`WORKFLOW_TASK_SUBTABLE_PAGE_INVALID:${d}.${p.code}`):r.push(...zo({taskPages:{child:{title:"\u5B50\u884C",fields:p.subtable.fields}}},n?.get(t?.get(p.code)?.subtable?.resourceCode||"")).map(m=>`${m}:${d}.${p.code}`)))}(l>Math.min(o,Ed)||l<0||!Number.isSafeInteger(l)||!Number.isSafeInteger(o)||o<1)&&r.push(`WORKFLOW_TASK_SUBTABLE_BUDGET_EXCEEDED:${d}`)}for(let[s,a]of Object.entries(e.nodes||{}))he(a)&&a.taskPageCode!==void 0&&(!["approval","handle","correction"].includes(a.kind)||typeof a.taskPageCode!="string"||!he(i)||!Object.hasOwn(i,a.taskPageCode)?r.push(`WORKFLOW_TASK_PAGE_NOT_FOUND:${s}`):Array.isArray(i[a.taskPageCode]?.fields)&&i[a.taskPageCode].fields.some(d=>d&&(a.fieldPolicy?.fields?.[d.code]||a.fieldPolicy?.default)==="hidden")&&r.push(`WORKFLOW_TASK_PAGE_FIELD_HIDDEN:${s}`));return r}function hd(e,t){return e.fields.map(n=>({code:n.code,visible:n.visibleWhen===void 0||!!wt(n.visibleWhen,t),readonly:n.readonly===!0,required:n.required===!0||n.requiredWhen!==void 0&&!!wt(n.requiredWhen,t)}))}var st=class extends Error{constructor(n,o){super(n);this.code=n;this.field=o}code;field;rowIndex;childField};function rA(e,t){return t.map(n=>({key:String(n.id),id:String(n.id),revision:Number(n.revision),state:"persisted",values:Object.fromEntries(hd({title:"\u5B50\u884C",fields:e.fields},n).filter(o=>o.visible&&!o.readonly).map(o=>[o.code,n[o.code]??null]))}))}function iA(e,t,n,o,r,i=!0,s=0){let a=e.subtable,d=m=>{throw new st(m,e.code)};if(!a||!Number.isSafeInteger(t)||t<1||t>yd||!Number.isSafeInteger(s)||s<0||s>t||!Array.isArray(o)||o.length>2*t||qo(o)>Vi||!Un(o))return d("WORKFLOW_TASK_SUBTABLE_VALUES_INVALID");let c=new Map(n.map(m=>[String(m.id),m])),l=new Set,f=new Set,p=[];for(let m of o){if(!pt(m,["key","state","id","revision","values"])||typeof m.key!="string"||!Id.test(m.key)||l.has(m.key)||!["created","persisted","deleted"].includes(m.state)||!he(m.values))return d("WORKFLOW_TASK_SUBTABLE_ROW_INVALID");if(l.add(m.key),m.state==="created"){if(!a.create||m.id!==void 0||m.revision!==void 0||c.has(m.key))return d("WORKFLOW_TASK_SUBTABLE_CREATE_FORBIDDEN")}else{if(typeof m.id!="string"||m.id!==m.key||!Id.test(m.id)||f.has(m.id)||!Number.isSafeInteger(m.revision)||m.revision<1||!c.has(m.id))return d("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(f.add(m.id),i&&Number(c.get(m.id).revision)!==m.revision)return d("WORKFLOW_TASK_SUBTABLE_REVISION_CONFLICT")}if(m.state==="deleted"){if(!a.delete||Object.keys(m.values).length)return d("WORKFLOW_TASK_SUBTABLE_DELETE_FORBIDDEN");continue}try{Su({title:e.code,fields:a.fields},m.id?c.get(m.id):{},m.values,r)}catch(A){if(!(A instanceof st))throw A;let I=new st(A.code,e.code);throw I.rowIndex=p.length,A.field!==void 0&&(I.childField=A.field),I}p.push(m)}if(f.size!==c.size)return d("WORKFLOW_TASK_SUBTABLE_SCOPE_CONFLICT");if(p.length>t)return d("WORKFLOW_TASK_SUBTABLE_MAX_ROWS_EXCEEDED");if(r&&p.length<s)return d("WORKFLOW_TASK_SUBTABLE_MIN_ROWS_NOT_MET");if(!a.reorder){let m=n.filter(I=>p.some(O=>O.id===String(I.id))).map(I=>String(I.id)),A=p.filter(I=>I.state==="persisted").map(I=>I.id);if(!Rt(m,A)||p.some((I,O)=>I.state==="created"&&p.slice(O+1).some(b=>b.state==="persisted")))return d("WORKFLOW_TASK_SUBTABLE_REORDER_FORBIDDEN")}return o}function Un(e,t={members:0},n=0){return++t.members>5e4||n>12?!1:e===null||typeof e=="boolean"?!0:typeof e=="string"?e.length<=Vi:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length<=1e3&&e.every(o=>Un(o,t,n+1)):he(e)&&Object.entries(e).every(([o,r])=>!jt.has(o)&&Un(r,t,n+1))}function Su(e,t,n,o){if(!he(n)||qo(n)>Vi||!Un(n))throw new st("WORKFLOW_TASK_FORM_VALUES_INVALID");let r={...t,...n},i=new Map(hd(e,r).map(s=>[s.code,s]));for(let s of Object.keys(n)){let a=i.get(s);if(!a||a.readonly||!a.visible)throw new st("WORKFLOW_TASK_FORM_FIELD_NOT_EDITABLE",s)}if(o)for(let s of i.values()){let a=r[s.code],d=e.fields.find(c=>c.code===s.code)?.subtable&&Array.isArray(a)?a.every(c=>he(c)&&c.state==="deleted"):bd(a);if(s.visible&&!s.readonly&&s.required&&d)throw new st("WORKFLOW_TASK_FORM_REQUIRED",s.code)}return r}function sA(e,t,n){let o=JSON.parse(JSON.stringify(t));for(let[s,a]of Object.entries(e.subject?.factProjection||{})){let d=s.split(".");if(!d.length||d.length>12||s.length>128||d[0]==="steps"||d.some(l=>!jn.test(l)||jt.has(l)))throw new st("WORKFLOW_TASK_FORM_FACT_PROJECTION_INVALID");if(!Object.hasOwn(n,a))throw new st("WORKFLOW_TASK_FORM_FACT_FIELD_MISSING",a);let c=o;for(let l of d.slice(0,-1))c=c[l]=he(c[l])?c[l]:{};c[d.at(-1)]=n[a]===void 0?void 0:JSON.parse(JSON.stringify(n[a]))}let r=new Set,i=Object.values(e.nodes||{}).filter(s=>s.kind==="action");for(let s=0;s<=i.length;s++){let a=!1;for(let d of i)he(o.steps)&&Object.hasOwn(o.steps,d.id)&&Object.values(d.inputs||{}).some(c=>c.source==="fact"&&!Rt(Fi(t,c.path),Fi(o,c.path)))&&(delete o.steps[d.id],r.add(d.id),a=!0);if(!a)break}return{facts:o,invalidatedNodeIds:[...r].sort()}}function aA(e,t,n){let o=e.nodes||{};for(let r of n){let i=new Set,s=new Map,a=d=>{if(d===r)return!0;if(s.has(d))return s.get(d);if(i.has(d)||i.size>200)return!1;let c=o[d];if(!he(c)||c.kind==="end")return!1;i.add(d);let l=c.kind==="approval"?[c.onApprove]:c.kind==="condition"?[...(c.branches||[]).map(p=>p.target),c.otherwise]:[c.next],f=l.length>0&&l.every(p=>typeof p=="string"&&a(p));return i.delete(d),s.set(d,f),f};if(!a(t))return!1}return!0}var Wi="^[A-Za-z][A-Za-z0-9_]{0,62}$",Nd="^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$",lA={type:"object",additionalProperties:!1,required:["mode","resourceCode","subtables"],properties:{mode:{const:"create"},resourceCode:{type:"string",maxLength:64,pattern:Nd},subtables:{type:"array",minItems:1,maxItems:16,items:{type:"object",additionalProperties:!1,required:["fieldCode","fieldCodes"],properties:{fieldCode:{type:"string",pattern:Wi},fieldCodes:{type:"array",minItems:1,maxItems:200,uniqueItems:!0,items:{type:"string",pattern:Wi}}}}}}};function Go(e){let t=o=>!!(o&&typeof o=="object"&&!Array.isArray(o)),n=o=>typeof o=="string"&&new RegExp(Wi).test(o)&&!["__proto__","prototype","constructor"].includes(o);if(!t(e)||Object.keys(e).some(o=>!["mode","resourceCode","subtables"].includes(o))||e.mode!=="create"||typeof e.resourceCode!="string"||e.resourceCode.length>64||!new RegExp(Nd).test(e.resourceCode)||!Array.isArray(e.subtables)||e.subtables.length<1||e.subtables.length>16||e.subtables.some(o=>!t(o)||Object.keys(o).some(r=>!["fieldCode","fieldCodes"].includes(r))||!n(o.fieldCode)||!Array.isArray(o.fieldCodes)||o.fieldCodes.length<1||o.fieldCodes.length>200||new Set(o.fieldCodes).size!==o.fieldCodes.length||o.fieldCodes.some(r=>!n(r)))||new Set(e.subtables.map(o=>o.fieldCode)).size!==e.subtables.length)throw new Error("WORKFLOW_OWNED_SUBJECT_CREATE_INVALID")}function uA(e){return Go(e),{mode:"create",resourceCode:e.resourceCode,subtables:e.subtables.map(t=>({fieldCode:t.fieldCode,fieldCodes:[...t.fieldCodes].sort()})).sort((t,n)=>t.fieldCode.localeCompare(n.fieldCode))}}function wd(e,t,n){Go(e);let o=a=>{throw new Error(`WORKFLOW_OWNED_SUBJECT_${a}`)},r=t.get(e.resourceCode);r||o("RESOURCE_MISSING");let i=new Set,s=0;for(let a of e.subtables){let d=r.get(a.fieldCode),c=d?.subtable,l=t.get(c?.resourceCode);(d?.type!=="subtable"||!l||c.resourceCode===e.resourceCode||i.has(c.resourceCode))&&o("RELATION_INVALID"),i.add(c.resourceCode);let f=c.maxRows??20;(!Number.isSafeInteger(f)||f<1||f>lt)&&o("BUDGET_EXCEEDED"),s+=f;for(let p of a.fieldCodes){let m=l.get(p);(!m||["serial-number","subtable"].includes(m.type)||[c.foreignKey,c.orderField].includes(p))&&o("FIELD_INVALID"),["file","image","signature","text.rich"].includes(m.type)&&!n.some(A=>A.resourceCode===c.resourceCode&&A.fieldCodes.includes(p)&&A.intents.includes("create"))&&o("FILE_ACCESS_REQUIRED")}}s>en&&o("BUDGET_EXCEEDED")}import*as er from"crypto";var Rd="native-4",xi="2.0.0-alpha.5",Td={"application-native-2":"1.0.0","application.extended-declaration-capacity":"1.0.0","application.extended-role-capacity":"1.0.0","application.extended-artifact-capacity":"1.0.0","application.high-density-artifact-capacity":"1.0.0","application.extended-configuration-bytes":"1.0.0","application.development-configuration":"2.0.0","authz.native-batch-explain":"1.0.0","authz.organizations":"1.0.0","authz.directory-roles":"1.0.0","data.organizations":"1.0.0","authz.native-management":"1.0.0","authz.native-membership-batch":"1.0.0","deployment.durable-runs":"1.0.0","deployment.platform-executor":"1.0.0","environment.on-demand-production":"1.0.0","environment.runtime-lifecycle":"1.0.0","data.rich-text":"1.0.0","data-api-v2":"1.1.0","data.service-mutations":"1.0.0","data.extended-owned-subtable-capacity":"1.0.0","data.aggregate-owned-subtable-capacity":"1.0.0","data.extended-field-capacity":"1.0.0","data.business-commands":"1.0.0","data.record-edit":"1.0.0","data.native-golden-crud":"1.0.0","data.audit-read-access":"1.0.0","data.managed-files":"1.1.0","data.decimal-reservations":"1.1.0","data.decimal-reservation-lifecycle":"1.0.0","data.unique-keys":"1.1.0","data.user-candidates":"1.0.0","data.field-source-contexts":"1.0.0","application.source-agents":"1.0.0","data.user-candidate-launch-scope":"1.0.0","data.datetime-minute-precision":"1.0.0","data.subtable-minimum-rows":"1.0.0","data.managed-concurrency":"1.0.0","data.managed-concurrency.durable":"1.0.0","workflow.named-input-sources":"1.0.0","workflow.approved-delegation":"1.0.0","directory-v2":"1.0.0","directory.selected-user":"1.0.0","directory.selected-departments":"1.0.0","directory.current-classes":"1.0.0","data.transaction-time-values":"1.0.0","data.record-set-assertions":"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.worker-effects":"1.0.0","events.native-data-actions":"1.0.0","workflow-kernel-v2":"1.0.0","workflow.business-data-command":"1.0.0","workflow.approval-business-command":"1.0.0","workflow.native-stage-guard":"1.0.0","workflow.launch-preflight":"1.0.0","workflow.optional-rejection-comment":"1.0.0","workflow.optional-operation-reason":"1.0.0","workflow.optional-withdrawal-reason":"1.0.0","data.transaction-actor-authority":"1.0.0","data.authenticated-public-projection":"1.0.0","data.parent-read-policy":"1.0.0","data.record-print":"1.0.0","data.workflow-record-deletion":"1.0.0","data.record-comments":"1.0.0","workflow.record-history-read":"1.0.0","workflow.rejection-notification":"1.0.0","workflow.instance-cancellation-policy":"1.0.0","workflow.node-administration":"1.0.0","workflow.assignment-routing":"1.0.0","workflow.conditional-assignment":"1.0.0","workflow.role-union":"1.0.0","workflow.role-input-selection":"1.0.0","workflow.named-owned-create":"1.0.0","workflow.owned-initial-facts":"1.0.0","workflow.initiator-correction":"1.0.0","workflow.correction-business-command":"1.0.0","workflow.correction-derived-subject-facts":"1.0.0","workflow.role-references":"1.0.0","workflow.delegation-management":"1.0.0","workflow.automatic-cc":"1.0.0","workflow.approval-empty-policy":"1.0.0","workflow.initiator-approval-policy":"1.0.0","workflow.platform-notify":"1.0.0","workflow.reminders":"1.0.0","workflow.supervisor-chain":"1.0.0","workflow.return-policy":"1.0.0","workflow.handling-nodes":"1.0.0","workflow.completion-deadline":"1.0.0","workflow.task-page-submit":"1.0.0","workflow.task-private-drafts":"1.0.0","workflow.task-managed-files":"1.0.0","workflow.task-rich-fields":"1.0.0","workflow.task-owned-subtables":"1.0.0","workflow.task-owned-files":"1.0.0","workflow.durable-business-step":"1.0.0","workflow.step-data-transaction":"1.0.0","business-process.durable-command":"1.1.0","workflow.fresh-command-token":"1.0.0","notification-hub-v2":"1.0.0","notification-hub-v2.event-tasks":"1.0.0","authentication.application-login-surface":"1.0.0","public-access.anonymous-owner-records":"1.0.0"};var q=Object.freeze({perspectives:100,resources:512,dataPolicies:512,roles:512,subjectReadSurfaces:50,capabilities:4096,operations:500,eventConsumers:100,eventProducers:1e3,eventSchemas:100,eventTypes:500,workflows:512,routes:2048,adminPages:2048,adminNavigationGroups:100,adminNavigationItems:1024});function Cd(e){let t=(e.surface?.mutationOwner||"native")==="native";return["query","get","create","update","delete"].filter(n=>{let o=e.surface?.generated;return n==="query"?o?.list??!0:n==="get"?o?.detail??!0:o?.[n]??t})}function ji(e){return(e.authz?.roles?.length||0)>256}function Ui(e){let t=(Array.isArray(e.agents)?e.agents:[]).reduce((n,o)=>n+(Array.isArray(o?.tasks)?o.tasks.length:0),0)+(e.data?.resources||[]).filter(n=>n.status!=="retired").reduce((n,o)=>n+Cd(o).length,0)+(e.backend?.operations||[]).filter(n=>n.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(n=>(n?.length||0)>100)||(e.frontend?.routes?.length||0)>500||t>500||(e.frontend?.admin?.navigation||[]).reduce((n,o)=>n+o.items.length,0)>500}var _e=Object.freeze({legacyConfigBytes:4194304,configBytes:8388608,contractBytes:8388608,depth:40,stringBytes:1048576,legacyNodes:1e5,extendedNodes:25e4}),fn=Object.freeze({nodes:5e5});function Mi(e){return Buffer.byteLength(re(e),"utf8")>_e.legacyConfigBytes}function Sd(e,t){let n=0,o=[[e][Symbol.iterator]()];for(;o.length;){let r=o[o.length-1].next();if(r.done){o.pop();continue}if(++n>t)return!0;if(Array.isArray(r.value))o.push(r.value.values());else if(r.value&&typeof r.value=="object"){let i=r.value;o.push((function*(){for(let s of Object.keys(i))i[s]!==void 0&&(yield i[s])})())}}return!1}function Jo(e){return Sd(e,_e.legacyNodes)}function Ho(e){return Sd(e,_e.extendedNodes)}var Mn=["openxiangda.workflow.task.reminded.v2","openxiangda.workflow.node.notified.v2","openxiangda.workflow.node.skipped.v2","openxiangda.workflow.step.requested.v2","openxiangda.workflow.step.result_received.v2","openxiangda.workflow.step.completed.v2","openxiangda.workflow.step.continuation_failed.v2","openxiangda.workflow.instance.started.v2","openxiangda.workflow.instance.cc_added.v2","openxiangda.workflow.instance.completed.v2","openxiangda.workflow.instance.rejected.v2","openxiangda.workflow.instance.returned.v2","openxiangda.workflow.instance.resumed.v2","openxiangda.workflow.instance.withdrawn.v2","openxiangda.workflow.instance.terminated.v2","openxiangda.workflow.task.created.v2","openxiangda.workflow.task.assigned.v2","openxiangda.workflow.task.assignment_pending.v2","openxiangda.workflow.task.assignment_resolution_failed.v2","openxiangda.workflow.task.approved.v2","openxiangda.workflow.task.completed.v2","openxiangda.workflow.task.rejected.v2","openxiangda.workflow.task.returned.v2","openxiangda.workflow.task.resubmitted.v2","openxiangda.workflow.task.transferred.v2","openxiangda.workflow.task.reassigned.v2","openxiangda.workflow.task.delegated.v2","openxiangda.workflow.task.assignee_added.v2","openxiangda.workflow.task.cancelled.v2","openxiangda.workflow.participant.activated.v2","openxiangda.workflow.participant.completed.v2","openxiangda.workflow.participant.rejected.v2","openxiangda.workflow.participant.returned.v2","openxiangda.workflow.participant.transferred.v2","openxiangda.workflow.participant.reassigned.v2","openxiangda.workflow.participant.delegated.v2","openxiangda.workflow.participant.added.v2","openxiangda.workflow.participant.suspended.v2","openxiangda.workflow.participant.resumed.v2","openxiangda.workflow.participant.cancelled.v2"];function Bi(e){let t=e.flatMap(o=>Object.values(o.definition.nodes)),n=t.some(o=>o.kind==="action"&&!ie(o));return Mn.filter(o=>o==="openxiangda.workflow.task.reminded.v2"?t.some(r=>r.reminders):o==="openxiangda.workflow.node.notified.v2"?t.some(ie):o==="openxiangda.workflow.node.skipped.v2"?t.some(r=>r.kind==="approval"&&r.emptyPolicy==="skip"):o.startsWith("openxiangda.workflow.step.")?n:!0)}var Du="openxiangda.config-bundle/v3",Gd="openxiangda.contract-bundle/v3",Dd="openxiangda.native-configuration-projection/v1",Bn=Rd,ku=/^[a-f0-9]{64}$/,Lu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,vu=/^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._*-]+$/,Pu=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,$u=/^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/,Fu=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Vu=/^[A-Za-z][A-Za-z0-9_]{0,62}$/,kd=/^[A-Za-z][A-Za-z0-9_]{0,127}$/,Wu=/^[a-z][a-z0-9]*(?:[-_][a-z0-9]+)*$/,xu=/^[A-Z][A-Z0-9_]*$/,ju=/^[a-z][a-z0-9-]{2,63}$/,Uu=/^[A-Za-z][A-Za-z0-9_-]{0,127}$/,Mu=/^[A-Za-z][A-Za-z0-9_.]{0,127}$/,Bu=16,Ku=2*1024,qu=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"]),zu=new Set(["overview","database","operations","workflow","members","calendar","document","folder","settings"]),Gu=new Set(["complete","save_form","approve","reject","return","transfer","delegate","add_assignee","resubmit","withdraw","terminate","admin_reassign","admin_override","retry_resolution"]),Ju=_e.configBytes,Hu=_e.contractBytes,Yu=_e.depth,qi=_e.stringBytes,Xu="openxiangda.event-handler-manifest/v2",Jd="openxiangda.application-route-manifest/v3",Ld=64,Hd=new Set(["id","revision","created_by","updated_by","created_at","updated_at"]),zi=["openxiangda.data.record.created.v2","openxiangda.data.record.updated.v2","openxiangda.data.record.deleted.v2"],Zu=new Set(Mn),Gi=class extends Error{code;pointer;identifiers;constructor(t,n,o={}){super(t),this.name="NativeConfigurationCompilerError",this.code=t,this.pointer=n,this.identifiers=Object.fromEntries(Object.entries(o).slice(0,8).map(([r,i])=>[r,String(i).slice(0,128)]))}};function wE(e){let t=k(e.appCode,"/appCode",128);Lu.test(t)||_("NATIVE_CONFIG_APP_CODE_INVALID","/appCode");let n=Hi(e.expectedConfigDigest,"/expectedConfigDigest"),o=Hi(e.expectedContractDigest,"/expectedContractDigest"),r=Kd(e.configBytes,Ju,"/configBytes","NATIVE_CONFIG_ARTIFACT_TOO_LARGE"),i=Kd(e.contractBytes,Hu,"/contractBytes","NATIVE_CONTRACT_ARTIFACT_TOO_LARGE");qd(r,n,"/configBytes","NATIVE_CONFIG_DIGEST_MISMATCH"),qd(i,o,"/contractBytes","NATIVE_CONTRACT_DIGEST_MISMATCH");let s=Bd(r,"/configBytes","NATIVE_CONFIG_JSON_INVALID","NATIVE_CONFIG_NOT_CANONICAL"),a=Bd(i,"/contractBytes","NATIVE_CONTRACT_JSON_INVALID","NATIVE_CONTRACT_NOT_CANONICAL");Yo(s,"/config",fn.nodes),Yo(a,"/contracts",fn.nodes),Ho(s)||Yo(a,"/contracts",_e.extendedNodes),Jo(s)||Yo(a,"/contracts",_e.legacyNodes);let d=s,c=a;nf(d,t),of(c,t,n);let l=rf(d,n,c.generatorVersion);qf(l,c,d),re(l)!==re(c)&&_("NATIVE_CONTRACT_CLOSURE_MISMATCH",Yi(l,c,"/contracts"));let f={authz:{appCode:t,...d.authz,perspectives:d.perspectives,capabilityCatalog:l.capabilities},data:{appCode:t,resources:d.data.resources,resourceContracts:l.resources,...l.concurrency?{concurrency:l.concurrency}:{},...l.subjectReadSurfaces?{subjectReadSurfaces:l.subjectReadSurfaces}:{}},events:{appCode:t,...d.events,consumers:l.eventConsumers,producers:l.eventProducers,handlerManifest:l.eventHandlerManifest,eventTypes:l.eventTypes,capturePlans:ef({resources:d.data.resources,dataPolicies:d.authz.dataPolicies,subscriptions:l.eventConsumers,capturePolicies:d.events.capturePolicies})},workflows:{appCode:t,...d.workflows,contracts:l.workflows},runtime:{appCode:t,requirements:d.runtime,backend:d.backend,frontend:d.frontend},contracts:l},p={authz:pn(f.authz),data:pn(f.data),events:pn(f.events),workflows:pn(f.workflows),runtime:pn(f.runtime),contracts:pn(f.contracts)},m={configDigest:n,contractDigest:o,generatorVersion:c.generatorVersion},A=Qu(d),I={schemaVersion:Dd,compilerContractVersion:Bn,appCode:t,source:m,projections:p,requiredPlatformCapabilities:A,aggregateDigest:ee({schemaVersion:Dd,compilerContractVersion:Bn,appCode:t,source:m,requiredPlatformCapabilities:A,projectionDigests:Object.fromEntries(Object.entries(p).map(([O,b])=>[O,b.digest]))})};return ac(I)}function vd(e,t){let n=e.subject,o=t.find(i=>i.code===n?.resourceCode),r=new Set(Object.values(n?.factProjection||{}));return!!o?.schema?.fields?.some(i=>i.type==="subtable"&&r.has(i.code))}function Qu(e){let t=e.authz.roles,n=e.data.resources,o=e.backend.operations,r=o.filter(u=>u.platformAccess?.directory?.mode==="current-initiator"&&u.platformAccess.directory.fields.includes("phone")),i=(e.data.concurrency?.commands||[]).filter(u=>u.execution?.directory?.mode==="current-initiator"&&u.execution.directory.fields.includes("phone")),s=t.some(u=>u.capabilities.some(E=>E.endsWith(":directory:read")))||n.some(u=>u.schema.fields.some(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type)))||o.some(u=>u.platformAccess?.directory||u.platformAccess?.selectedDepartments||u.platformAccess?.directoryClasses),a=!!(e.events.subscriptions.length||e.events.timers.length||e.events.dateTriggers.length||e.events.schemas.length),d=o.some(u=>u.platformAccess?.managedFiles||u.platformAccess?.managedFileCopies)||e.events.subscriptions.some(u=>u.platformAccess?.managedFileCopies),c=e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)||o.some(u=>u.platformAccess?.notification)||e.events.subscriptions.some(u=>u.platformAccess?.notification),l=(u,E,w=!1)=>{let S=n.find(T=>T.code===u.definition.subject?.resourceCode)?.schema.fields||[];return Object.values(u.definition.taskPages||{}).some(T=>T.fields.some(C=>{if(C.readonly)return!1;let v=S.find(H=>H.code===C.code);if(!w&&v&&E.includes(v.type))return!0;if(!C.subtable||!v?.subtable)return!1;let P=n.find(H=>H.code===v.subtable.resourceCode)?.schema.fields||[];return C.subtable.fields.some(H=>!H.readonly&&P.some(ne=>ne.code===H.code&&E.includes(ne.type)))}))},f=e.workflows.definitions.filter(u=>l(u,["file","image","signature","text.rich"])),p=e.workflows.definitions.filter(u=>l(u,["signature","text.rich"])),m=e.workflows.definitions.filter(u=>l(u,["file","image","signature","text.rich"],!0)),A=e.workflows.definitions.filter(u=>u.launch.mode==="standalone"||u.launch.mode==="hidden-handoff"),I=o.some(u=>u.platformAccess?.workflow)||A.length>0,O=A.filter(u=>{let E=u.launch.submission;if(!E)return!1;let w=n.find(S=>S.code===u.definition.subject.resourceCode);return[E.create,E.existing].some(S=>S&&Object.values(S.inputs).some(T=>T.source==="field"&&w?.schema.fields.some(C=>C.code===T.fieldCode&&C.type.startsWith("resource-ref.")&&C.source)))}),b={resources:n},g={perspectives:e.perspectives,authz:e.authz},y={schemaVersion:e.schemaVersion,appCode:e.appCode,frontend:{routes:e.frontend.routes,user:e.frontend.user,admin:e.frontend.admin,devicePolicy:e.frontend.devicePolicy},backend:{operations:o.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[...ji(e)?[{code:"application.extended-role-capacity",declaration:{roles:e.authz.roles.length,maximum:q.roles}}]:[],...Mi(e)?[{code:"application.extended-configuration-bytes",declaration:{legacyConfigBytes:_e.legacyConfigBytes,configBytes:_e.configBytes}}]:[],...Jo(e)?[{code:"application.extended-artifact-capacity",declaration:_e}]:[],...Ho(e)?[{code:"application.high-density-artifact-capacity",declaration:fn}]:[],...e.agents?.length?[{code:"application.source-agents",declaration:e.agents}]:[],...Ui(e)?[{code:"application.extended-declaration-capacity",declaration:{resources:e.data.resources.length,policies:e.authz.dataPolicies.length,roles:e.authz.roles.length,capabilities:e.authz.capabilities.length,definitions:e.workflows.definitions.length,bindings:e.workflows.bindings.length,activations:e.workflows.activations.length,routes:e.frontend.routes.length,navigationItems:e.frontend.admin.navigation.reduce((u,E)=>u+E.items.length,0)}}]:[],...n.some(u=>u.uniqueKeys?.length)?[{code:"data.unique-keys",declaration:n.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}]:[],...n.some(u=>u.decimalReservationLifecycle)?[{code:"data.decimal-reservation-lifecycle",declaration:n.filter(u=>u.decimalReservationLifecycle).map(u=>({code:u.code,decimalReservationLifecycle:u.decimalReservationLifecycle}))}]:[],...o.some(u=>u.platformAccess?.dataCommands)?[{code:"data.business-commands",declaration:o.filter(u=>u.platformAccess?.dataCommands)}]:[],...e.authz.dataPolicies.some(yi)?[{code:"data.parent-read-policy",declaration:e.authz.dataPolicies.filter(yi)}]:[],...e.authz.dataPolicies.some(u=>u.publicRead)?[{code:"data.authenticated-public-projection",declaration:e.authz.dataPolicies.filter(u=>u.publicRead)}]:[],...o.some(u=>u.platformAccess?.roleAssertions?.actorAuthority)?[{code:"data.transaction-actor-authority",declaration:o.filter(u=>u.platformAccess?.roleAssertions?.actorAuthority)}]:[],...o.some(u=>u.platformAccess?.workflowStage)?[{code:"workflow.native-stage-guard",declaration:o.filter(u=>u.platformAccess?.workflowStage)}]:[],...o.some(u=>u.platformAccess?.recordEdit)?[{code:"data.record-edit",declaration:o.filter(u=>u.platformAccess?.recordEdit)}]:[],...o.some(u=>u.platformAccess?.decimalReservation)||e.events.subscriptions.some(u=>u.platformAccess?.decimalReservation)?[{code:"data.decimal-reservations",declaration:[...o.filter(u=>u.platformAccess?.decimalReservation).map(u=>({code:u.code,decimalReservation:u.platformAccess.decimalReservation})),...e.events.subscriptions.filter(u=>u.platformAccess?.decimalReservation).map(u=>({subscriptionCode:u.code,decimalReservation:u.platformAccess.decimalReservation}))]}]:[],{code:"application-native-2",declaration:y},{code:"authz.native-batch-explain",declaration:g},{code:"authz.native-management",declaration:g},{code:"deployment.durable-runs",declaration:y.backend},{code:"deployment.platform-executor",declaration:y.backend},{code:"environment.on-demand-production",declaration:{environments:["preproduction","production"]}},{code:"environment.runtime-lifecycle",declaration:{environments:["preproduction","production"]}},...n.length?[{code:"data-api-v2",declaration:b},{code:"data.native-golden-crud",declaration:b}]:[],...n.some(u=>u.recordComments!==void 0)?[{code:"data.record-comments",declaration:b}]:[],...n.some(u=>u.recordDeletion!==void 0)?[{code:"data.workflow-record-deletion",declaration:b}]:[],...n.some(u=>u.recordPrint!==void 0)?[{code:"data.record-print",declaration:b}]:[],...n.some(u=>u.workflowHistory!==void 0)?[{code:"workflow.record-history-read",declaration:b}]:[],...n.some(Qs)?[{code:"data.audit-read-access",declaration:b}]:[],...n.some(u=>u.schema.fields.some(E=>/^(resource-ref|user|department)\.(single|multiple)$/.test(E.type)))||e.authz.scopeDimensions.some(u=>u.valueSource)?[{code:"data.field-source-contexts",declaration:{resources:n.map(u=>({code:u.code,fields:u.schema.fields.filter(E=>/^(resource-ref|user|department)\.(single|multiple)$/.test(E.type))})),dimensions:e.authz.scopeDimensions.filter(u=>u.valueSource)}}]:[],...s?[{code:"directory-v2",declaration:{roles:t.map(u=>({code:u.code,capabilities:u.capabilities.filter(E=>E.endsWith(":directory:read"))})),resources:n.map(u=>({code:u.code,fields:u.schema.fields.filter(E=>["user.single","user.multiple","department.single","department.multiple"].includes(E.type))})),operations:o.filter(u=>u.platformAccess?.directory).map(u=>({code:u.code,directory:u.platformAccess.directory}))}}]:[],...t.some(u=>u.organizationReach)?[{code:"authz.organizations",declaration:t.filter(u=>u.organizationReach).map(u=>({code:u.code,organizationReach:u.organizationReach}))}]:[],...e.authz.directoryRoleSources?.length?[{code:"authz.directory-roles",declaration:e.authz.directoryRoleSources}]:[],...n.some(u=>u.organization&&u.organization.mode!=="none")?[{code:"data.organizations",declaration:n.filter(u=>u.organization&&u.organization.mode!=="none").map(u=>({code:u.code,organization:u.organization}))}]:[],...o.some(u=>u.platformAccess?.transactionTime)?[{code:"data.transaction-time-values",declaration:o.filter(u=>u.platformAccess?.transactionTime).map(u=>({code:u.code,transactionTime:u.platformAccess.transactionTime}))}]:[],...o.some(u=>u.platformAccess?.transactionTime?.recordSetAssertions)?[{code:"data.record-set-assertions",declaration:o.filter(u=>u.platformAccess?.transactionTime?.recordSetAssertions).map(u=>({code:u.code,transactionTime:u.platformAccess.transactionTime}))}]:[],...o.some(u=>u.platformAccess?.directoryClasses)?[{code:"directory.current-classes",declaration:o.filter(u=>u.platformAccess?.directoryClasses).map(u=>({code:u.code,directoryClasses:u.platformAccess.directoryClasses}))}]:[],...o.some(u=>u.platformAccess?.selectedDepartments)?[{code:"directory.selected-departments",declaration:o.filter(u=>u.platformAccess?.selectedDepartments).map(u=>({code:u.code,selectedDepartments:u.platformAccess.selectedDepartments}))}]:[],...o.some(u=>u.platformAccess?.directory?.mode==="selected-user")?[{code:"directory.selected-user",declaration:o.filter(u=>u.platformAccess?.directory?.mode==="selected-user").map(u=>({code:u.code,directory:u.platformAccess.directory}))}]:[],...r.length||i.length?[{code:"directory.current-initiator-phone",declaration:{operations:r.map(u=>({code:u.code,directory:u.platformAccess.directory})),commands:i.map(u=>({code:u.code,directory:u.execution.directory}))}}]:[],...e.data.resources.some(u=>u.schema.fields.some(E=>E.type==="text.rich"))?[{code:"data.rich-text",declaration:{policyVersion:"rich-text-html/1"}}]:[],...d?[{code:"data.managed-files",declaration:{operations:o.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?.kind==="worker-effect")?[{code:"events.worker-effects",declaration:e.events.subscriptions.filter(u=>u.execution?.kind==="worker-effect")}]:[],...e.events.subscriptions.some(u=>u.execution?.kind==="native-data")?[{code:"events.native-data-actions",declaration:e.events.subscriptions.filter(u=>u.execution?.kind==="native-data")}]:[],...e.events.capturePolicies?.length?[{code:"events.capture-policy",declaration:e.events.capturePolicies}]:[],...e.events.dateTriggers.some(u=>Ad(u.resourceCode,e.events.subscriptions.filter(E=>E.eventTypes.includes(u.eventType)),e.data.resources.find(E=>E.code===u.resourceCode)).length>0)?[{code:"events.date-source-projection",declaration:{triggers:e.events.dateTriggers,subscriptions:e.events.subscriptions}}]:[],...a?[{code:"events-v2",declaration:e.events},{code:"events.durable-receipts",declaration:e.events}]:[],...jr(e.data.resources)?[{code:"data.extended-owned-subtable-capacity",declaration:e.data.resources.filter(u=>jr([u]))}]:[],...Wr(e.data.resources,e.workflows?.definitions||[])?[{code:"data.extended-field-capacity",declaration:{resources:e.data.resources.filter(u=>u.schema.fields.length>100),workflows:(e.workflows?.definitions||[]).filter(u=>Wr([],[u]))}}]:[],...xr(e.data.resources)?[{code:"data.aggregate-owned-subtable-capacity",declaration:e.data.resources.filter(u=>xr([u]))}]:[],...e.data.resources.some(u=>u.schema.fields.some(E=>E.userCandidates!==void 0))?[{code:"data.user-candidates",declaration:e.data.resources.filter(u=>u.schema.fields.some(E=>E.userCandidates!==void 0))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.selectedInputPath!==void 0))?[{code:"workflow.role-input-selection",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.selectedInputPath!==void 0))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.roleCodes!==void 0))?[{code:"workflow.role-union",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.roleCodes!==void 0))}]:[],...e.backend.operations.some(u=>u.platformAccess?.ownedSubject)?[{code:"workflow.named-owned-create",declaration:e.backend.operations.filter(u=>u.platformAccess?.ownedSubject)}]:[],...$r(e.data.resources)?[{code:"data.user-candidate-launch-scope",declaration:e.data.resources.filter(u=>$r([u]))}]:[],...qr(e.data.resources)?[{code:"data.subtable-minimum-rows",declaration:e.data.resources.filter(u=>qr([u]))}]:[],...Kr(e.data.resources)?[{code:"data.datetime-minute-precision",declaration:e.data.resources.filter(u=>Kr([u]))}]:[],...e.workflows.activations.length?[{code:"workflow-kernel-v2",declaration:e.workflows},{code:"workflow.fresh-command-token",declaration:e.workflows}]:[],...e.workflows.definitions.some(u=>u.definition.instanceCommands!==void 0)?[{code:"workflow.instance-cancellation-policy",declaration:e.workflows.definitions.filter(u=>u.definition.instanceCommands!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.instanceCommands?.withdraw?.reasonRequired===!1)?[{code:"workflow.optional-withdrawal-reason",declaration:e.workflows.definitions.filter(u=>u.definition.instanceCommands?.withdraw?.reasonRequired===!1)}]:[],...e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)?[{code:"workflow.rejection-notification",declaration:e.workflows.definitions.filter(u=>u.definition.rejectionNotification!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers!==void 0)||o.some(u=>u.platformAccess?.workflow?.businessCommands)?[{code:"workflow.business-data-command",declaration:{definitions:e.workflows.definitions.filter(u=>u.definition.commandHandlers!==void 0),operations:o.filter(u=>u.platformAccess?.workflow?.businessCommands)}}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.approve?.transitionPolicy==="workflow")?[{code:"workflow.approval-business-command",declaration:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.approve?.transitionPolicy==="workflow")}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.resubmit)||o.some(u=>u.platformAccess?.workflow?.businessCommands?.includes("resubmit"))?[{code:"workflow.correction-business-command",declaration:{definitions:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.resubmit),operations:o.filter(u=>u.platformAccess?.workflow?.businessCommands?.includes("resubmit"))}}]:[],...e.workflows.definitions.some(u=>u.definition.launchPreflight!==void 0)?[{code:"workflow.launch-preflight",declaration:e.workflows.definitions.filter(u=>u.definition.launchPreflight!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)?[{code:"workflow.correction-derived-subject-facts",declaration:e.workflows.definitions.filter(u=>u.definition.commandHandlers?.resubmit?.derivedSubjectFields!==void 0)}]:[],...e.workflows.definitions.some(u=>u.definition.approvedDelegation!==void 0)?[{code:"workflow.approved-delegation",declaration:e.workflows.definitions.filter(u=>u.definition.approvedDelegation!==void 0)}]:[],...e.workflows.definitions.some(u=>vd(u.definition,e.data.resources))?[{code:"workflow.owned-initial-facts",declaration:e.workflows.definitions.filter(u=>vd(u.definition,e.data.resources))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.kind==="correction"))?[{code:"workflow.initiator-correction",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.kind==="correction"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.operationPolicy?.reject?.commentRequired===!1))?[{code:"workflow.optional-rejection-comment",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.operationPolicy?.reject?.commentRequired===!1))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>Object.values(E.operationPolicy||{}).some(w=>w.reasonRequired===!1)))?[{code:"workflow.optional-operation-reason",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>Object.values(E.operationPolicy||{}).some(w=>w.reasonRequired===!1)))}]:[],...O.length?[{code:"workflow.named-input-sources",declaration:O}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.administration!==void 0||E.operationPolicy!==void 0))?[{code:"workflow.node-administration",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.administration!==void 0||E.operationPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.kind==="approval"&&E.emptyPolicy!==void 0))?[{code:"workflow.approval-empty-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.kind==="approval"&&E.emptyPolicy!==void 0))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).some(E=>E.provider==="conditional"))?[{code:"workflow.conditional-assignment",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).some(E=>E.provider==="conditional"))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.provider==="supervisor_chain"))?[{code:"workflow.supervisor-chain",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.provider==="supervisor_chain"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.reminders))?[{code:"workflow.reminders",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.reminders))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>ie(E)))?[{code:"workflow.platform-notify",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>ie(E)))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.returnPolicy!==void 0))?[{code:"workflow.return-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.returnPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.kind==="handle"))?[{code:"workflow.handling-nodes",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.kind==="handle"))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.completionDeadline!==void 0))?[{code:"workflow.completion-deadline",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.completionDeadline!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.initiatorApprovalPolicy!==void 0))?[{code:"workflow.initiator-approval-policy",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.initiatorApprovalPolicy!==void 0))}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.nodes).some(E=>E.kind==="cc"))?[{code:"workflow.automatic-cc",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.nodes).some(E=>E.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(E=>E.definition.taskPages!==void 0)})):[],...f.length?[{code:"workflow.task-managed-files",declaration:f}]:[],...m.length?[{code:"workflow.task-owned-files",declaration:m}]:[],...p.length?[{code:"workflow.task-rich-fields",declaration:p}]:[],...e.workflows.definitions.some(u=>Object.values(u.definition.taskPages||{}).some(E=>E.fields.some(w=>w.subtable)))?[{code:"workflow.task-owned-subtables",declaration:e.workflows.definitions.filter(u=>Object.values(u.definition.taskPages||{}).some(E=>E.fields.some(w=>w.subtable)))}]:[],...e.workflows.definitions.some(u=>u.definition.authoring?.businessSteps?.length||Object.values(u.definition.nodes).some(E=>E.kind==="action"&&!ie(E)))?[{code:"workflow.durable-business-step",declaration:e.workflows.definitions.filter(u=>u.definition.authoring?.businessSteps?.length||Object.values(u.definition.nodes).some(E=>E.kind==="action"&&!ie(E)))}]:[],...e.workflows.definitions.some(u=>[...Object.values(u.definition.nodes),...u.definition.authoring?.businessSteps||[]].some(E=>E.handler?.dataTransaction))?[{code:"workflow.step-data-transaction",declaration:e.workflows.definitions.filter(u=>[...Object.values(u.definition.nodes),...u.definition.authoring?.businessSteps||[]].some(E=>E.handler?.dataTransaction))}]:[],...e.workflows.bindings.some(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.routing!==void 0))?[{code:"workflow.assignment-routing",declaration:e.workflows.bindings.filter(u=>Object.values(u.binding.bindings).flatMap(E=>ae(E)).some(E=>E.routing!==void 0))}]:[],...I?[{code:"business-process.durable-command",declaration:{operations:o.filter(u=>u.platformAccess?.workflow).map(u=>({code:u.code,workflow:u.platformAccess.workflow})),definitions:A,activations:e.workflows.activations.filter(u=>A.some(E=>E.definition.code===u.workflowCode))}}]:[],...o.some(u=>u.platformAccess?.dataMutations)||e.events.subscriptions.some(u=>u.platformAccess?.dataMutations)?[{code:"data.service-mutations",declaration:{operations:o.filter(u=>u.platformAccess?.dataMutations).map(u=>({code:u.code,grants:u.platformAccess.dataMutations})),subscriptions:e.events.subscriptions.filter(u=>u.platformAccess?.dataMutations).map(u=>({code:u.code,grants:u.platformAccess.dataMutations}))}}]:[],...e.events.subscriptions.some(u=>u.platformAccess?.notification?.mode==="business-task")?[{code:"notification-hub-v2.event-tasks",declaration:e.events.subscriptions.filter(u=>u.platformAccess?.notification?.mode==="business-task")}]:[],...c?[{code:"notification-hub-v2",declaration:{...e.workflows.definitions.some(u=>u.definition.rejectionNotification!==void 0)?{rejectionNotifications:e.workflows.definitions.filter(u=>u.definition.rejectionNotification!==void 0)}:{},operations:o.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:E})=>({code:u,contractVersion:u==="data.unique-keys"?n.some(w=>qa(w.schema.fields,w.uniqueKeys)==="1.1.0")?"1.1.0":"1.0.0":Td[u],usageDigest:`sha256:${ee(E)}`})).sort((u,E)=>u.code===E.code?0:u.code<E.code?-1:1)}function ef(e){let t=new Map,n=new Set(e.resources.map(i=>String(i.code)));for(let[i,s]of D(e.capturePolicies===void 0?[]:e.capturePolicies,"/capturePlan/capturePolicies",100).entries()){let a=`/capturePlan/capturePolicies/${i}`,d=N(s,a);R(d,["resourceCode","mode"],a);let c=Q(d.resourceCode,`${a}/resourceCode`);n.has(c)||_("NATIVE_EVENT_CAPTURE_RESOURCE_NOT_FOUND",a,{resourceCode:c}),t.has(c)&&_("NATIVE_EVENT_CAPTURE_POLICY_DUPLICATE",a,{resourceCode:c}),d.mode!=="all"&&d.mode!=="subscribed"&&_("NATIVE_EVENT_CAPTURE_MODE_INVALID",`${a}/mode`),t.set(c,d.mode)}let o=new Map(e.dataPolicies.map((i,s)=>{let a=N(i,`/capturePlan/dataPolicies/${s}`);return[String(a.code),a]})),r=e.subscriptions.map((i,s)=>N(i,`/capturePlan/subscriptions/${s}`));return e.resources.map((i,s)=>{let a=`/capturePlan/resources/${s}`,d=N(i,a),c=Q(d.code,`${a}/code`),l=d.schema?N(d.schema,`${a}/schema`):d,f=new Set(D(l.fields||[],`${a}/schema/fields`,500).map((E,w)=>J(N(E,`${a}/schema/fields/${w}`).code,`${a}/schema/fields/${w}/code`))),p=d.dataPolicyCode?F(d.dataPolicyCode,`${a}/dataPolicyCode`):null,m=p?o.get(p):void 0;p&&!m&&_("NATIVE_EVENT_CAPTURE_AUTHZ_POLICY_NOT_FOUND",a,{resourceCode:c,dataPolicyCode:p});let A=new Set;for(let E of m?.rules||[])A.add(E.parentRead?$o(e.resources,c,E.parentRead,`${a}/parentRead`).foreignKey:String(E.field));if(m?.readExpression)for(let E of an(m.readExpression,`${a}/readExpression`))A.add(E.rule.parentRead?$o(e.resources,c,E.rule.parentRead,`${a}/parentRead`).foreignKey:String(E.rule.field));let I=new Set,O=new Set,b=new Set;for(let[E,w]of r.entries()){let S=D(w.eventTypes,`/capturePlan/subscriptions/${E}/eventTypes`,20).map(String);if(!S.some(P=>P.startsWith("openxiangda.data.")))continue;let T=N(w.filter||{},`/capturePlan/subscriptions/${E}/filter`),C=Array.isArray(T.resourceCodes)?T.resourceCodes.map(String):[];if(C.length&&!C.includes(c))continue;for(let P of S)zi.includes(P)&&b.add(P);for(let P of tf(T,`/capturePlan/subscriptions/${E}/filter`))I.add(P);let v=N(w.payload||{},`/capturePlan/subscriptions/${E}/payload`);for(let P of D(v.fields||[],`/capturePlan/subscriptions/${E}/payload/fields`,32))O.add(J(P,`/capturePlan/subscriptions/${E}/payload/fields`))}let g=new Set([...I,...O]),y=new Set([...g,...A]);y.size>Ld&&_("NATIVE_EVENT_CAPTURE_FIELDS_LIMIT",a,{resourceCode:c,maximum:Ld});for(let E of y)!f.has(E)&&!(A.has(E)&&Hd.has(E))&&_("NATIVE_EVENT_CAPTURE_FIELD_NOT_FOUND",a,{resourceCode:c,field:E});let h=N(d.fieldPolicies||{},`${a}/fieldPolicies`);for(let E of g)h[E]?.mask==="omit"&&_("NATIVE_EVENT_CAPTURE_FIELD_SENSITIVE",a,{resourceCode:c,field:E});let u={resourceCode:c,...t.get(c)==="subscribed"?{capturedEventTypes:[...b].sort()}:{},filterFields:[...I].sort(),projectionFields:[...O].sort(),authorizationFields:[...A].sort(),captureFields:[...y].sort()};return{...u,digest:ee(u)}}).sort((i,s)=>i.resourceCode.localeCompare(s.resourceCode))}function tf(e,t){let n=new Set;for(let[s,a]of D(e.changes||[],`${t}/changes`,16).entries()){let d=N(a,`${t}/changes/${s}`);n.add(J(d.field,`${t}/changes/${s}/field`))}let o=N(e.changedFields||{},`${t}/changedFields`);for(let s of["anyOf","allOf","noneOf"])for(let[a,d]of D(o[s]||[],`${t}/changedFields/${s}`,32).entries())n.add(J(d,`${t}/changedFields/${s}/${a}`));let r=0,i=(s,a,d)=>{d>3&&_("NATIVE_EVENT_FILTER_DEPTH_LIMIT",a);let c=N(s,a);if(c.change){let f=N(c.change,`${a}/change`);n.add(J(f.field,`${a}/change/field`)),r+=1;return}if(c.not){i(c.not,`${a}/not`,d+1);return}let l=c.all?"all":c.any?"any":null;l||_("NATIVE_EVENT_FILTER_CONDITION_INVALID",a);for(let[f,p]of D(c[l],`${a}/${l}`,16).entries())i(p,`${a}/${l}/${f}`,d+1)};return e.where&&i(e.where,`${t}/where`,1),r+=Array.isArray(e.changes)?e.changes.length:0,r>16&&_("NATIVE_EVENT_FILTER_ATOM_LIMIT",t),[...n].sort()}function nf(e,t){R(e,["schemaVersion","compilerContractVersion","appCode","perspectives","authz","backend","data","events","workflows","frontend","runtime"],"/config",["agents"]),Sa(t,e.agents,e.data?.resources||[],{authz:e.authz}),x(e.schemaVersion,Du,"/config/schemaVersion"),x(e.compilerContractVersion,Bn,"/config/compilerContractVersion"),x(e.appCode,t,"/config/appCode"),D(e.perspectives,"/config/perspectives",100);let n=N(e.authz,"/config/authz");try{Oa(e)}catch(f){if(!(f instanceof Cn))throw f;_(f.code,f.pointer)}R(n,["capabilities","roles","scopeDimensions","scopeSources","roleMembershipSources","relationshipGrantSources","dataPolicies","authorizationTransitions"],"/config/authz",["authenticatedUserRoleCode","directoryRoleSources"]),D(n.capabilities,"/config/authz/capabilities",q.capabilities),D(n.roles,"/config/authz/roles",q.roles),D(n.scopeDimensions,"/config/authz/scopeDimensions",100),D(n.scopeSources,"/config/authz/scopeSources",100),D(n.roleMembershipSources,"/config/authz/roleMembershipSources",100),D(n.relationshipGrantSources,"/config/authz/relationshipGrantSources",100),D(n.dataPolicies,"/config/authz/dataPolicies",q.dataPolicies),D(n.authorizationTransitions,"/config/authz/authorizationTransitions",100);let o=N(e.backend,"/config/backend");R(o,["secrets","operations"],"/config/backend"),D(o.secrets,"/config/backend/secrets",100),D(o.operations,"/config/backend/operations",500),xf(o.secrets);let r=N(e.data,"/config/data");R(r,["resources"],"/config/data",["resourceDetailRoutes","subjectReadSurfaces","concurrency"]),D(r.resources,"/config/data/resources",q.resources),r.subjectReadSurfaces!==void 0&&D(r.subjectReadSurfaces,"/config/data/subjectReadSurfaces",q.subjectReadSurfaces),r.resourceDetailRoutes!==void 0&&D(r.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100);let i=N(e.events,"/config/events");R(i,["schemas","subscriptions","timers","dateTriggers"],"/config/events",["capturePolicies"]),D(i.schemas,"/config/events/schemas",100),D(i.subscriptions,"/config/events/subscriptions",100),D(i.timers,"/config/events/timers",100),D(i.dateTriggers,"/config/events/dateTriggers",100);let s=N(e.workflows,"/config/workflows");R(s,["definitions","bindings","activations","providers","editableParameters"],"/config/workflows"),D(s.definitions,"/config/workflows/definitions",q.workflows),D(s.bindings,"/config/workflows/bindings",q.workflows),D(s.activations,"/config/workflows/activations",q.workflows),D(s.providers,"/config/workflows/providers",100),D(s.editableParameters,"/config/workflows/editableParameters",100);let a=N(e.frontend,"/config/frontend");R(a,["routes","user","admin","devicePolicy"],"/config/frontend",["authentication","publicAccess"]),D(a.routes,"/config/frontend/routes",q.routes);let d=N(a.user,"/config/frontend/user");R(d,["applicationTodoCenter"],"/config/frontend/user"),_n(d.applicationTodoCenter,"/config/frontend/user/applicationTodoCenter"),Xi(a.devicePolicy,"/config/frontend/devicePolicy"),Object.prototype.hasOwnProperty.call(a,"authentication")&&Xd(a.authentication,a.routes,e,"/config/frontend/authentication"),Object.prototype.hasOwnProperty.call(a,"publicAccess")&&yf(a.publicAccess,e,"/config/frontend/publicAccess");let c=N(a.admin,"/config/frontend/admin");R(c,["navigation"],"/config/frontend/admin",["access"]),c.access!==void 0&&nr(c.access,"/config/frontend/admin/access",e.appCode),Nf(c.navigation,"/config/frontend/admin/navigation");let l=N(e.runtime,"/config/runtime");R(l,["protocolCapabilities","health"],"/config/runtime"),V(l.protocolCapabilities,"/config/runtime/protocolCapabilities",100),R(N(l.health,"/config/runtime/health"),["livePath","readyPath","versionPath"],"/config/runtime/health"),x(l.health.livePath,"/__platform/health","/config/runtime/health/livePath"),x(l.health.readyPath,"/__platform/ready","/config/runtime/health/readyPath"),x(l.health.versionPath,"/__platform/version","/config/runtime/health/versionPath")}function of(e,t,n){R(e,["schemaVersion","compilerContractVersion","generatorVersion","appCode","configDigest","perspectives","resources","capabilities","operations","eventConsumers","eventProducers","eventSchemas","eventHandlerManifest","eventTypes","workflows","routes","routeManifest","adminPages","adminNavigation"],"/contracts",["authentication","publicAccess","adminAccess","subjectReadSurfaces","concurrency"]),x(e.schemaVersion,Gd,"/contracts/schemaVersion"),x(e.compilerContractVersion,Bn,"/contracts/compilerContractVersion"),k(e.generatorVersion,"/contracts/generatorVersion",128),x(e.appCode,t,"/contracts/appCode"),x(e.configDigest,n,"/contracts/configDigest"),D(e.perspectives,"/contracts/perspectives",q.perspectives),D(e.resources,"/contracts/resources",q.resources),e.subjectReadSurfaces!==void 0&&D(e.subjectReadSurfaces,"/contracts/subjectReadSurfaces",q.subjectReadSurfaces),D(e.capabilities,"/contracts/capabilities",q.capabilities),D(e.operations,"/contracts/operations",q.operations),D(e.eventConsumers,"/contracts/eventConsumers",q.eventConsumers),D(e.eventProducers,"/contracts/eventProducers",q.eventProducers),D(e.eventSchemas,"/contracts/eventSchemas",q.eventSchemas),N(e.eventHandlerManifest,"/contracts/eventHandlerManifest"),V(e.eventTypes,"/contracts/eventTypes",q.eventTypes),D(e.workflows,"/contracts/workflows",q.workflows),D(e.routes,"/contracts/routes",q.routes),Object.prototype.hasOwnProperty.call(e,"authentication")&&Af(e.authentication,"/contracts/authentication"),Object.prototype.hasOwnProperty.call(e,"publicAccess")&&Of(e.publicAccess,"/contracts/publicAccess"),Object.prototype.hasOwnProperty.call(e,"adminAccess")&&nr(e.adminAccess,"/contracts/adminAccess",t),Df(e.routeManifest,"/contracts/routeManifest",t),Tf(e.adminPages,"/contracts/adminPages"),Cf(e.adminNavigation,"/contracts/adminNavigation")}function rf(e,t,n){let o=df(e);$f(e,o),Vf(e),Ff(e),jf(e);let r=e.events.schemas.map((g,y)=>{let h=`/config/events/schemas/${y}`,u=N(g,h),E=k(u.eventType,`${h}/eventType`,255);return E.startsWith("openxiangda.")&&_("NATIVE_EVENT_SCHEMA_RESERVED",`${h}/eventType`,{eventType:E}),x(u.schemaDigest,ee(N(u.jsonSchema,`${h}/jsonSchema`)),`${h}/schemaDigest`),u}),i=new Set([...zi,...Mn,...r.map(g=>String(g.eventType))]),s=new Map(e.data.resources.map(g=>[String(g.code),new Map(g.schema.fields.map(y=>[String(y.code),String(y.type)]))])),a=ue(e.events.subscriptions.map((g,y)=>{let h=`/config/events/subscriptions/${y}`,u=N(g,h),E=V(u.eventTypes,`${h}/eventTypes`,20);E.forEach((C,v)=>{i.has(C)||_("NATIVE_EVENT_TYPE_NOT_REGISTERED",`${h}/eventTypes/${v}`,{eventType:C})});let w=Xa(u,e.data.resources,h,{emitEventTypes:r.map(C=>String(C.eventType)),workflowResources:e.workflows.definitions.map(C=>String(C.definition?.subject?.resourceCode||""))}),S=af(u.delivery,E,`${h}/delivery`),T=sf(u.platformAccess,`${h}/platformAccess`,s,e,u);return{code:F(u.code,`${h}/code`),endpointPath:Je(u.endpointPath,`${h}/endpointPath`),eventTypes:E,filter:N(u.filter,`${h}/filter`),payload:w?.payload||N(u.payload,`${h}/payload`),...w?{execution:w.execution}:{},...T?{platformAccess:T}:{},delivery:S}}),g=>g.code),d=new Map(r.map(g=>[String(g.eventType),String(g.dataSchemaVersion)])),c=ue([...e.data.resources.flatMap(g=>zi.map(y=>({code:`data:${g.code}:${y}`,source:"data",eventType:y,dataSchemaVersion:"2.0.0",resourceCode:g.code}))),...r.map(g=>({code:`app:${g.eventType}`,source:"app",eventType:g.eventType,dataSchemaVersion:g.dataSchemaVersion})),...e.events.timers.map(g=>({code:g.code,source:"timer",eventType:g.eventType,dataSchemaVersion:d.get(String(g.eventType))||"2.0.0"})),...e.events.dateTriggers.map(g=>({code:g.code,source:"date",eventType:g.eventType,dataSchemaVersion:d.get(String(g.eventType))||"2.0.0",resourceCode:g.resourceCode,field:g.field})),...e.workflows.activations.length?Bi(e.workflows.definitions).map(g=>({code:`workflow:${g}`,source:"workflow",eventType:g,dataSchemaVersion:"2.0.0"})):[]],g=>`${g.source}:${g.code}:${g.eventType}`),l=K([...a.flatMap(g=>g.eventTypes),...c.map(g=>String(g.eventType))]);Rf(e);let f=ec(e),p;try{p=la(e.data.concurrency,e.data.resources,o)}catch(g){throw g instanceof wn&&_(g.code,g.pointer,{reason:g.reason}),g}p?.commands.some(g=>g.mode==="durable")&&e.backend?.enabled===!1&&_("NATIVE_MANAGED_CONCURRENCY_INVALID","/data/concurrency",{reason:"durable commands require backend runtime"});let m=lf(e,o),A=Yd(e),I=e.workflows.definitions.map(g=>g.definition),O=Nr(I),b=bs(I,a,!0);b.length&&_(b[0],"/config/events/subscriptions");try{fa(e.data.resources,A)}catch(g){throw g instanceof rn&&_(g.code,g.pointer,{reason:g.reason}),g}return{schemaVersion:Gd,compilerContractVersion:Bn,generatorVersion:n,appCode:e.appCode,configDigest:t,perspectives:e.perspectives,resources:cf(e),...m.length?{subjectReadSurfaces:m}:{},...p?{concurrency:p}:{},capabilities:ue(o,g=>g.code),operations:A,eventConsumers:a,eventProducers:c,eventSchemas:r,eventHandlerManifest:{schemaVersion:Xu,appCode:e.appCode,handlers:a.filter(g=>g.execution?.kind!=="native-data").map(g=>({code:g.code,endpointPath:g.endpointPath,eventTypes:g.eventTypes,dataSchemaVersions:K(g.eventTypes.map(y=>y.startsWith("openxiangda.")?"2.0.0":d.get(y)||"2.0.0")),maxBodyBytes:65536,receiptProtocolVersion:2,...O[g.code]?{workflowStep:O[g.code]}:{}}))},eventTypes:l,workflows:oc(e),routes:tr(e),...Object.prototype.hasOwnProperty.call(e.frontend,"authentication")?{authentication:Ef(e)}:{},...Object.prototype.hasOwnProperty.call(e.frontend,"publicAccess")?{publicAccess:bf(e)}:{},...e.frontend.admin.access?{adminAccess:e.frontend.admin.access}:{},routeManifest:vf(e),adminPages:f,adminNavigation:hf(e)}}function sf(e,t,n,o,r){if(e===void 0)return;let i=N(e,t);R(i,["notification","managedFileCopies","decimalReservation","dataMutations"],t,!0);let s={};if(i.dataMutations!==void 0)try{s.dataMutations=Ei(i.dataMutations,n)}catch{_("NATIVE_EVENT_DATA_MUTATIONS_INVALID",`${t}/dataMutations`)}if(i.decimalReservation!==void 0)try{s.decimalReservation=Ga(i.decimalReservation,Ja(o,r))}catch{_("NATIVE_EVENT_DECIMAL_RESERVATION_INVALID",`${t}/decimalReservation`)}if(i.notification!==void 0){let a=N(i.notification,`${t}/notification`);if(a.mode==="business-task"){R(a,["mode","taskCodes"],`${t}/notification`);let d=D(a.taskCodes,`${t}/notification/taskCodes`,16).map((c,l)=>F(c,`${t}/notification/taskCodes/${l}`));(!d.length||new Set(d).size!==d.length||d.some(c=>!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(c)))&&_("NATIVE_EVENT_TASK_CODES_INVALID",`${t}/notification/taskCodes`),s.notification={mode:"business-task",taskCodes:d}}else R(a,["mode"],`${t}/notification`),x(a.mode,"business-standard",`${t}/notification/mode`),s.notification={mode:"business-standard"}}if(i.managedFileCopies!==void 0){let a=D(i.managedFileCopies,`${t}/managedFileCopies`,16);a.length||_("NATIVE_EVENT_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let d=new Set;s.managedFileCopies=ue(a.map((c,l)=>{let f=`${t}/managedFileCopies/${l}`,p=N(c,f);R(p,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],f),x(p.mode,"copy",`${f}/mode`);let m=Q(p.sourceResourceCode,`${f}/sourceResourceCode`),A=Q(p.targetResourceCode,`${f}/targetResourceCode`),I=n.get(m),O=n.get(A);(!I||!O)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_RESOURCE_INVALID",f);let b=V(p.sourceFieldCodes,`${f}/sourceFieldCodes`,16),g=V(p.targetFieldCodes,`${f}/targetFieldCodes`,16);(!b.length||b.length!==g.length)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_FIELDS_INVALID",f),b.forEach((h,u)=>{let E=I.get(h),w=O.get(g[u]);(!["file","image","text.rich"].includes(String(E))||E!==w)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_FIELD_INVALID",`${f}/sourceFieldCodes/${u}`)});let y=`${m}:${b.join(",")}=>${A}:${g.join(",")}`;return d.has(y)&&_("NATIVE_EVENT_MANAGED_FILE_COPY_DUPLICATE",f),d.add(y),{mode:"copy",sourceResourceCode:m,sourceFieldCodes:K(b),targetResourceCode:A,targetFieldCodes:K(g)}}),c=>`${c.sourceResourceCode}:${c.sourceFieldCodes.join(",")}=>${c.targetResourceCode}:${c.targetFieldCodes.join(",")}`)}return Object.keys(s).length||_("NATIVE_EVENT_PLATFORM_ACCESS_EMPTY",t),s}function af(e,t,n){let o=N(e,n);R(o,["timeoutMs","maxAttempts","initialBackoffMs","maxBackoffMs","ordering","concurrency"],n),Ae(o.timeoutMs,`${n}/timeoutMs`,1e3,3e4),Ae(o.maxAttempts,`${n}/maxAttempts`,1,12);let r=Ae(o.initialBackoffMs,`${n}/initialBackoffMs`,1e3,3e5);Ae(o.maxBackoffMs,`${n}/maxBackoffMs`,r,18e5),Ae(o.concurrency,`${n}/concurrency`,1,50);let i=k(o.ordering,`${n}/ordering`,32);return["none","record","workflow-instance"].includes(i)||_("NATIVE_EVENT_DELIVERY_ORDERING_INVALID",`${n}/ordering`),i==="workflow-instance"&&t.some(s=>!Zu.has(s))&&_("NATIVE_EVENT_WORKFLOW_ORDERING_REQUIRES_WORKFLOW_FACTS",`${n}/ordering`),o}function df(e){let t=new Map;for(let i of sc(e.appCode))t.set(i.code,i);for(let[i,s]of e.authz.capabilities.entries()){let a=`/config/authz/capabilities/${i}`,d=N(s,a);R(d,["code","kind","name","description"],a,!0);let c=ve(d.code,`${a}/code`,e.appCode);t.has(c)&&_("NATIVE_CAPABILITY_DUPLICATE",`${a}/code`),["backend","ui"].includes(d.kind)||_("NATIVE_CAPABILITY_KIND_INVALID",`${a}/kind`);let l={code:c,kind:d.kind,name:k(d.name,`${a}/name`,255),source:"explicit",...d.description===void 0?{}:{description:Qi(d.description,`${a}/description`,2e3)}};t.set(c,l)}let n=e.data.resources.map((i,s)=>({pointer:`/config/data/resources/${s}`,resource:Ut(i,`/config/data/resources/${s}`,e.appCode)}));for(let{pointer:i,resource:s}of n){let a={read:`\u8BFB\u53D6${s.name}`,create:`\u65B0\u5EFA${s.name}`,update:`\u66F4\u65B0${s.name}`,delete:`\u5220\u9664${s.name}`};for(let d of["read","create","update","delete"]){let c=ve(s.capabilities[d],`${i}/capabilities/${d}`,e.appCode);t.has(c)&&_("NATIVE_CAPABILITY_DUPLICATE",`${i}/capabilities/${d}`),t.set(c,{code:c,kind:"data",name:a[d],source:"data"})}}let o=new Set(t.keys()),r=new Map;for(let{pointer:i,resource:s}of n)for(let[a,d]of Object.entries(s.fieldPolicies)){if(Vt(a))continue;let c=N(d,`${i}/fieldPolicies/${a}`);for(let l of["read","create","update"])if(Array.isArray(c[l]))for(let f of V(c[l],`${i}/fieldPolicies/${a}/${l}`,2e3)){if(ve(f,`${i}/fieldPolicies/${a}/${l}`,e.appCode),o.has(f))continue;let p=r.get(f);p&&p!==s.code&&_("NATIVE_CAPABILITY_DUPLICATE",`${i}/fieldPolicies/${a}/${l}`),r.set(f,s.code),!t.has(f)&&t.set(f,{code:f,kind:"data",name:`${s.name}.${a}.${l}`,source:"data"})}}return[...t.values()]}function cf(e){let t=uf(e);return ue(e.data.resources.map((n,o)=>{let r=Ut(n,`/config/data/resources/${o}`,e.appCode),i=t.get(r.code);return{code:r.code,schemaDigest:ee(r.schema),fields:ue(r.schema.fields.map(s=>({code:s.code,type:s.type})),s=>s.code),...i?{detailRouteCode:i}:{}}}),n=>n.code)}function lf(e,t){if(e.data.subjectReadSurfaces===void 0)return[];let n=D(e.data.subjectReadSurfaces,"/config/data/subjectReadSurfaces",q.subjectReadSurfaces),o=new Set(t.map(s=>String(s.code))),r=new Map(e.data.resources.map((s,a)=>{let d=`/config/data/resources/${a}`,c=Ut(s,d,e.appCode);return[String(c.code),{resource:c,fields:new Map(D(N(c.schema,`${d}/schema`).fields,`${d}/schema/fields`,500).map(l=>{let f=N(l,`${d}/schema/fields`);return[String(f.code),f]}))}]})),i=new Set;return ue(n.map((s,a)=>{let d=`/config/data/subjectReadSurfaces/${a}`,c=N(s,d);R(c,["code","name","capability","subject","relations"],d);let l=F(c.code,`${d}/code`);i.has(l)&&_("NATIVE_SUBJECT_READ_SURFACE_CODE_DUPLICATE",`${d}/code`),i.add(l);let f=ve(c.capability,`${d}/capability`,e.appCode);o.has(f)||_("NATIVE_SUBJECT_READ_SURFACE_CAPABILITY_NOT_DECLARED",`${d}/capability`);let p=N(c.subject,`${d}/subject`);R(p,["resourceCode","fields"],`${d}/subject`);let m=Q(p.resourceCode,`${d}/subject/resourceCode`),A=r.get(m);A||_("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${d}/subject/resourceCode`);let I=V(p.fields,`${d}/subject/fields`,100).map((h,u)=>J(h,`${d}/subject/fields/${u}`));I.length||_("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${d}/subject/fields`);for(let[h,u]of I.entries()){let E=A.fields.get(u);(!E||E.type==="subtable")&&_("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${d}/subject/fields/${h}`)}let O=D(c.relations,`${d}/relations`,8);O.length||_("NATIVE_SUBJECT_READ_SURFACE_RELATIONS_REQUIRED",`${d}/relations`);let b=new Set,g=0,y=ue(O.map((h,u)=>{let E=`${d}/relations/${u}`,w=N(h,E);R(w,["code","resourceCode","foreignKeyField","fields","limit"],E,["order"]);let S=F(w.code,`${E}/code`);b.has(S)&&_("NATIVE_SUBJECT_READ_SURFACE_RELATION_CODE_DUPLICATE",`${E}/code`),b.add(S);let T=Q(w.resourceCode,`${E}/resourceCode`),C=r.get(T);C||_("NATIVE_SUBJECT_READ_SURFACE_RESOURCE_NOT_DECLARED",`${E}/resourceCode`);let v=J(w.foreignKeyField,`${E}/foreignKeyField`),P=C.fields.get(v),H=N(P?.source||{},`${E}/foreignKeyField/source`);(!P||!["uuid","resource-ref.single"].includes(String(P.type))||P.type==="resource-ref.single"&&(H.kind!=="resource"||H.resourceCode!==m))&&_("NATIVE_SUBJECT_READ_SURFACE_RELATION_INVALID",`${E}/foreignKeyField`);let ne=V(w.fields,`${E}/fields`,100).map((Ee,Ie)=>J(Ee,`${E}/fields/${Ie}`));ne.length||_("NATIVE_SUBJECT_READ_SURFACE_FIELDS_REQUIRED",`${E}/fields`);for(let[Ee,Ie]of ne.entries()){let fe=C.fields.get(Ie);(!fe||fe.type==="subtable")&&_("NATIVE_SUBJECT_READ_SURFACE_FIELD_INVALID",`${E}/fields/${Ee}`)}let Z=D(w.order||[],`${E}/order`,10).map((Ee,Ie)=>{let fe=`${E}/order/${Ie}`,ye=N(Ee,fe);R(ye,["field","direction"],fe);let $=J(ye.field,`${fe}/field`),Y=C.fields.get($);return(!Hd.has($)&&!Y||Y?.type==="subtable"||Y&&!Nn(Y.type))&&_("NATIVE_SUBJECT_READ_SURFACE_ORDER_FIELD_INVALID",`${fe}/field`),["asc","desc"].includes(String(ye.direction))||_("NATIVE_SUBJECT_READ_SURFACE_ORDER_DIRECTION_INVALID",`${fe}/direction`),{field:$,direction:ye.direction}}),Ce=Ae(w.limit,`${E}/limit`,1,100);return g+=Ce,{code:S,resourceCode:T,foreignKeyField:v,fields:K(ne),...Z.length?{order:Z}:{},limit:Ce}}),h=>h.code);return g>400&&_("NATIVE_SUBJECT_READ_SURFACE_ROW_LIMIT_EXCEEDED",`${d}/relations`),{code:l,name:k(c.name,`${d}/name`,255),capability:f,subject:{resourceCode:m,fields:K(I)},relations:y}}),s=>s.code)}function uf(e){let t=e.data.resourceDetailRoutes===void 0?[]:D(e.data.resourceDetailRoutes,"/config/data/resourceDetailRoutes",100),n=new Map(e.data.resources.map((i,s)=>{let a=`/config/data/resources/${s}`,d=Ut(i,a,e.appCode);return[d.code,d]})),o=new Map(tr(e).map(i=>[String(i.code),i])),r=new Map;for(let[i,s]of t.entries()){let a=`/config/data/resourceDetailRoutes/${i}`,d=N(s,a);R(d,["resourceCode","desktop","mobile"],a);let c=Q(d.resourceCode,`${a}/resourceCode`);r.has(c)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_DUPLICATE",`${a}/resourceCode`);let l=n.get(c);l||_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_RESOURCE_MISSING",`${a}/resourceCode`);let f=F(d.desktop,`${a}/desktop`),p=F(d.mobile,`${a}/mobile`);f===p&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_INVALID",a);let m=String(l.capabilities.read);for(let[A,I]of[["desktop",f],["mobile",p]]){let O=`${a}/${A}`,b=o.get(I);b||_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_REFERENCE_MISSING",O),b.surface!=="user"&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_SURFACE_INVALID",O);let g=Je(b.path,`${O}/path`),y=[...g.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)],h=A==="mobile"?!g.startsWith("/m/"):g==="/m"||g.startsWith("/m/");(g.includes("*")||g.includes("?")||g.includes("#")||g.split("/").includes("..")||y.length!==1||h)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_PATH_INVALID",O);let u=Array.isArray(b.access?.allOf)?b.access.allOf:[];b.capability!==m&&!u.includes(m)&&_("NATIVE_DATA_RESOURCE_DETAIL_ROUTE_CAPABILITY_INVALID",O)}r.set(c,{desktop:f,mobile:p})}return r}function Yd(e){let t=new Map(e.data.resources.map((s,a)=>{let d=`/config/data/resources/${a}`,c=Ut(s,d,e.appCode);return[c.code,new Map(c.schema.fields.map(l=>[String(l.code),l]))]})),n=new Map(e.data.resources.map((s,a)=>{let d=`/config/data/resources/${a}`,c=Ut(s,d,e.appCode);return[c.code,new Map(c.schema.fields.map(l=>[String(l.code),String(l.type)]))]})),o=new Set(n.keys()),r=new Set(e.workflows.activations.map((s,a)=>or(N(s,`/config/workflows/activations/${a}`).workflowCode,`/config/workflows/activations/${a}/workflowCode`))),i=new Map;return ue(e.backend.operations.map((s,a)=>{let d=`/config/backend/operations/${a}`,c=N(s,d);R(c,["code","method","path","capability","requestSchema","responseSchema","description","platformAccess","browser","ai"],d,!0);let l=k(c.method,`${d}/method`,16);["GET","POST","PUT","PATCH","DELETE"].includes(l)||_("NATIVE_OPERATION_METHOD_INVALID",`${d}/method`);let f=F(c.code,`${d}/code`);gf(c.ai,d,f,l,o);let p=mf(c.platformAccess,`${d}/platformAccess`,n,t,r,new Set(e.authz.roles.map(A=>String(A.code))));if(p?.workflowStage){let A=p.workflowStage,I=e.workflows.definitions.find(O=>O.definition.code===A.workflowCode);(!I||I.definition.subject?.resourceCode!==A.resourceCode||A.runningNodeIds.some(O=>!I.definition.nodes[O]))&&_("NATIVE_WORKFLOW_STAGE_NODE_INVALID",`${d}/platformAccess/workflowStage/runningNodeIds`)}if(p?.recordEdit){let A=e.data.resources.find(I=>I.code===p.recordEdit.resourceCode);A?.surface?.mutationOwner!=="action"&&_("NATIVE_RECORD_EDIT_ACTION_OWNER_REQUIRED",`${d}/platformAccess/recordEdit`);for(let I of p.recordEdit.fieldCodes)(!A.fieldPolicies?.[I]?.update?.length||A.surface?.fields?.[I]?.system===!0)&&_("NATIVE_RECORD_EDIT_FIELD_INVALID",`${d}/platformAccess/recordEdit/fieldCodes`)}if(p?.decimalReservation){let A=p.decimalReservation,I=String(A.resourceCode),O=JSON.stringify([A.amountFieldCode,A.currencyFieldCode,A.relationFieldCode,A.parentFieldCode,A.rootFieldCode,A.statusFieldCode,A.parentRelationValue,A.childRelationValue]),b=i.get(I);b&&b!==O&&_("NATIVE_DECIMAL_RESERVATION_MAPPING_CONFLICT",`${d}/platformAccess/decimalReservation`),i.set(I,O)}let m=ff(c.browser,`${d}/browser`,l,c.requestSchema,c.responseSchema,n,t,e.data.subjectReadSurfaces||[]);return{code:f,method:l,path:Je(c.path,`${d}/path`),requiredCapability:ve(c.capability,`${d}/capability`,e.appCode),requestSchemaDigest:ee(N(c.requestSchema,`${d}/requestSchema`)),responseSchemaDigest:ee(N(c.responseSchema,`${d}/responseSchema`)),...c.description===void 0?{}:{description:Qi(c.description,`${d}/description`,2e3)},...p?{platformAccess:p}:{},...m?{browser:m}:{}}}),s=>s.code)}function ff(e,t,n,o,r,i,s,a){if(e===void 0)return null;let d=N(e,t);R(d,["exposure","behavior","idempotency","subject"],t,["refreshTargets","fileIntent"]),x(d.exposure,"authenticated",`${t}/exposure`);let c=k(d.behavior,`${t}/behavior`,32);["read","controlled"].includes(c)||_("NATIVE_OPERATION_BROWSER_BEHAVIOR_INVALID",`${t}/behavior`);let l=k(d.idempotency,`${t}/idempotency`,32);(!["none","required"].includes(l)||c==="controlled"&&l!=="required"||c==="read"&&l!=="none")&&_("NATIVE_OPERATION_BROWSER_IDEMPOTENCY_INVALID",`${t}/idempotency`);let f=N(d.subject,`${t}/subject`);R(f,["resourceCode","inputField"],`${t}/subject`);let p=Q(f.resourceCode,`${t}/subject/resourceCode`);i.has(p)||_("NATIVE_OPERATION_BROWSER_SUBJECT_RESOURCE_NOT_DECLARED",`${t}/subject/resourceCode`);let m=J(f.inputField,`${t}/subject/inputField`),A=N(o,`${t}/requestSchema`),I=N(r,`${t}/responseSchema`);(A.type!=="object"||A.additionalProperties!==!1||I.type!=="object"||I.additionalProperties!==!1)&&_("NATIVE_OPERATION_BROWSER_SCHEMA_ROOT_INVALID",`${t}/requestSchema`);let O=N(A.properties,`${t}/requestSchema/properties`),b=new Set(A.required===void 0?[]:V(A.required,`${t}/requestSchema/required`,200));(!(m in O)||!b.has(m))&&_("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let g=N(O[m],`${t}/requestSchema/properties/${m}`);(g.type!=="string"||g.format!=="uuid")&&_("NATIVE_OPERATION_BROWSER_SUBJECT_INPUT_INVALID",`${t}/subject/inputField`);let y=new Map((Array.isArray(a)?a:[]).map((S,T)=>{let C=N(S,`/config/data/subjectReadSurfaces/${T}`);return[String(C.code),String(N(C.subject,`/config/data/subjectReadSurfaces/${T}/subject`).resourceCode)]})),h=d.refreshTargets===void 0?[]:D(d.refreshTargets,`${t}/refreshTargets`,16),u=new Set,E=ue(h.map((S,T)=>{let C=`${t}/refreshTargets/${T}`,v=N(S,C);R(v,["kind","code"],C),x(v.kind,"subject-surface",`${C}/kind`);let P=F(v.code,`${C}/code`);return(u.has(P)||!y.has(P)||y.get(P)!==p)&&_("NATIVE_OPERATION_BROWSER_REFRESH_TARGET_INVALID",`${C}/code`),u.add(P),{kind:"subject-surface",code:P}}),S=>`${S.kind}:${S.code}`),w=pf(d.fileIntent,`${t}/fileIntent`,n,c,l,p,O,b,s);return{exposure:"authenticated",behavior:c,idempotency:l,subject:{resourceCode:p,inputField:m},...E.length?{refreshTargets:E}:{},...w?{fileIntent:w}:{}}}function pf(e,t,n,o,r,i,s,a,d){if(e===void 0)return null;let c=N(e,t);R(c,["recordResourceCode","recordIdInputField","relationField","fileNameField","contentTypeField","sizeField","purposes","maxTtlSeconds","maxBytes"],t),(n!=="GET"||o!=="read"||r!=="none")&&_("NATIVE_OPERATION_FILE_INTENT_BEHAVIOR_INVALID",t);let l=Q(c.recordResourceCode,`${t}/recordResourceCode`),f=d.get(l);f||_("NATIVE_OPERATION_FILE_INTENT_RESOURCE_NOT_DECLARED",`${t}/recordResourceCode`);let p=J(c.recordIdInputField,`${t}/recordIdInputField`),m=N(s[p],`${t}/recordIdInputField`);(!a.has(p)||m.type!=="string"||m.format!=="uuid")&&_("NATIVE_OPERATION_FILE_INTENT_RECORD_INPUT_INVALID",`${t}/recordIdInputField`);let A=J(c.relationField,`${t}/relationField`),I=f.get(A);(!I||!["uuid","resource-ref.single"].includes(String(I.type))||String(I.type)==="resource-ref.single"&&(String(N(I.source,`${t}/relationField`).kind||"")!=="resource"||String(N(I.source,`${t}/relationField`).resourceCode||"")!==i))&&_("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[u,E]of O){let w=J(c[u],`${t}/${u}`);E.includes(String(f.get(w)?.type))||_("NATIVE_OPERATION_FILE_INTENT_METADATA_INVALID",`${t}/${u}`),b[u]=w}let g=ue(V(c.purposes,`${t}/purposes`,2),u=>u);(!g.length||g.some(u=>!["preview","download"].includes(u)))&&_("NATIVE_OPERATION_FILE_INTENT_PURPOSE_INVALID",`${t}/purposes`);let y=Number(c.maxTtlSeconds);(!Number.isSafeInteger(y)||y<1||y>300)&&_("NATIVE_OPERATION_FILE_INTENT_TTL_INVALID",`${t}/maxTtlSeconds`);let h=Number(c.maxBytes);return(!Number.isSafeInteger(h)||h<1||h>104857600)&&_("NATIVE_OPERATION_FILE_INTENT_SIZE_INVALID",`${t}/maxBytes`),{recordResourceCode:l,recordIdInputField:p,relationField:A,fileNameField:b.fileNameField,contentTypeField:b.contentTypeField,sizeField:b.sizeField,purposes:g,maxTtlSeconds:y,maxBytes:h}}function mf(e,t,n,o,r,i){if(e===void 0)return null;let s=N(e,t);R(s,["directory","directoryClasses","transactionTime","selectedDepartments","managedFiles","managedFileCopies","notification","workflow","roleAssertions","decimalReservation","dataCommands","recordEdit","ownedSubject","workflowStage","dataMutations"],t,!0),Object.keys(s).length===0&&_("NATIVE_OPERATION_PLATFORM_ACCESS_EMPTY",t);let a={};if(s.dataMutations!==void 0)try{a.dataMutations=Ei(s.dataMutations,o)}catch{_("NATIVE_OPERATION_DATA_MUTATIONS_INVALID",`${t}/dataMutations`)}if(s.dataCommands!==void 0){let d=N(s.dataCommands,`${t}/dataCommands`);R(d,["mode"],`${t}/dataCommands`),x(d.mode,"recoverable-native",`${t}/dataCommands/mode`),a.dataCommands={mode:"recoverable-native"}}if(s.workflowStage!==void 0){try{ja(s.workflowStage)}catch{_("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`)}let d=s.workflowStage;(!a.dataCommands||s.decimalReservation!==void 0||!n.has(d.resourceCode)||!r.has(d.workflowCode)||!s.workflow?.codes?.includes(d.workflowCode))&&_("NATIVE_WORKFLOW_STAGE_DECLARATION_INVALID",`${t}/workflowStage`),a.workflowStage={...d,runningNodeIds:K([...d.runningNodeIds]),allowedStatuses:K([...d.allowedStatuses])}}if(s.recordEdit!==void 0){let d=`${t}/recordEdit`,c=N(s.recordEdit,d);R(c,["resourceCode","fieldCodes"],d);let l=Q(c.resourceCode,`${d}/resourceCode`),f=o.get(l),p=V(c.fieldCodes,`${d}/fieldCodes`,200);(!f||!p.length||!a.dataCommands)&&_("NATIVE_RECORD_EDIT_DECLARATION_INVALID",d);for(let m of p){let A=f.get(m);(!A||A.type==="serial-number"||A.type==="subtable")&&_("NATIVE_RECORD_EDIT_FIELD_INVALID",`${d}/fieldCodes`)}a.recordEdit={resourceCode:l,fieldCodes:K(p)}}if(s.roleAssertions!==void 0){let d=N(s.roleAssertions,`${t}/roleAssertions`);R(d,["roleCodes","actorAuthority"],`${t}/roleAssertions`,!0),d.actorAuthority!==void 0&&x(d.actorAuthority,!0,`${t}/roleAssertions/actorAuthority`);let c=V(d.roleCodes,`${t}/roleAssertions/roleCodes`,20);c.length||_("NATIVE_OPERATION_ROLE_ASSERTIONS_REQUIRED",`${t}/roleAssertions/roleCodes`),c.forEach((l,f)=>{i.has(l)||_("NATIVE_ROLE_REFERENCE_MISSING",`${t}/roleAssertions/roleCodes/${f}`)}),a.roleAssertions={roleCodes:K(c),...d.actorAuthority===!0?{actorAuthority:!0}:{}}}if(s.directory!==void 0){let d=N(s.directory,`${t}/directory`);R(d,["mode","fields"],`${t}/directory`),["current-initiator","selected-user"].includes(String(d.mode))||_("NATIVE_OPERATION_DIRECTORY_MODE_INVALID",`${t}/directory/mode`);let c=new Set(["displayName","employeeNumber","primaryDepartment","departments",...d.mode==="current-initiator"?["phone"]:[]]),l=V(d.fields,`${t}/directory/fields`,c.size);(!l.length||l.some(f=>!c.has(f)))&&_("NATIVE_OPERATION_DIRECTORY_FIELDS_INVALID",`${t}/directory/fields`),a.directory={mode:String(d.mode),fields:K(l)}}if(s.transactionTime!==void 0){let d=`${t}/transactionTime`,c=N(s.transactionTime,d);R(c,["mode","recordSetAssertions"],d,!0),(c.mode!=="database-accepted"||s.dataCommands?.mode!=="recoverable-native"||c.recordSetAssertions!==void 0&&c.recordSetAssertions!==!0)&&_("NATIVE_OPERATION_TRANSACTION_TIME_INVALID",d),a.transactionTime={mode:"database-accepted",...c.recordSetAssertions?{recordSetAssertions:!0}:{}}}if(s.directoryClasses!==void 0){let d=`${t}/directoryClasses`,c=N(s.directoryClasses,d);R(c,["maxIds"],d),(!Number.isSafeInteger(c.maxIds)||c.maxIds<1||c.maxIds>20)&&_("NATIVE_OPERATION_DIRECTORY_CLASSES_INVALID",d),a.directoryClasses={maxIds:c.maxIds}}if(s.selectedDepartments!==void 0){let d=`${t}/selectedDepartments`,c=N(s.selectedDepartments,d);R(c,["fields","maxIds"],d);let l=V(c.fields,`${d}/fields`,4);(!l.includes("name")||l.some(f=>!["name","path","parent","fullPath"].includes(f))||!Number.isSafeInteger(c.maxIds)||c.maxIds<1||c.maxIds>50)&&_("NATIVE_OPERATION_SELECTED_DEPARTMENTS_INVALID",d),a.selectedDepartments={fields:K(l),maxIds:c.maxIds}}if(s.managedFiles!==void 0){let d=D(s.managedFiles,`${t}/managedFiles`,16);d.length||_("NATIVE_OPERATION_MANAGED_FILES_REQUIRED",`${t}/managedFiles`);let c=new Set;a.managedFiles=ue(d.map((l,f)=>{let p=`${t}/managedFiles/${f}`,m=N(l,p);R(m,["resourceCode","fieldCodes","intents"],p);let A=Q(m.resourceCode,`${p}/resourceCode`);(c.has(A)||!n.has(A))&&_("NATIVE_OPERATION_MANAGED_FILE_RESOURCE_INVALID",`${p}/resourceCode`),c.add(A);let I=V(m.fieldCodes,`${p}/fieldCodes`,16);(!I.length||I.some(b=>!["file","image","signature","text.rich"].includes(String(n.get(A)?.get(b)||""))))&&_("NATIVE_OPERATION_MANAGED_FILE_FIELD_INVALID",`${p}/fieldCodes`);let O=V(m.intents,`${p}/intents`,2);return(!O.length||O.some(b=>!["create","update"].includes(b)))&&_("NATIVE_OPERATION_MANAGED_FILE_INTENT_INVALID",`${p}/intents`),{resourceCode:A,fieldCodes:K(I),intents:K(O)}}),l=>l.resourceCode)}if(s.managedFileCopies!==void 0){let d=D(s.managedFileCopies,`${t}/managedFileCopies`,16);d.length||_("NATIVE_OPERATION_MANAGED_FILE_COPIES_REQUIRED",`${t}/managedFileCopies`);let c=new Set;a.managedFileCopies=ue(d.map((l,f)=>{let p=`${t}/managedFileCopies/${f}`,m=N(l,p);R(m,["mode","sourceResourceCode","sourceFieldCodes","targetResourceCode","targetFieldCodes"],p),x(m.mode,"copy",`${p}/mode`);let A=Q(m.sourceResourceCode,`${p}/sourceResourceCode`),I=Q(m.targetResourceCode,`${p}/targetResourceCode`),O=n.get(A),b=n.get(I);(!O||!b)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_RESOURCE_INVALID",p);let g=V(m.sourceFieldCodes,`${p}/sourceFieldCodes`,16),y=V(m.targetFieldCodes,`${p}/targetFieldCodes`,16);(!g.length||g.length!==y.length)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELDS_INVALID",p),g.forEach((u,E)=>{let w=O.get(u),S=b.get(y[E]);(!["file","image","text.rich"].includes(String(w))||w!==S)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_FIELD_INVALID",`${p}/sourceFieldCodes/${E}`)});let h=`${A}:${g.join(",")}=>${I}:${y.join(",")}`;return c.has(h)&&_("NATIVE_OPERATION_MANAGED_FILE_COPY_DUPLICATE",p),c.add(h),{mode:"copy",sourceResourceCode:A,sourceFieldCodes:K(g),targetResourceCode:I,targetFieldCodes:K(y)}}),l=>`${l.sourceResourceCode}:${l.sourceFieldCodes.join(",")}=>${l.targetResourceCode}:${l.targetFieldCodes.join(",")}`)}if(s.notification!==void 0){let d=N(s.notification,`${t}/notification`);R(d,["mode"],`${t}/notification`),d.mode!=="business-standard"&&_("NATIVE_OPERATION_NOTIFICATION_MODE_INVALID",`${t}/notification/mode`),a.notification={mode:"business-standard"}}if(s.workflow!==void 0){let d=N(s.workflow,`${t}/workflow`);R(d,["codes"],`${t}/workflow`,["businessCommands"]);let c=V(d.codes,`${t}/workflow/codes`,16);(!c.length||c.some(f=>!r.has(f)))&&_("NATIVE_OPERATION_WORKFLOW_CODE_INVALID",`${t}/workflow/codes`);let l=d.businessCommands===void 0?void 0:V(d.businessCommands,`${t}/workflow/businessCommands`,4);l&&(!l.length||l.some(f=>!["approve","reject","withdraw","resubmit"].includes(f)))&&_("NATIVE_OPERATION_WORKFLOW_BUSINESS_COMMAND_INVALID",`${t}/workflow/businessCommands`),a.workflow={codes:K(c),...l?{businessCommands:K(l)}:{}}}if(s.ownedSubject!==void 0){let d=`${t}/ownedSubject`,c=s.ownedSubject;try{Go(c)}catch{_("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",d)}(!a.workflow||s.decimalReservation!==void 0)&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_INVALID",d);try{wd(c,o,a.managedFiles||[])}catch(l){_(`NATIVE_${l.message}`,d)}a.ownedSubject={mode:"create",resourceCode:c.resourceCode,subtables:ue(c.subtables.map(l=>({fieldCode:l.fieldCode,fieldCodes:K([...l.fieldCodes])})),l=>l.fieldCode)}}if(s.decimalReservation!==void 0){let d=`${t}/decimalReservation`,c=N(s.decimalReservation,d);R(c,["mode","resourceCode","amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode","parentRelationValue","childRelationValue","eligibleParentStatuses","eligibleChildStatuses"],d);let l=k(c.mode,`${d}/mode`,16);["reserve","commit","release"].includes(l)||_("NATIVE_DECIMAL_RESERVATION_MODE_INVALID",`${d}/mode`);let f=Q(c.resourceCode,`${d}/resourceCode`),p=o.get(f);p||_("NATIVE_DECIMAL_RESERVATION_RESOURCE_MISSING",`${d}/resourceCode`);let A=Object.fromEntries(["amountFieldCode","currencyFieldCode","relationFieldCode","parentFieldCode","rootFieldCode","statusFieldCode"].map(u=>[u,J(c[u],`${d}/${u}`)])),I=u=>p.get(A[u]),O=u=>new Set((I(u)?.options||[]).map(E=>String(E.value))),b=F(c.parentRelationValue,`${d}/parentRelationValue`),g=F(c.childRelationValue,`${d}/childRelationValue`),y=V(c.eligibleParentStatuses,`${d}/eligibleParentStatuses`,16),h=V(c.eligibleChildStatuses,`${d}/eligibleChildStatuses`,16);(I("amountFieldCode")?.type!=="number.decimal"||I("amountFieldCode")?.exactDecimal!==!0||I("amountFieldCode")?.precision!==18||I("amountFieldCode")?.scale!==2||I("currencyFieldCode")?.type!=="option.single"||I("relationFieldCode")?.type!=="option.single"||I("parentFieldCode")?.type!=="resource-ref.single"||I("parentFieldCode")?.source?.resourceCode!==f||I("rootFieldCode")?.type!=="uuid"||I("statusFieldCode")?.type!=="option.single"||b===g||!O("relationFieldCode").has(b)||!O("relationFieldCode").has(g)||!y.length||!h.length||y.some(u=>!O("statusFieldCode").has(u))||h.some(u=>!O("statusFieldCode").has(u)))&&_("NATIVE_DECIMAL_RESERVATION_FIELD_INVALID",d),a.decimalReservation={mode:l,resourceCode:f,...A,parentRelationValue:b,childRelationValue:g,eligibleParentStatuses:K(y),eligibleChildStatuses:K(h)}}return a}function gf(e,t,n,o,r){if(e===void 0)return;let i=`${t}/ai`,s=N(e,i);$u.test(n)||_("NATIVE_OPERATION_AI_CODE_INVALID",`${t}/code`),R(s,["name","description","risk","resources","sideEffects","concurrency","timeoutMs"],i,!0),k(s.name,`${i}/name`,qi),k(s.description,`${i}/description`,qi);let a=k(s.risk,`${i}/risk`,16);["read","write","destructive","external"].includes(a)||_("NATIVE_OPERATION_AI_RISK_INVALID",`${i}/risk`),a==="read"!=(o==="GET")&&_("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`),o==="DELETE"&&!["destructive","external"].includes(a)&&_("NATIVE_OPERATION_AI_METHOD_RISK_MISMATCH",`${i}/risk`);let d=V(s.resources,`${i}/resources`,16);d.length===0&&_("NATIVE_OPERATION_AI_RESOURCE_REQUIRED",`${i}/resources`),d.forEach((l,f)=>{let p=Q(l,`${i}/resources/${f}`);r.has(p)||_("NATIVE_OPERATION_AI_RESOURCE_MISSING",`${i}/resources/${f}`)});let c=V(s.sideEffects,`${i}/sideEffects`,20);(a==="read"&&c.length!==0||a!=="read"&&c.length===0)&&_("NATIVE_OPERATION_AI_SIDE_EFFECT_INVALID",`${i}/sideEffects`),s.concurrency!==void 0&&!["none","revision"].includes(k(s.concurrency,`${i}/concurrency`,16))&&_("NATIVE_OPERATION_AI_CONCURRENCY_INVALID",`${i}/concurrency`),s.timeoutMs!==void 0&&Ae(s.timeoutMs,`${i}/timeoutMs`,100,3e4)}function Xo(e){return(e.replace(/\/{2,}/g,"/").replace(/\/$/,"")||"/").split("/").map(n=>n.startsWith(":")?":":n.includes("*")?"*":n).join("/")}function _f(e,t){let n=N(e,t),o=k(n.type,`${t}/type`,32),r=["code","type","label","presentation","required"],i=o==="sso"?[...r,"provider"]:o==="dingtalk"?[...r,"flow"]:r;R(n,i,t);let s=F(n.code,`${t}/code`),a=k(n.label,`${t}/label`,255),d=k(n.presentation,`${t}/presentation`,16);["primary","secondary"].includes(d)||_("NATIVE_APPLICATION_AUTH_METHOD_PRESENTATION_INVALID",`${t}/presentation`);let c=_n(n.required,`${t}/required`);return["sso","password","dingtalk"].includes(o)||_("NATIVE_APPLICATION_AUTH_METHOD_TYPE_INVALID",`${t}/type`),o==="sso"&&n.provider!=="tenant-default"&&_("NATIVE_APPLICATION_AUTH_SSO_PROVIDER_INVALID",`${t}/provider`),o==="dingtalk"&&!["auto","jsapi","oauth"].includes(k(n.flow,`${t}/flow`,16))&&_("NATIVE_APPLICATION_AUTH_DINGTALK_FLOW_INVALID",`${t}/flow`),{code:s,type:o,label:a,presentation:d,required:c,...o==="sso"?{provider:"tenant-default"}:{},...o==="dingtalk"?{flow:n.flow}:{}}}function Pd(e,t,n){let o=N(e,n);R(o,["routeCode","path","defaultRouteCode"],n);let r=F(o.routeCode,`${n}/routeCode`),i=Je(o.path,`${n}/path`),s=t==="desktop"?"/login":"/m/login";return(i!==s||/[:*?#\\]/.test(i))&&_("NATIVE_APPLICATION_AUTH_SURFACE_PATH_INVALID",`${n}/path`,{device:t,expectedPath:s}),{routeCode:r,path:i,defaultRouteCode:F(o.defaultRouteCode,`${n}/defaultRouteCode`)}}function Xd(e,t,n,o){if(e===null)return;let r=N(e,o);R(r,["accountMode","registration","methods","surfaces"],o),x(r.accountMode,"existing-platform-users-only",`${o}/accountMode`);let i=N(r.registration,`${o}/registration`);R(i,["mode"],`${o}/registration`),x(i.mode,"reject",`${o}/registration/mode`);let s=D(r.methods,`${o}/methods`,8);s.length===0&&_("NATIVE_APPLICATION_AUTH_METHOD_REQUIRED",`${o}/methods`);let a=s.map((b,g)=>_f(b,`${o}/methods/${g}`)),d=new Set,c=new Set;for(let[b,g]of a.entries())d.has(g.code)&&_("NATIVE_APPLICATION_AUTH_METHOD_CODE_DUPLICATE",`${o}/methods/${b}/code`),c.has(g.type)&&_("NATIVE_APPLICATION_AUTH_METHOD_TYPE_DUPLICATE",`${o}/methods/${b}/type`),d.add(g.code),c.add(g.type);a.filter(b=>b.presentation==="primary").length!==1&&_("NATIVE_APPLICATION_AUTH_PRIMARY_METHOD_INVALID",`${o}/methods`);let l=N(r.surfaces,`${o}/surfaces`);R(l,["desktop","mobile"],`${o}/surfaces`);let f=Pd(l.desktop,"desktop",`${o}/surfaces/desktop`),p=Pd(l.mobile,"mobile",`${o}/surfaces/mobile`);f.routeCode===p.routeCode&&_("NATIVE_APPLICATION_AUTH_SURFACE_CODE_DUPLICATE",`${o}/surfaces/mobile/routeCode`);let m=D(t,"/config/frontend/routes",q.routes),A=new Map;for(let[b,g]of m.entries()){let y=N(g,`/config/frontend/routes/${b}`);A.set(String(y.code||""),y)}let I=new Set((Array.isArray(n.data?.resources)?n.data.resources:[]).map(b=>String(b.code||"")).filter(b=>/^[a-z][a-z0-9-]{0,62}$/.test(b)));for(let[b,g]of[["desktop",f],["mobile",p]]){A.has(g.routeCode)&&_("NATIVE_APPLICATION_AUTH_SURFACE_CODE_CONFLICT",`${o}/surfaces/${b}/routeCode`);let y=/^user\.([a-z][a-z0-9-]{0,62})\.(records|submit)$/.exec(String(g.defaultRouteCode||"")),h=A.get(g.defaultRouteCode),u=String(h?.path||"");if(y&&I.has(y[1])){let w=y[2]==="records"?`/my/${y[1]}`:`/my/${y[1]}/submit`;h={surface:"user",path:b==="mobile"?`/m${w}`:w},u=String(h.path)}let E=b==="desktop"?u==="/m"||u.startsWith("/m/"):!(u==="/m"||u.startsWith("/m/"));(!h||h.surface!=="user"||/[:*]/.test(u)||E)&&_("NATIVE_APPLICATION_AUTH_DEFAULT_ROUTE_INVALID",`${o}/surfaces/${b}/defaultRouteCode`)}let O=Zd(n).filter(b=>!b.owner.startsWith("authentication:"));for(let[b,g]of[["desktop",f],["mobile",p]]){let y=O.find(h=>Xo(h.path)===Xo(g.path));y&&_("NATIVE_APPLICATION_AUTH_SURFACE_PATH_CONFLICT",`${o}/surfaces/${b}/path`,{owner:y.owner})}}function Af(e,t){if(e===null)return;let n={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}},o=N(e,t),r=N(o.surfaces,`${t}/surfaces`),i={...o,surfaces:{...r,desktop:{...N(r.desktop,`${t}/surfaces/desktop`),defaultRouteCode:"auth-desktop-default"},mobile:{...N(r.mobile,`${t}/surfaces/mobile`),defaultRouteCode:"auth-mobile-default"}}};Xd(i,n.frontend.routes,{...n,frontend:{...n.frontend,authentication:i}},t)}function Ef(e){let t=e.frontend.authentication;return t===null?null:{accountMode:t.accountMode,registration:{mode:t.registration.mode},methods:t.methods.map(n=>({...n})),surfaces:{desktop:{...t.surfaces.desktop},mobile:{...t.surfaces.mobile}}}}var If=new Set(["draft.read","draft.update","validate","create","own.list","own.read","public.list","public.read","public.query"]);function yf(e,t,n){let o=N(e,n);R(o,["policies"],n);let r=D(o.policies,`${n}/policies`,16);r.length<1&&_("NATIVE_PUBLIC_POLICY_REQUIRED",n);let i=new Map(t.frontend.routes.map(c=>[c.code,c])),s=new Map(t.data.resources.map(c=>[c.code,c])),a=new Set,d=new Set(r.map(c=>String(c?.code||"")));r.forEach((c,l)=>{let f=`${n}/policies/${l}`,p=N(c,f);R(p,["code","routeCode","mode","resourceCode","operations","fields"],f,["requiredFields","ownRecordFields","publicRecordFields","publicFilters","serverGeneratedFields","schedule","publicSubtableFields","publicQueries","draft","validations"]);let m=F(p.code,`${f}/code`);a.has(m)&&_("NATIVE_PUBLIC_POLICY_DUPLICATE",`${f}/code`);let A=F(p.routeCode,`${f}/routeCode`),I=i.get(A);(!I||I.surface!=="user"||I.capability!==void 0||I.access!==void 0||/[:*]/.test(String(I.path)))&&_("NATIVE_PUBLIC_ROUTE_INVALID",`${f}/routeCode`),x(p.mode,"anonymous",`${f}/mode`);let O=Q(p.resourceCode,`${f}/resourceCode`),b=s.get(O);b||_("NATIVE_PUBLIC_RESOURCE_MISSING",`${f}/resourceCode`);let g=new Map(b.schema.fields.map($=>[String($.code),String($.type)])),y=V(p.operations,`${f}/operations`,8);(y.length<1||y.some($=>!If.has($)))&&_("NATIVE_PUBLIC_OPERATION_INVALID",`${f}/operations`),y.includes("draft.read")!==y.includes("draft.update")&&_("NATIVE_PUBLIC_DRAFT_OPERATION_INCOMPLETE",`${f}/operations`);let h=V(p.fields,`${f}/fields`,64);(h.length<1||h.some($=>!g.has($)))&&_("NATIVE_PUBLIC_FIELD_INVALID",`${f}/fields`);for(let $ of["requiredFields","ownRecordFields","publicRecordFields"]){if(!Object.prototype.hasOwnProperty.call(p,$))continue;V(p[$],`${f}/${$}`,64).some(W=>!h.includes(W))&&_("NATIVE_PUBLIC_FIELD_SCOPE_INVALID",`${f}/${$}`)}let u=Object.prototype.hasOwnProperty.call(p,"serverGeneratedFields")?D(p.serverGeneratedFields,`${f}/serverGeneratedFields`,16):[],E=new Set;u.forEach(($,Y)=>{let W=`${f}/serverGeneratedFields/${Y}`,M=N($,W);R(M,["field","kind"],W);let B=J(M.field,`${W}/field`);(E.has(B)||!g.has(B)||h.includes(B)||g.get(B)!=="text.short"&&g.get(B)!=="text.long")&&_("NATIVE_PUBLIC_SERVER_GENERATED_FIELD_INVALID",`${W}/field`),x(M.kind,"random-token",`${W}/kind`),E.add(B)});let w=Object.prototype.hasOwnProperty.call(p,"schedule")?N(p.schedule,`${f}/schedule`):null;if(w){let $=["campusPolicyCode","rulePolicyCode","campusField","ruleCampusField","ruleWeekdaysField","ruleOpenAtField","ruleCloseAtField","ruleSlotMinutesField","ruleAdvanceHoursField","ruleAdvanceDaysField","campusEnabledField","ruleEnabledField","dateField","timeField"];R(w,$,`${f}/schedule`);for(let Y of["campusPolicyCode","rulePolicyCode"])F(w[Y],`${f}/schedule/${Y}`);for(let Y of $.filter(W=>!["campusPolicyCode","rulePolicyCode"].includes(W)))J(w[Y],`${f}/schedule/${Y}`);for(let Y of[w.campusField,w.dateField,w.timeField])h.includes(String(Y))||_("NATIVE_PUBLIC_SCHEDULE_FIELD_INVALID",`${f}/schedule`);(!d.has(String(w.campusPolicyCode))||!d.has(String(w.rulePolicyCode)))&&_("NATIVE_PUBLIC_SCHEDULE_POLICY_INVALID",`${f}/schedule`)}let S=Object.prototype.hasOwnProperty.call(p,"publicFilters")?D(p.publicFilters,`${f}/publicFilters`,16):[],T=new Set;S.forEach(($,Y)=>{let W=`${f}/publicFilters/${Y}`,M=N($,W);R(M,["field","operator","value"],W);let B=J(M.field,`${W}/field`);T.has(B)&&_("NATIVE_PUBLIC_FILTER_DUPLICATE",`${W}/field`),h.includes(B)||_("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${W}/field`),x(M.operator,"eq",`${W}/operator`),["boolean","text.short","text.long","number.integer","number.decimal","date","time","option.single"].includes(g.get(B)||"")||_("NATIVE_PUBLIC_FILTER_FIELD_INVALID",`${W}/field`),M.value!==null&&typeof M.value!="string"&&typeof M.value!="number"&&typeof M.value!="boolean"&&_("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${W}/value`),["option.single"].includes(g.get(B)||"")&&M.value!==null&&typeof M.value!="string"&&_("NATIVE_PUBLIC_FILTER_VALUE_INVALID",`${W}/value`),T.add(B)});let C=Object.prototype.hasOwnProperty.call(p,"publicSubtableFields")?N(p.publicSubtableFields,`${f}/publicSubtableFields`):null;if(C){Object.keys(C).length>64&&_("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${f}/publicSubtableFields`);for(let[$,Y]of Object.entries(C)){let W=b.schema.fields.find(pe=>String(pe.code)===$),M=String(W?.subtable?.resourceCode||""),B=s.get(M),oe=new Map((B?.schema?.fields||[]).map(pe=>[String(pe.code),String(pe.type)])),se=V(Y,`${f}/publicSubtableFields/${$}`,64);(!h.includes($)||g.get($)!=="subtable"||!B||se.length<1||se.some(pe=>!oe.has(pe))||se.some(pe=>oe.get(pe)==="subtable")||se.some(pe=>oe.get(pe)==="signature"))&&_("NATIVE_PUBLIC_SUBTABLE_FIELDS_INVALID",`${f}/publicSubtableFields/${$}`)}}let v=Object.prototype.hasOwnProperty.call(p,"publicRecordFields")?V(p.publicRecordFields,f+"/publicRecordFields",64):[];y.some($=>$.startsWith("public."))&&(Object.prototype.hasOwnProperty.call(p,"publicRecordFields")||_("NATIVE_PUBLIC_RECORD_FIELDS_REQUIRED",f+"/publicRecordFields"),(v.length<1||v.some($=>!h.includes($))||v.some($=>g.get($)==="signature"||g.get($)==="subtable"&&!C?.[$]))&&_("NATIVE_PUBLIC_RECORD_FIELDS_INVALID",f+"/publicRecordFields"));let P=Object.prototype.hasOwnProperty.call(p,"publicQueries")?D(p.publicQueries,f+"/publicQueries",16):[],H=new Set;P.forEach(($,Y)=>{let W=f+"/publicQueries/"+Y,M=N($,W);R(M,["code","kind","resourceCode","fields","defaultLimit","maxLimit"],W,["sort","parameters","aggregate"]);let B=F(M.code,W+"/code");H.has(B)&&_("NATIVE_PUBLIC_QUERY_DUPLICATE",W+"/code"),H.add(B),["records","aggregate"].includes(String(M.kind))||_("NATIVE_PUBLIC_QUERY_KIND_INVALID",W+"/kind"),String(M.resourceCode)!==O&&_("NATIVE_PUBLIC_QUERY_RESOURCE_INVALID",W+"/resourceCode");let oe=V(M.fields,W+"/fields",64);(oe.length<1||oe.some(te=>!h.includes(te))||oe.some(te=>!v?.includes(te)))&&_("NATIVE_PUBLIC_QUERY_FIELDS_INVALID",W+"/fields");let se=Number(M.defaultLimit),pe=Number(M.maxLimit);if((!Number.isSafeInteger(se)||!Number.isSafeInteger(pe)||se<1||pe<se||pe>100)&&_("NATIVE_PUBLIC_QUERY_LIMIT_INVALID",W+"/maxLimit"),Object.prototype.hasOwnProperty.call(M,"sort")){let te=D(M.sort,W+"/sort",4),de=new Set;te.forEach((gt,Xe)=>{let Me=W+"/sort/"+Xe,Ve=N(gt,Me);R(Ve,["field","direction"],Me);let Se=J(Ve.field,Me+"/field");(!oe.includes(Se)||de.has(Se)||!["asc","desc"].includes(String(Ve.direction)))&&_("NATIVE_PUBLIC_QUERY_SORT_INVALID",Me),de.add(Se)})}if(Object.prototype.hasOwnProperty.call(M,"parameters")){let te=D(M.parameters,W+"/parameters",8),de=new Set;te.forEach((gt,Xe)=>{let Me=W+"/parameters/"+Xe,Ve=N(gt,Me);R(Ve,["name","field","operator","type"],Me);let Se=F(Ve.name,Me+"/name"),at=J(Ve.field,Me+"/field");(de.has(Se)||!oe.includes(at)||!["eq","contains","in"].includes(String(Ve.operator))||!["string","number","boolean","string[]"].includes(String(Ve.type)))&&_("NATIVE_PUBLIC_QUERY_PARAMETER_INVALID",Me),de.add(Se)})}if(Object.prototype.hasOwnProperty.call(M,"aggregate")){String(M.kind)!=="aggregate"&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_KIND_INVALID",W+"/aggregate");let te=W+"/aggregate",de=N(M.aggregate,te);R(de,["measures"],te,["dimensions","order"]);let gt=new Set,Xe=(Se,at)=>{let ce=String(Se||"").trim();return(!/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(ce)||gt.has(ce))&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_ALIAS_INVALID",at),gt.add(ce),ce};(Object.prototype.hasOwnProperty.call(de,"dimensions")?D(de.dimensions,te+"/dimensions",3):[]).forEach((Se,at)=>{let ce=`${te}/dimensions/${at}`,Oe=N(Se,ce);R(Oe,["field","as"],ce,["bucket"]);let Be=J(Oe.field,ce+"/field");oe.includes(Be)||_("NATIVE_PUBLIC_QUERY_AGGREGATE_FIELD_INVALID",ce+"/field"),Xe(Oe.as,ce+"/as"),Oe.bucket!==void 0&&!["day","week","month","quarter","year"].includes(String(Oe.bucket))&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_BUCKET_INVALID",ce+"/bucket")});let Ve=D(de.measures,te+"/measures",8);Ve.length<1&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_MEASURES_INVALID",te+"/measures"),Ve.forEach((Se,at)=>{let ce=`${te}/measures/${at}`,Oe=N(Se,ce);R(Oe,["type","as"],ce,["field"]);let Be=String(Oe.type),_r=Oe.field===void 0?void 0:J(Oe.field,ce+"/field");(!["count","countDistinct","sum","avg","min","max"].includes(Be)||(Be==="count"?_r!==void 0:!_r||!oe.includes(_r)))&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_MEASURE_INVALID",ce),Xe(Oe.as,ce+"/as")}),Object.prototype.hasOwnProperty.call(de,"order")&&D(de.order,te+"/order",10).forEach((at,ce)=>{let Oe=`${te}/order/${ce}`,Be=N(at,Oe);R(Be,["field"],Oe,["direction","nulls"]),(!gt.has(String(Be.field))||Be.direction!==void 0&&!["asc","desc"].includes(String(Be.direction))||Be.nulls!==void 0&&!["first","last"].includes(String(Be.nulls)))&&_("NATIVE_PUBLIC_QUERY_AGGREGATE_ORDER_INVALID",Oe)})}});let ne=Object.prototype.hasOwnProperty.call(p,"requiredFields")?V(p.requiredFields,`${f}/requiredFields`,64):[],Z=b.surface||{},Ce=Z.fields||{},Ee=String(Z.mutationOwner||"native")==="native"&&Z.generated?.create!==!1,Ie=b.schema.fields.filter($=>Et($,Ce[$.code])).map($=>String($.code));if(y.includes("create")&&!Ee&&_("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${f}/fields`),y.includes("create")&&!Object.prototype.hasOwnProperty.call(p,"draft")&&_("NATIVE_PUBLIC_DRAFT_REQUIRED",`${f}/draft`),y.includes("create"))for(let $ of Ie){let Y=h.includes($)?ne.includes($)?null:"requiredFields":"fields";Y&&_("NATIVE_PUBLIC_CREATE_FIELDS_INCOMPLETE",`${f}/${Y}`,{resourceCode:Q,fieldCode:$})}if(Object.prototype.hasOwnProperty.call(p,"draft")){let $=N(p.draft,`${f}/draft`);R($,["enabled","inactivityTtlSeconds","maxBytes"],`${f}/draft`),x($.enabled,!0,`${f}/draft/enabled`),Ae($.inactivityTtlSeconds,`${f}/draft/inactivityTtlSeconds`,3600,7776e3),Ae($.maxBytes,`${f}/draft/maxBytes`,4096,262144)}else y.includes("draft.read")&&_("NATIVE_PUBLIC_DRAFT_REQUIRED",`${f}/draft`);let fe=Object.prototype.hasOwnProperty.call(p,"validations")?D(p.validations,`${f}/validations`,16):[],ye=new Set;fe.forEach(($,Y)=>{let W=`${f}/validations/${Y}`,M=N($,W);R(M,["code","kind","fields","result"],W);let B=F(M.code,`${W}/code`);ye.has(B)&&_("NATIVE_PUBLIC_VALIDATION_DUPLICATE",`${W}/code`),x(M.kind,"duplicate",`${W}/kind`),x(M.result,"availability",`${W}/result`);let oe=V(M.fields,`${W}/fields`,8);(oe.length<1||oe.some(se=>!h.includes(se))||oe.some(se=>["file","subtable"].includes(g.get(se)||"")))&&_("NATIVE_PUBLIC_VALIDATION_FIELD_INVALID",`${W}/fields`),ye.add(B)}),a.add(m)})}function Of(e,t){let n=N(e,t);R(n,["policies"],t),D(n.policies,`${t}/policies`,16).length<1&&_("NATIVE_PUBLIC_POLICY_REQUIRED",t)}function bf(e){return{policies:ue(e.frontend.publicAccess.policies.map(t=>({code:t.code,routeCode:t.routeCode,mode:t.mode,resourceCode:t.resourceCode,operations:K(t.operations),fields:K(t.fields),...t.requiredFields?{requiredFields:K(t.requiredFields)}:{},...t.ownRecordFields?{ownRecordFields:K(t.ownRecordFields)}:{},...t.publicRecordFields?{publicRecordFields:K(t.publicRecordFields)}:{},...t.publicFilters?{publicFilters:t.publicFilters.map(n=>({field:n.field,operator:n.operator,value:n.value})).sort((n,o)=>Pe(n.field,o.field))}:{},...t.publicQueries?{publicQueries:ue(t.publicQueries.map(n=>({code:n.code,kind:n.kind,resourceCode:n.resourceCode,fields:K(n.fields),defaultLimit:Number(n.defaultLimit),maxLimit:Number(n.maxLimit),...n.sort?{sort:n.sort.map(o=>({field:o.field,direction:o.direction}))}:{},...n.parameters?{parameters:n.parameters.map(o=>({name:o.name,field:o.field,operator:o.operator,type:o.type})).sort((o,r)=>Pe(o.name,r.name))}:{},...n.aggregate?{aggregate:{...n.aggregate.dimensions?{dimensions:n.aggregate.dimensions.map(o=>({field:o.field,as:o.as,...o.bucket?{bucket:o.bucket}:{}})).sort((o,r)=>o.as.localeCompare(r.as))}:{},measures:n.aggregate.measures.map(o=>({type:o.type,...o.field?{field:o.field}:{},as:o.as})).sort((o,r)=>o.as.localeCompare(r.as)),...n.aggregate.order?{order:n.aggregate.order.map(o=>({field:o.field,...o.direction?{direction:o.direction}:{},...o.nulls?{nulls:o.nulls}:{}})).sort((o,r)=>o.field.localeCompare(r.field))}:{}}}:{}})),n=>String(n.code))}:{},...t.publicSubtableFields?{publicSubtableFields:Object.fromEntries(Object.entries(t.publicSubtableFields).sort(([n],[o])=>n.localeCompare(o)).map(([n,o])=>[n,K(Array.isArray(o)?o.map(String):[])]))}:{},...t.serverGeneratedFields?{serverGeneratedFields:t.serverGeneratedFields.map(n=>({field:n.field,kind:n.kind})).sort((n,o)=>Pe(n.field,o.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:ue(t.validations.map(n=>({code:n.code,kind:n.kind,fields:K(n.fields),result:n.result})),n=>n.code)}:{}})),t=>t.code)}}function Zd(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 n of e.data.resources){let o=Qd(n),r=`/admin/resources/${n.code}`,i=[["list",r],["detail",`${r}/:id`],["create",`${r}/new`],["update",`${r}/:id/edit`]];for(let[s,a]of i)o[s]&&t.push({owner:`resource:${n.code}:${s}`,path:a},{owner:`resource:${n.code}:${s}:mobile`,path:`/m${a}`})}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 n=!1;for(let o of e.workflows.definitions)["standalone","hidden-handoff"].includes(o.launch.mode)&&(n=!0);n&&t.push({owner:"workflow:launch",path:"/workflows/:workflowCode/start"},{owner:"workflow:launch:mobile",path:"/m/workflows/:workflowCode/start"})}return t}function tr(e){let t=new Map(Zd(e).map(n=>[Xo(n.path),n]));return ue(e.frontend.routes.map((n,o)=>{let r=`/config/frontend/routes/${o}`,i=N(n,r);R(i,["code","path","label","surface","parentCode","capability","access","pinned","tabPersistence","keepAlive"],r,!0),["admin","user"].includes(i.surface)||_("NATIVE_ROUTE_SURFACE_INVALID",`${r}/surface`);let s=Je(i.path,`${r}/path`);i.surface==="admin"&&s!=="/admin"&&!s.startsWith("/admin/")&&_("NATIVE_ADMIN_ROUTE_PATH_INVALID",`${r}/path`),i.surface==="user"&&(s==="/admin"||s.startsWith("/admin/"))&&_("NATIVE_USER_ROUTE_PATH_RESERVED",`${r}/path`);let a=Xo(s),d=t.get(a);d&&_("NATIVE_ROUTE_PATH_CONFLICT",`${r}/path`,{path:s,owner:d.owner}),t.set(a,{owner:`frontend:${String(i.code||o)}`,path:s});let c=/[:*]/.test(s),l=Zi(i,r,e.appCode),f=i.pinned===void 0?void 0:_n(i.pinned,`${r}/pinned`),p=i.tabPersistence===void 0?c?"none":"session":k(i.tabPersistence,`${r}/tabPersistence`,16),m=i.keepAlive===void 0?"none":k(i.keepAlive,`${r}/keepAlive`,16);return["session","none"].includes(p)||_("NATIVE_ROUTE_TAB_PERSISTENCE_INVALID",`${r}/tabPersistence`),["none","memory"].includes(m)||_("NATIVE_ROUTE_KEEP_ALIVE_INVALID",`${r}/keepAlive`),c&&f===!0&&_("NATIVE_DYNAMIC_ROUTE_PINNED_FORBIDDEN",`${r}/pinned`),c&&p==="session"&&_("NATIVE_DYNAMIC_ROUTE_TAB_PERSISTENCE_FORBIDDEN",`${r}/tabPersistence`),c&&m==="memory"&&_("NATIVE_DYNAMIC_ROUTE_KEEP_ALIVE_FORBIDDEN",`${r}/keepAlive`),{code:F(i.code,`${r}/code`),path:s,label:k(i.label,`${r}/label`,255),surface:i.surface,...i.parentCode===void 0?{}:{parentCode:F(i.parentCode,`${r}/parentCode`)},...l,...f===void 0?{}:{pinned:f},tabPersistence:p,keepAlive:m}}),n=>n.code)}function Qd(e){let t=e.surface===void 0?{}:N(e.surface,"/surface"),n=t.mutationOwner||"native",o=t.generated===void 0?{}:N(t.generated,"/surface/generated"),r=n==="native";return{list:o.list??!0,detail:o.detail??!0,create:o.create??r,update:o.update??r,delete:o.delete??r}}function ec(e){let t=[];for(let n of ue(e.data.resources,o=>o.code).flatMap(o=>[{resource:o,viewCode:void 0},...(o.surface?.views||[]).map(r=>({viewCode:r.code,resource:{...o,name:r.name,surface:ni(o.surface,r.code)}}))])){let{resource:o,viewCode:r}=n,i=`/admin/resources/${o.code}${r?`/views/${r}`:""}`,s=Qd(o),a=[{operation:"list",kind:"resource-list",path:`${i}`,label:o.name,capability:o.capabilities.read,navigationEligible:!0},{operation:"detail",kind:"resource-detail",path:`${i}/:id`,label:`${o.name}\u8BE6\u60C5`,capability:o.capabilities.read,navigationEligible:!1},{operation:"create",kind:"resource-create",path:`${i}/new`,label:`\u65B0\u589E${o.name}`,capability:o.capabilities.create,navigationEligible:!1},{operation:"update",kind:"resource-update",path:`${i}/:id/edit`,label:`\u7F16\u8F91${o.name}`,capability:o.capabilities.update,navigationEligible:!1}];for(let d of a)s[d.operation]&&t.push({code:`resource:${o.code}${r?`:view:${r}`:""}:${d.operation}`,kind:d.kind,path:d.path,label:d.label,navigationEligible:d.navigationEligible,capability:d.capability,resourceCode:o.code,...r?{viewCode:r}:{}})}for(let n of tr(e))n.surface==="admin"&&t.push({code:`operation:${n.code}`,kind:"operation",path:n.path,label:n.label,navigationEligible:!/[:*]/.test(n.path),routeCode:n.code});return t.sort((n,o)=>Pe(n.code,o.code))}function tc(e){return e.kind==="resource"?`resource:${e.resourceCode}${e.viewCode?`:view:${e.viewCode}`:""}:list`:`operation:${e.routeCode}`}function hf(e){return e.frontend.admin.navigation.map((t,n)=>({code:t.code,label:t.label,...t.icon===void 0?{}:{icon:t.icon},order:t.order??n,items:t.items.map((o,r)=>({pageCode:tc(o.page),...o.label===void 0?{}:{label:o.label},...o.icon===void 0?{}:{icon:o.icon},order:o.order??r})).sort((o,r)=>o.order-r.order||Pe(o.pageCode,r.pageCode))})).sort((t,n)=>t.order-n.order||Pe(t.code,n.code))}function Nf(e,t){let n=D(e,t,q.adminNavigationGroups);n.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>q.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let o=0;n.forEach((r,i)=>{let s=`${t}/${i}`,a=N(r,s);R(a,["code","label","icon","order","items"],s,!0),F(a.code,`${s}/code`),k(a.label,`${s}/label`,255),Zo(a.icon,`${s}/icon`),xd(a.order,`${s}/order`);let d=D(a.items,`${s}/items`,500);d.length===0&&_("NATIVE_ADMIN_GROUP_ORPHANED",`${s}/items`),o+=d.length,o>q.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),d.forEach((c,l)=>{let f=`${s}/items/${l}`,p=N(c,f);R(p,["page","label","icon","order"],f,!0),wf(p.page,`${f}/page`),p.label!==void 0&&k(p.label,`${f}/label`,255),Zo(p.icon,`${f}/icon`),xd(p.order,`${f}/order`)})})}function wf(e,t){let n=N(e,t),o=k(n.kind,`${t}/kind`,64);if(o==="resource"){R(n,["kind","resourceCode"],t,["viewCode"]),n.viewCode!==void 0&&F(n.viewCode,`${t}/viewCode`),Q(n.resourceCode,`${t}/resourceCode`);return}if(o==="operation"){R(n,["kind","routeCode"],t),F(n.routeCode,`${t}/routeCode`);return}_("NATIVE_ADMIN_PAGE_REFERENCE_KIND_INVALID",`${t}/kind`)}function Rf(e){let t=new Map(ec(e).map(r=>[String(r.code),r])),n=new Set,o=new Set;e.frontend.admin.navigation.forEach((r,i)=>{let s=`/config/frontend/admin/navigation/${i}`;n.has(r.code)&&_("NATIVE_ADMIN_GROUP_DUPLICATE",`${s}/code`),n.add(r.code),r.label===r.code&&_("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${s}/label`),r.items.forEach((a,d)=>{let c=`${s}/items/${d}`,l=tc(a.page),f=t.get(l);(!f||f.navigationEligible!==!0)&&_("NATIVE_ADMIN_PAGE_NOT_FOUND",`${c}/page`),o.has(l)&&_("NATIVE_ADMIN_PAGE_DUPLICATE",`${c}/page`),o.add(l);let p=a.page.resourceCode||a.page.routeCode||a.page.workflowCode||l,m=a.label||f.label;(!m||m===p||m===l)&&_("NATIVE_ADMIN_USER_LABEL_REQUIRED",`${c}/label`)})})}function Tf(e,t){let n=D(e,t,q.adminPages),o=new Set;n.forEach((r,i)=>{let s=`${t}/${i}`,a=N(r,s);R(a,["code","kind","path","label","navigationEligible","capability","access","resourceCode","viewCode","routeCode"],s,!0);let d=k(a.code,`${s}/code`,255);o.has(d)&&_("NATIVE_ADMIN_PAGE_DUPLICATE",`${s}/code`),o.add(d);let c=k(a.kind,`${s}/kind`,64);if(["resource-list","resource-detail","resource-create","resource-update","operation"].includes(c)||_("NATIVE_ADMIN_PAGE_KIND_INVALID",`${s}/kind`),Je(a.path,`${s}/path`),k(a.label,`${s}/label`,255),_n(a.navigationEligible,`${s}/navigationEligible`),a.capability!==void 0&&a.access!==void 0&&_("NATIVE_ROUTE_ACCESS_CONFLICT",`${s}/access`),a.capability!==void 0&&k(a.capability,`${s}/capability`,255),a.access!==void 0){let l=N(a.access,`${s}/access`);R(l,["allOf","anyOf"],`${s}/access`,!0);for(let f of["allOf","anyOf"])l[f]!==void 0&&V(l[f],`${s}/access/${f}`,50)}for(let l of["resourceCode","viewCode","routeCode"])a[l]!==void 0&&F(a[l],`${s}/${l}`)})}function Cf(e,t){let n=D(e,t,q.adminNavigationGroups);n.reduce((r,i)=>r+(Array.isArray(i?.items)?i.items.length:0),0)>q.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t);let o=0;n.forEach((r,i)=>{let s=`${t}/${i}`,a=N(r,s);R(a,["code","label","icon","order","items"],s,!0),F(a.code,`${s}/code`),k(a.label,`${s}/label`,255),Zo(a.icon,`${s}/icon`),Ae(a.order,`${s}/order`,-1e4,1e4);let d=D(a.items,`${s}/items`,500);d.length===0&&_("NATIVE_ADMIN_GROUP_ORPHANED",`${s}/items`),o+=d.length,o>q.adminNavigationItems&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),d.forEach((c,l)=>{let f=`${s}/items/${l}`,p=N(c,f);R(p,["pageCode","label","icon","order"],f,!0),k(p.pageCode,`${f}/pageCode`,255),p.label!==void 0&&k(p.label,`${f}/label`,255),Zo(p.icon,`${f}/icon`),Ae(p.order,`${f}/order`,-1e4,1e4)})})}var Sf=new Set(["application-todo-center","workflow-work-center","workflow-launch","workflow-task","workflow-instance","resource-records","resource-submit"]);function Df(e,t,n){let o=N(e,t);R(o,["schemaVersion","appCode","devicePolicy","rootEntry","authentication","routes","digest"],t),x(o.schemaVersion,Jd,`${t}/schemaVersion`),x(o.appCode,n,`${t}/appCode`),Xi(o.devicePolicy,`${t}/devicePolicy`),kf(o.rootEntry,`${t}/rootEntry`),Lf(o.authentication,`${t}/authentication`),Hi(o.digest,`${t}/digest`);let r=D(o.routes,`${t}/routes`,q.routes),i=new Set;r.forEach((s,a)=>{let d=`${t}/routes/${a}`,c=N(s,d),l=c.kind==="resource-records"||c.kind==="resource-submit";R(c,["code","kind","desktop","mobile"],d,["workflowCode",...l?["resourceCode"]:[]]);let f=k(c.code,`${d}/code`,255);i.has(f)&&_("NATIVE_ROUTE_MANIFEST_DUPLICATE",`${d}/code`),i.add(f);let p=k(c.kind,`${d}/kind`,64);if(Sf.has(p)||_("NATIVE_ROUTE_MANIFEST_KIND_INVALID",`${d}/kind`),c.workflowCode!==void 0&&F(c.workflowCode,`${d}/workflowCode`),l){let I=Q(c.resourceCode,`${d}/resourceCode`);x(f,`user.${I}.${c.kind==="resource-records"?"records":"submit"}`,`${d}/code`)}else c.resourceCode!==void 0&&_("NATIVE_PROPERTY_UNKNOWN",`${d}/resourceCode`);let m=Fd(c.desktop,`${d}/desktop`,n),A=Fd(c.mobile,`${d}/mobile`,n);m.surface!=="user"&&_("NATIVE_ROUTE_MANIFEST_DESKTOP_SURFACE_INVALID",`${d}/desktop/surface`),A.surface!=="user"&&_("NATIVE_ROUTE_MANIFEST_MOBILE_SURFACE_INVALID",`${d}/mobile/surface`),m.routeCode===A.routeCode&&_("NATIVE_ROUTE_MANIFEST_PAIR_DUPLICATE",d)}),x(o.digest,ee({schemaVersion:o.schemaVersion,appCode:o.appCode,devicePolicy:o.devicePolicy,rootEntry:o.rootEntry,authentication:o.authentication,routes:o.routes}),`${t}/digest`)}function Xi(e,t){let n=N(e,t);R(n,["kind","mobileMaxWidthPx","desktopMinWidthPx"],t),x(n.kind,"viewport-family",`${t}/kind`);let o=Ae(n.mobileMaxWidthPx,`${t}/mobileMaxWidthPx`,320,1600),r=Ae(n.desktopMinWidthPx,`${t}/desktopMinWidthPx`,320,1600);return r!==o+1&&_("NATIVE_FRONTEND_DEVICE_POLICY_INVALID",t),{kind:"viewport-family",mobileMaxWidthPx:o,desktopMinWidthPx:r}}function kf(e,t){let n=N(e,t);R(n,["code","desktop","mobile"],t);let o=F(n.code,`${t}/code`),r=Ji(n.desktop,`${t}/desktop`),i=Ji(n.mobile,`${t}/mobile`);return(r===i||i==="/"||!i.startsWith("/m/"))&&_("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",t),r.startsWith("/m/")&&_("NATIVE_ROUTE_MANIFEST_ROOT_ENTRY_INVALID",`${t}/desktop`),{code:o,desktop:r,mobile:i}}function Lf(e,t){let n=N(e,t);R(n,["desktop","mobile"],t);let o=$d(n.desktop,`${t}/desktop`,!1),r=$d(n.mobile,`${t}/mobile`,!0);return(o.routeCode===r.routeCode||o.path===r.path)&&_("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_DUPLICATE",t),{desktop:o,mobile:r}}function $d(e,t,n){let o=N(e,t);R(o,["routeCode","path"],t);let r=F(o.routeCode,`${t}/routeCode`),i=Ji(o.path,`${t}/path`);return(n?!i.startsWith("/m/"):i.startsWith("/m/"))&&_("NATIVE_ROUTE_MANIFEST_AUTHENTICATION_PATH_INVALID",`${t}/path`),{routeCode:r,path:i}}function Ji(e,t){let n=Je(e,t);return/[:*?#\\\\]/.test(n)&&_("NATIVE_ROUTE_MANIFEST_STATIC_PATH_INVALID",t),n}function Fd(e,t,n){let o=N(e,t);R(o,["routeCode","path","surface","pathParams","requiresAuthentication"],t,["capability","access"]),F(o.routeCode,`${t}/routeCode`);let r=Je(o.path,`${t}/path`),i=k(o.surface,`${t}/surface`,16);["admin","user"].includes(i)||_("NATIVE_ROUTE_SURFACE_INVALID",`${t}/surface`);let s=V(o.pathParams,`${t}/pathParams`,8);return s.forEach((a,d)=>{(!/^[A-Za-z][A-Za-z0-9_]*$/.test(a)||a.length>64)&&_("NATIVE_ROUTE_PATH_PARAM_INVALID",`${t}/pathParams/${d}`)}),re(s)!==re(nc(r))&&_("NATIVE_ROUTE_PATH_PARAMS_MISMATCH",`${t}/pathParams`),Zi(o,t,n),o.requiresAuthentication!==!0&&_("NATIVE_ROUTE_AUTHENTICATION_REQUIRED",`${t}/requiresAuthentication`),o}function nc(e){return K([...e.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(t=>t[1]))}function Vd(e,t,n,o){return{routeCode:e,path:t,surface:n,pathParams:nc(t),...o?.capability?{capability:o.capability}:{},...o?.access?{access:o.access}:{},requiresAuthentication:!0}}function Wd(e,t,n,o){return e==="workflow-launch"?`workflow.${n}.launch.${t}`:e==="application-todo-center"?`application.todo-center.${t}`:e==="resource-records"?`user.${o}.records.${t}`:e==="resource-submit"?`user.${o}.submit.${t}`:`${e.replace(/-/g,".")}.${t}`}function vf(e){let t=e.appCode,n=[],o=(m,A,I,O,b,g,y)=>{n.push({code:m,kind:A,...b?{workflowCode:b}:{},...y?{resourceCode:y}:{},desktop:Vd(Wd(A,"desktop",b,y),I,"user",g),mobile:Vd(Wd(A,"mobile",b,y),O,"user",g)})};e.frontend.user.applicationTodoCenter===!0&&o("application:todo-center","application-todo-center","/todos","/m/todos");let r=oc(e);r.length>0&&(o("workflow:work-center","workflow-work-center","/work-center","/m/work-center"),o("workflow:task","workflow-task","/tasks/:taskId","/m/tasks/:taskId"),o("workflow:instance","workflow-instance","/workflows/:instanceId","/m/workflows/:instanceId"));for(let m of r){if(!["standalone","hidden-handoff"].includes(m.launch.mode))continue;let A=K([m.launch.submission?.create?.requiredCapability,m.launch.submission?.existing?.requiredCapability].filter(I=>!!I));o(`workflow:${m.code}:launch`,"workflow-launch","/workflows/:workflowCode/start","/m/workflows/:workflowCode/start",m.code,A.length===1?{capability:A[0]}:A.length>1?{access:{anyOf:A}}:void 0)}let i=n.sort((m,A)=>Pe(String(m.code),String(A.code))),s=tr(e),a=m=>{let A=m==="mobile"?"/m/":"/",I=s.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&b.path===A).sort((b,g)=>Pe(b.code,g.code))[0];if(I)return{code:I.code,path:I.path};let O=s.filter(b=>b.surface==="user"&&!/[:*?#\\\\]/.test(b.path)&&(m==="mobile"?b.path.startsWith("/m/"):!b.path.startsWith("/m/"))).sort((b,g)=>Pe(b.code,g.code))[0];return O?{code:O.code,path:O.path}:{code:m==="mobile"?"application-root-mobile":"application-root",path:A}},d=e.frontend.authentication?{desktop:{routeCode:e.frontend.authentication.surfaces.desktop.routeCode,path:e.frontend.authentication.surfaces.desktop.path},mobile:{routeCode:e.frontend.authentication.surfaces.mobile.routeCode,path:e.frontend.authentication.surfaces.mobile.path}}:{desktop:{routeCode:"application-login",path:"/login"},mobile:{routeCode:"application-login-mobile",path:"/m/login"}},c=Xi(e.frontend.devicePolicy,"/config/frontend/devicePolicy"),l=a("desktop"),f=a("mobile"),p={schemaVersion:Jd,appCode:t,devicePolicy:c,rootEntry:{code:l.code,desktop:l.path,mobile:f.path},authentication:d,routes:i};return{...p,digest:ee(p)}}function Zo(e,t){if(e===void 0)return;let n=k(e,t,32);zu.has(n)||_("NATIVE_ADMIN_ICON_INVALID",t)}function xd(e,t){e!==void 0&&Ae(e,t,-1e4,1e4)}function Zi(e,t,n){return e.capability!==void 0&&e.access!==void 0&&_("NATIVE_ROUTE_ACCESS_CONFLICT",`${t}/access`),e.capability!==void 0?{capability:ve(e.capability,`${t}/capability`,n)}:e.access===void 0?{}:{access:nr(e.access,`${t}/access`,n)}}function nr(e,t,n){let o=N(e,t);R(o,["allOf","anyOf"],t,!0);let r=o.allOf===void 0?void 0:K(V(o.allOf,`${t}/allOf`,50).map((s,a)=>ve(s,`${t}/allOf/${a}`,n))),i=o.anyOf===void 0?void 0:K(V(o.anyOf,`${t}/anyOf`,50).map((s,a)=>ve(s,`${t}/anyOf/${a}`,n)));return(r?.length||0)+(i?.length||0)===0&&_("NATIVE_ROUTE_ACCESS_EMPTY",t),{...r===void 0?{}:{allOf:r},...i===void 0?{}:{anyOf:i}}}function oc(e){let t=new Map(Yd(e).map(r=>[String(r.code),r])),n=e.workflows.definitions.map((r,i)=>{let s=`/config/workflows/definitions/${i}`,a=N(r,s);R(a,["version","definition","launch"],s,["detailRouteCode"]);let d=N(a.definition,`${s}/definition`),c=a.detailRouteCode===void 0?void 0:ic(a.detailRouteCode,`${s}/detailRouteCode`);return{code:F(d.code,`${s}/definition/code`),title:k(d.title,`${s}/definition/title`,255),version:gn(a.version,`${s}/version`),launch:Pf(e,d,a.launch,`${s}/launch`,t),...c?{detailRouteCode:c}:{},definition:d}});return K(n.map(r=>r.code)).map(r=>{let i=n.filter(c=>c.code===r),s=e.workflows.activations.find(c=>c.workflowCode===r)?.definitionVersion,a=i.find(c=>c.version===s)||[...i].sort((c,l)=>l.version-c.version)[0],d=new Set;for(let c of i){let l=N(c.definition.nodes,"/config/workflows/definitions/nodes");for(let f of Object.values(l)){let p=N(f,"/config/workflows/definitions/nodes/*");if(!(p.kind!=="approval"&&p.kind!=="handle"))for(let m of V(p.allowedOperations||[],"/config/workflows/definitions/nodes/*/allowedOperations",20))d.add(m)}}return{code:r,title:a.title,acceptedCommandDeactivationPolicy:a.definition.acceptedCommandDeactivationPolicy,subject:a.definition.subject,launch:a.launch,...["standalone","hidden-handoff"].includes(a.launch.mode)&&!a.launch.submission?{processOperationCode:`openxiangda.workflow.${r}.submit`}:{},...a.detailRouteCode?{detailRouteCode:a.detailRouteCode}:{},definitionVersions:zd(i.map(c=>c.version)),bindingVersions:zd(e.workflows.bindings.map((c,l)=>{let f=`/config/workflows/bindings/${l}`,p=N(c,f),m=N(p.binding,`${f}/binding`);return{code:F(m.workflowCode,`${f}/binding/workflowCode`),version:gn(p.version,`${f}/version`)}}).filter(c=>c.code===r).map(c=>c.version)),providerCodes:K(e.workflows.providers.map((c,l)=>F(N(c,`/config/workflows/providers/${l}`).code,`/config/workflows/providers/${l}/code`))),allowedOperations:[...d].sort(Pe),editableParameterCodes:K(e.workflows.editableParameters.map((c,l)=>{let f=`/config/workflows/editableParameters/${l}`,p=N(c,f);return{code:F(p.code,`${f}/code`),workflowCode:F(p.workflowCode,`${f}/workflowCode`)}}).filter(c=>c.workflowCode===r).map(c=>c.code))}})}function rc(e,t){let n=N(e,t);R(n,["mode"],t,["submission"]);let o=k(n.mode,`${t}/mode`,32);return["standalone","custom-page","hidden-handoff","work-center-only"].includes(o)||_("NATIVE_WORKFLOW_LAUNCH_MODE_INVALID",`${t}/mode`),{mode:o,...n.submission===void 0?{}:{submission:N(n.submission,`${t}/submission`)}}}function Pf(e,t,n,o,r){let i=rc(n,o);if(!i.submission)return{mode:i.mode};["standalone","hidden-handoff"].includes(i.mode)||_("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${o}/submission`);let s=N(i.submission,`${o}/submission`);R(s,["kind"],`${o}/submission`,["create","existing","context"]),x(s.kind,"named-operation",`${o}/submission/kind`);let a=o.endsWith("/launch")?o.slice(0,-7):o,d=N(t.subject,`${a}/definition/subject`),c=Q(d.resourceCode,`${a}/definition/subject/resourceCode`),l=e.data.resources.findIndex(E=>E.code===c),f=e.data.resources[l];(l<0||!f)&&_("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${a}/definition/subject/resourceCode`);let p=new Set(N(f.schema,`/config/data/resources/${l}/schema`).fields.map(E=>String(E.code))),m=new Map(e.backend.operations.map(E=>[String(E.code),E])),A=(E,w)=>{let S=`${o}/submission/${w}`,T=N(E,S);R(T,["operationCode","inputs","output"],S);let C=F(T.operationCode,`${S}/operationCode`),v=m.get(C),P=r.get(C),H=P?.platformAccess?.workflow?.codes;(!v||!P||P.method!=="POST"||!Array.isArray(H)||!H.includes(t.code))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INVALID",S);let ne=N(v.requestSchema,`${S}/operation/requestSchema`),Z=N(ne.properties,`${S}/operation/requestSchema/properties`),Ce=new Set(ne.required===void 0?[]:V(ne.required,`${S}/operation/requestSchema/required`,205)),Ee=N(T.inputs,`${S}/inputs`),Ie=Object.entries(Ee);(!Ie.length||Ie.length>205)&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${S}/inputs`);let fe=new Set,ye=new Map,$={},Y=P.platformAccess?.ownedSubject;Y&&(w!=="create"||Y.resourceCode!==c)&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_MISMATCH",S);for(let[B,oe]of Ie){(!kd.test(B)||!Object.prototype.hasOwnProperty.call(Z,B))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${S}/inputs/${B}`);let se=`${S}/inputs/${B}`,pe=N(oe,se),te=k(pe.source,`${se}/source`,32);if(["field","idempotency-key","current-user-reference","subject-id","subject-revision","requested-at"].includes(te)||_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",se),R(pe,["source"],se,te==="field"?["fieldCode"]:!1),ye.set(te,(ye.get(te)||0)+1),te==="field"){let de=J(pe.fieldCode,`${se}/fieldCode`);(fe.has(de)||!p.has(de))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${se}/fieldCode`),fe.add(de),f.schema.fields.find(Xe=>Xe.code===de)?.type==="subtable"&&(!Y||!Y.subtables.some(Xe=>Xe.fieldCode===de))&&_("NATIVE_WORKFLOW_OWNED_SUBJECT_LAUNCH_REQUIRED",se),$[B]={source:te,fieldCode:de}}else $[B]={source:te}}([...Ce].some(B=>!(B in Ee))||(ye.get("idempotency-key")||0)!==1||!Ie.some(([B,oe])=>N(oe,`${S}/inputs/${B}`).source==="idempotency-key"&&Ce.has(B))||w==="create"&&((ye.get("subject-id")||0)>0||(ye.get("subject-revision")||0)>0)||w==="existing"&&((ye.get("subject-id")||0)!==1||(ye.get("subject-revision")||0)!==1))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_INPUT_INVALID",`${S}/inputs`);let W=N(T.output,`${S}/output`);R(W,["subjectId"],`${S}/output`,["subjectRevision","processCommand"]);let M=N(N(v.responseSchema,`${S}/operation/responseSchema`).properties,`${S}/operation/responseSchema/properties`);for(let B of["subjectId","subjectRevision","processCommand"]){if(W[B]===void 0)continue;let oe=k(W[B],`${S}/output/${B}`,128);(!kd.test(oe)||!Object.prototype.hasOwnProperty.call(M,oe))&&_("NATIVE_WORKFLOW_NAMED_OPERATION_OUTPUT_INVALID",`${S}/output/${B}`)}return{operationCode:C,method:"POST",path:P.path,requiredCapability:P.requiredCapability,requestSchemaDigest:P.requestSchemaDigest,responseSchemaDigest:P.responseSchemaDigest,inputs:$,output:{...W},fieldCodes:fe}},I=s.create===void 0?void 0:A(s.create,"create"),O=s.existing===void 0?void 0:A(s.existing,"existing");!I&&!O&&_("NATIVE_WORKFLOW_NAMED_OPERATION_SUBMISSION_INVALID",`${o}/submission`);let b=new Set([...I?.fieldCodes||[],...O?.fieldCodes||[]]),g=s.context===void 0?[]:D(s.context,`${o}/submission/context`,16),y=new Set,h=g.map((E,w)=>{let S=`${o}/submission/context/${w}`,T=N(E,S);R(T,["queryParameter","fieldCode"],S);let C=k(T.queryParameter,`${S}/queryParameter`,64),v=J(T.fieldCode,`${S}/fieldCode`);return(!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(C)||y.has(C)||!b.has(v))&&_("NATIVE_WORKFLOW_LAUNCH_CONTEXT_INVALID",S),y.add(C),{queryParameter:C,fieldCode:v}}),u=E=>{let{fieldCodes:w,...S}=E;return S};return{mode:i.mode,submission:{kind:"named-operation",...I?{create:u(I)}:{},...O?{existing:u(O)}:{},context:h}}}function ic(e,t){let n=N(e,t);R(n,["desktop","mobile"],t);let o=F(n.desktop,`${t}/desktop`),r=F(n.mobile,`${t}/mobile`);return o===r&&_("NATIVE_WORKFLOW_DETAIL_ROUTE_DUPLICATE",t),{desktop:o,mobile:r}}function $f(e,t){let n=new Set(t.map(l=>l.code)),o=new Map;e.data.resources.forEach((l,f)=>{let p=`/config/data/resources/${f}`,m=N(l,p);if(m.recordDeletion!==void 0){let O=`${p}/recordDeletion/delete`;for(let b of m.recordDeletion.delete)ve(b,O,e.appCode),n.has(b)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(m.recordComments!==void 0)for(let O of["read","create"]){let b=`${p}/recordComments/${O}`;for(let g of m.recordComments[O])ve(g,b,e.appCode),n.has(g)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",b)}if(m.recordPrint!==void 0){let O=`${p}/recordPrint/read`;for(let b of m.recordPrint.read)ve(b,O,e.appCode),n.has(b)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}if(m.workflowHistory!==void 0){let O=`${p}/workflowHistory/read`;for(let b of m.workflowHistory.read)ve(b,O,e.appCode),n.has(b)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",O)}for(let[O,b]of Object.entries(m.fieldPolicies||{})){if(!Vt(O))continue;let g=`${p}/fieldPolicies/${O}/read`,y=N(b,`${p}/fieldPolicies/${O}`);for(let h of V(y.read||[],g,2e3))n.has(h)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",g)}let A=m.surface===void 0?{}:N(m.surface,`${p}/surface`);if(["native","queued-command"].includes(A.mutationOwner||"native"))return;let I=N(m.capabilities,`${p}/capabilities`);for(let O of["create","update","delete"])O==="delete"&&Array.isArray(m.recordDeletion?.delete)&&m.recordDeletion.delete.length>0||o.set(String(I[O]),O)});let r=new Set;for(let[l,f]of e.authz.roles.entries()){let p=`/config/authz/roles/${l}`,m=N(f,p);R(m,["code","name","description","capabilities","organizationReach"],p,!0);let A=F(m.code,`${p}/code`);r.has(A)&&_("NATIVE_ROLE_DUPLICATE",`${p}/code`),r.add(A),k(m.name,`${p}/name`,255);let I=V(m.capabilities,`${p}/capabilities`,2e3);for(let[O,b]of I.entries())o.has(b)&&_("NATIVE_DATA_SURFACE_MUTATION_GRANT_FORBIDDEN",`${p}/capabilities/${O}`,{operation:o.get(b)}),n.has(b)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capabilities`)}let i=e.authz.authenticatedUserRoleCode===void 0?"":F(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode");i&&!r.has(i)&&_("NATIVE_AUTHENTICATED_USER_ROLE_REFERENCE_MISSING","/config/authz/authenticatedUserRoleCode");let s=new Set,a=0;for(let[l,f]of e.perspectives.entries()){let p=`/config/perspectives/${l}`,m=N(f,p);R(m,["code","name","description","roleCodes","capabilityCodes","default"],p,!0);let A=F(m.code,`${p}/code`);s.has(A)&&_("NATIVE_PERSPECTIVE_DUPLICATE",`${p}/code`),s.add(A),k(m.name,`${p}/name`,255);let I=V(m.roleCodes,`${p}/roleCodes`,20);I.length<1&&_("NATIVE_PERSPECTIVE_ROLE_REQUIRED",`${p}/roleCodes`),I.forEach((g,y)=>{r.has(g)||_("NATIVE_PERSPECTIVE_ROLE_MISSING",`${p}/roleCodes/${y}`)});let O=K(e.authz.roles.filter(g=>I.includes(g.code)).flatMap(g=>g.capabilities)),b=V(m.capabilityCodes,`${p}/capabilityCodes`,2e3);re(O)!==re(b)&&_("NATIVE_PERSPECTIVE_CAPABILITY_PROJECTION_MISMATCH",`${p}/capabilityCodes`),m.default===!0?a+=1:m.default!==void 0&&_("NATIVE_PERSPECTIVE_DEFAULT_INVALID",`${p}/default`)}a>1&&_("NATIVE_PERSPECTIVE_DEFAULT_DUPLICATE","/config/perspectives");for(let[l,f]of e.backend.operations.entries()){let p=N(f,`/config/backend/operations/${l}`);n.has(p.capability)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/backend/operations/${l}/capability`)}let d=new Set,c=new Set;for(let[l,f]of e.frontend.routes.entries()){let p=`/config/frontend/routes/${l}`,m=N(f,p),A=F(m.code,`${p}/code`);d.has(A)&&_("NATIVE_ROUTE_DUPLICATE",`${p}/code`),d.add(A);let I=Je(m.path,`${p}/path`);c.has(I)&&_("NATIVE_ROUTE_PATH_DUPLICATE",`${p}/path`),c.add(I);let O=Zi(m,p,e.appCode);O.capability&&!n.has(O.capability)&&_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/capability`);let b=m.access===void 0?void 0:N(m.access,`${p}/access`);for(let g of["allOf","anyOf"]){let y=b?.[g]===void 0?[]:D(b[g],`${p}/access/${g}`,50);for(let[h,u]of y.entries()){let E=ve(u,`${p}/access/${g}/${h}`,e.appCode);n.has(E)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`${p}/access/${g}/${h}`)}}}if(e.frontend.admin.access!==void 0){let l=nr(e.frontend.admin.access,"/config/frontend/admin/access",e.appCode);for(let f of["allOf","anyOf"])for(let[p,m]of(l[f]||[]).entries())n.has(m)||_("NATIVE_CAPABILITY_REFERENCE_MISSING",`/config/frontend/admin/access/${f}/${p}`)}for(let[l,f]of e.frontend.routes.entries()){let p=N(f,`/config/frontend/routes/${l}`);p.parentCode&&!d.has(p.parentCode)&&_("NATIVE_ROUTE_PARENT_MISSING",`/config/frontend/routes/${l}/parentCode`)}}function Ff(e){let t=new Set(e.authz.roles.map(c=>String(c.code))),n=e.authz.authenticatedUserRoleCode===void 0?"":F(e.authz.authenticatedUserRoleCode,"/config/authz/authenticatedUserRoleCode"),o=new Map(e.authz.scopeDimensions.map(c=>[String(c.code),{valueType:c.valueType==="uuid"?"uuid":"string",...c.valueSource?.resourceCode?{valueSourceResourceCode:String(c.valueSource.resourceCode)}:{}}])),r=new Set(o.keys()),i=new Map(e.data.resources.map((c,l)=>{let f=Ut(c,`/config/data/resources/${l}`,e.appCode);return[f.code,new Map(f.schema.fields.map(p=>[String(p.code),p]))]}));for(let[c,l]of e.authz.scopeDimensions.entries()){let f=`/config/authz/scopeDimensions/${c}`,p=N(l,f);if(R(p,["code","name","resourceCode","valueType","hierarchyMode","valueSource"],f,!0),p.valueSource===void 0)continue;let m=N(p.valueSource,`${f}/valueSource`);R(m,["kind","resourceCode","labelField","enabledField"],`${f}/valueSource`,!0),m.kind!=="native_resource"&&_("NATIVE_SCOPE_VALUE_SOURCE_KIND_INVALID",`${f}/valueSource/kind`),p.valueType!=="uuid"&&_("NATIVE_SCOPE_VALUE_SOURCE_TYPE_INVALID",`${f}/valueType`);let A=Q(m.resourceCode,`${f}/valueSource/resourceCode`),I=i.get(A);I||_("NATIVE_SCOPE_VALUE_SOURCE_RESOURCE_MISSING",`${f}/valueSource/resourceCode`);let O=J(m.labelField,`${f}/valueSource/labelField`);if(["text.short","text.long"].includes(String(I.get(O)?.type||""))||_("NATIVE_SCOPE_VALUE_SOURCE_LABEL_FIELD_INVALID",`${f}/valueSource/labelField`),m.enabledField!==void 0){let b=J(m.enabledField,`${f}/valueSource/enabledField`);I.get(b)?.type!=="boolean"&&_("NATIVE_SCOPE_VALUE_SOURCE_ENABLED_FIELD_INVALID",`${f}/valueSource/enabledField`)}}let s=new Set,a=new Set;for(let[c,l]of e.authz.scopeSources.entries()){let f=`/config/authz/scopeSources/${c}`,p=N(l,f);R(p,["code","name","resourceCode","subject","grants","operationField","enabledField","effectiveFromField","effectiveToField","failureMode"],f,!0);let m=F(p.code,`${f}/code`);s.has(m)&&_("NATIVE_SCOPE_SOURCE_DUPLICATE",`${f}/code`),s.add(m),k(p.name,`${f}/name`,255);let A=Q(p.resourceCode,`${f}/resourceCode`),I=i.get(A);I||_("NATIVE_SCOPE_SOURCE_RESOURCE_MISSING",`${f}/resourceCode`);let O=N(p.subject,`${f}/subject`),b=k(O.type,`${f}/subject/type`,32);R(O,b==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${f}/subject`),["user","role_membership"].includes(b)||_("NATIVE_SCOPE_SOURCE_SUBJECT_INVALID",`${f}/subject/type`);let g=Rn(O.userIdField,I);ci(g)||_("NATIVE_SCOPE_SOURCE_SUBJECT_PATH_INVALID",`${f}/subject/userIdField`),b==="role_membership"&&!t.has(String(O.roleCode))&&_("NATIVE_ROLE_REFERENCE_MISSING",`${f}/subject/roleCode`);let y=new Set;for(let[h,u]of D(p.grants,`${f}/grants`,100).entries()){let E=`${f}/grants/${h}`,w=N(u,E);R(w,["dimensionCode","valueField","parentValueField"],E,!0);let S=F(w.dimensionCode,`${E}/dimensionCode`);(!r.has(S)||y.has(S))&&_("NATIVE_SCOPE_SOURCE_DIMENSION_INVALID",`${E}/dimensionCode`),y.add(S),p.failureMode==="last_known_good"&&a.add(S);for(let T of["valueField","parentValueField"]){if(w[T]===void 0)continue;let C=Rn(w[T],I);Ea(C,o.get(S),i)||_("NATIVE_SCOPE_SOURCE_GRANT_PATH_INVALID",`${E}/${T}`)}}y.size===0&&_("NATIVE_SCOPE_SOURCE_GRANT_REQUIRED",`${f}/grants`),["strict","last_known_good"].includes(p.failureMode)||_("NATIVE_SCOPE_SOURCE_FAILURE_MODE_INVALID",`${f}/failureMode`);for(let h of["operationField","enabledField","effectiveFromField","effectiveToField"]){if(p[h]===void 0)continue;let u=J(p[h],`${f}/${h}`);I.has(u)||_("NATIVE_SCOPE_SOURCE_FIELD_MISSING",`${f}/${h}`)}}Wf(e,t,i,n);let d=new Set;for(let[c,l]of e.authz.dataPolicies.entries()){let f=`/config/authz/dataPolicies/${c}`,p=N(l,f);R(p,["code","name","resourceCode","unrestrictedRoleCodes","publicRead","operations","matchMode","rules","readExpression","writeBoundary"],f,!0);let m=F(p.code,`${f}/code`);d.has(m)&&_("NATIVE_DATA_POLICY_DUPLICATE",`${f}/code`),d.add(m);let A=p.readExpression!==void 0,I=V(p.operations||[],`${f}/operations`,4);p.operations!==void 0&&(I.length===0||I.some(u=>!["read","create","update","delete"].includes(u)))&&_("NATIVE_DATA_POLICY_OPERATIONS_INVALID",`${f}/operations`),["AND","OR"].includes(p.matchMode)||_("NATIVE_DATA_POLICY_MATCH_MODE_INVALID",`${f}/matchMode`),A&&p.operations!==void 0&&_("NATIVE_DATA_POLICY_READ_EXPRESSION_OPERATIONS_FORBIDDEN",`${f}/operations`);let O=e.data.resources.find(u=>u.dataPolicyCode===m),b=p.resourceCode||O?.code,g=b?i.get(Q(b,`${f}/resourceCode`)):void 0;if(A&&!g&&_("NATIVE_DATA_POLICY_RESOURCE_MISSING",`${f}/resourceCode`),p.publicRead!==void 0){try{let u=e.authz.roles.find(E=>E.code===n);Ma({policy:p,resource:e.data.resources.find(E=>E.code===b),baselineRoleCode:n,baselineCapabilities:u?.capabilities||[],baselineDeniedCapabilities:u?.deniedCapabilities||[],pointer:f})}catch(u){if(!(u instanceof kn))throw u;_(u.code,u.pointer)}(p.unrestrictedRoleCodes||[]).includes(n)||_("AUTHENTICATED_PUBLIC_READ_CANONICAL_BASELINE_MISSING",`${f}/unrestrictedRoleCodes`)}else n&&(p.unrestrictedRoleCodes||[]).includes(n)&&_("NATIVE_DATA_POLICY_BASELINE_UNRESTRICTED",`${f}/unrestrictedRoleCodes`);let y=V(p.unrestrictedRoleCodes||[],`${f}/unrestrictedRoleCodes`,100);p.unrestrictedRoleCodes!==void 0&&y.length===0&&_("NATIVE_DATA_POLICY_UNRESTRICTED_ROLES_INVALID",`${f}/unrestrictedRoleCodes`);for(let u of y)t.has(u)||_("NATIVE_ROLE_REFERENCE_MISSING",`${f}/unrestrictedRoleCodes`);let h;try{let u=D(p.rules,`${f}/rules`,100).map((E,w)=>({rule:N(E,`${f}/rules/${w}`),pointer:`${f}/rules/${w}`}));u.length===0?(!A||p.matchMode!=="AND"||p.writeBoundary!=="capability_only")&&_("NATIVE_DATA_POLICY_WRITE_BOUNDARY_REQUIRED",f):p.writeBoundary!==void 0&&_("NATIVE_DATA_POLICY_WRITE_BOUNDARY_INVALID",`${f}/writeBoundary`),h=[...u],A&&(h.push(...an(p.readExpression,`${f}/readExpression`)),ka(p.readExpression,`${f}/readExpression`))}catch(u){throw u instanceof Dn&&_(u.code,u.pointer),u}for(let{rule:u,pointer:E}of h){if(R(u,["parentRead","subject","dimensionCode","relationCode","resourceCode","field","roleCodes","operation","valuePath","emptyMatchesAll","operator","value","operand"],E,!0),u.parentRead!==void 0){for(let Z of V(u.roleCodes||[],`${E}/roleCodes`,100))t.has(Z)||_("NATIVE_ROLE_REFERENCE_MISSING",`${E}/roleCodes`);continue}let w=J(u.field,`${E}/field`),S=g?.get(w);A&&!S&&_("NATIVE_DATA_POLICY_FIELD_MISSING",`${E}/field`);for(let Z of V(u.roleCodes||[],`${E}/roleCodes`,100))t.has(Z)||_("NATIVE_ROLE_REFERENCE_MISSING",`${E}/roleCodes`);let T=String(u.operator||""),C=u.operand==="db_now",v=["is_null","is_not_null"].includes(T),P=["eq","not_eq","in","not_in"].includes(T),H=!C&&(u.operator!==void 0||u.value!==void 0);if([u.subject==="current_user"?"current_user":"",typeof u.dimensionCode=="string"?"dimension":"",typeof u.relationCode=="string"?"relationship":"",H?"constant":"",C?"db_now":""].filter(Boolean).length!==1&&_("NATIVE_DATA_POLICY_RULE_SOURCE_INVALID",E),u.subject!==void 0&&u.subject!=="current_user"&&_("NATIVE_DATA_POLICY_SUBJECT_INVALID",`${E}/subject`),H){if(!P&&!v&&_("NATIVE_DATA_POLICY_OPERATOR_INVALID",`${E}/operator`),["in","not_in"].includes(T)){let Z=D(u.value,`${E}/value`,100).map((Ce,Ee)=>k(Ce,`${E}/value/${Ee}`,2048));(Z.length===0||new Set(Z).size!==Z.length)&&_("NATIVE_DATA_POLICY_VALUE_INVALID",`${E}/value`)}else["eq","not_eq"].includes(T)?k(u.value,`${E}/value`,2048):(u.value!==void 0||u.operand!==void 0)&&_("NATIVE_DATA_POLICY_VALUE_INVALID",`${E}/value`);for(let Z of["operation","valuePath","emptyMatchesAll","resourceCode","operand"])u[Z]!==void 0&&_("NATIVE_DATA_POLICY_CONSTANT_RULE_INVALID",`${E}/${Z}`)}if(C){(!["lt","lte","gt","gte"].includes(T)||u.value!==void 0||S?.type!=="datetime")&&_("NATIVE_DATA_POLICY_DB_NOW_INVALID",E);for(let Z of["operation","valuePath","emptyMatchesAll","resourceCode","value"])u[Z]!==void 0&&_("NATIVE_DATA_POLICY_DB_NOW_INVALID",`${E}/${Z}`)}u.dimensionCode&&!r.has(u.dimensionCode)&&_("NATIVE_SCOPE_DIMENSION_MISSING",`${E}/dimensionCode`),a.has(String(u.dimensionCode||""))&&u.operation!=="read"&&_("NATIVE_SCOPE_SOURCE_LAST_KNOWN_GOOD_UNSAFE",`${E}/operation`)}}try{$a(e.data.resources,e.authz.dataPolicies)}catch(c){throw c instanceof Te&&_(c.code,c.pointer),c}for(let[c,l]of e.data.resources.entries()){let f=N(l,`/config/data/resources/${c}`);f.dataPolicyCode&&!d.has(f.dataPolicyCode)&&_("NATIVE_DATA_POLICY_REFERENCE_MISSING",`/config/data/resources/${c}/dataPolicyCode`)}}function Vf(e){try{Xs(e.data.resources,"/config/data/resources"),e.data.resources.forEach((t,n)=>Ms(t.schema.fields,new Set(e.authz.roles.map(o=>o.code)),new Set(e.authz.scopeDimensions.map(o=>o.code)),`/config/data/resources/${n}/schema/fields`))}catch(t){throw(t instanceof We||t instanceof $t)&&_(t.code,t.pointer),t}}function Wf(e,t,n,o){let r=new Set;for(let[i,s]of e.authz.roleMembershipSources.entries()){let a=`/config/authz/roleMembershipSources/${i}`,d=N(s,a);R(d,["code","name","resourceCode","userIdField","roleCode","enabledField","effectiveFromField","effectiveToField","failureMode"],a,!0);let c=F(d.code,`${a}/code`);c.length>100&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${a}/code`),r.has(c)&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${a}/code`),r.add(c),k(d.name,`${a}/name`,255);let l=jd(d.resourceCode,`${a}/resourceCode`,n);Ud(d.userIdField,`${a}/userIdField`,l),t.has(String(d.roleCode||""))||_("NATIVE_ROLE_REFERENCE_MISSING",`${a}/roleCode`),o&&d.roleCode===o&&_("NATIVE_AUTHENTICATED_USER_ROLE_SOURCE_CONFLICT",`${a}/roleCode`),Md(d,a,l)}for(let[i,s]of e.authz.relationshipGrantSources.entries()){let a=`/config/authz/relationshipGrantSources/${i}`,d=N(s,a);R(d,["code","name","resourceCode","subject","relationCode","targetResourceCode","resourceIdField","operations","enabledField","effectiveFromField","effectiveToField","failureMode"],a,!0);let c=F(d.code,`${a}/code`);c.length>100&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_CODE_INVALID",`${a}/code`),r.has(c)&&_("NATIVE_AUTHORIZATION_PROJECTION_SOURCE_DUPLICATE",`${a}/code`),r.add(c),k(d.name,`${a}/name`,255);let l=jd(d.resourceCode,`${a}/resourceCode`,n),f=N(d.subject,`${a}/subject`),p=k(f.type,`${a}/subject/type`,32);R(f,p==="role_membership"?["type","userIdField","roleCode"]:["type","userIdField"],`${a}/subject`),["user","role_membership"].includes(p)||_("NATIVE_AUTHORIZATION_PROJECTION_SUBJECT_INVALID",`${a}/subject/type`),Ud(f.userIdField,`${a}/subject/userIdField`,l),p==="role_membership"&&!t.has(String(f.roleCode||""))&&_("NATIVE_ROLE_REFERENCE_MISSING",`${a}/subject/roleCode`),F(d.relationCode,`${a}/relationCode`);let m=Q(d.targetResourceCode,`${a}/targetResourceCode`);n.has(m)||_("NATIVE_AUTHORIZATION_PROJECTION_TARGET_RESOURCE_MISSING",`${a}/targetResourceCode`);let A=Rn(d.resourceIdField,l),I=A?.field.type==="resource-ref.single"&&A.valuePath==="value"&&A.field.source?.resourceCode===m;(d.resourceIdField==="id"?m!==String(d.resourceCode):!I)&&_("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_ID_FIELD_INVALID",`${a}/resourceIdField`);let O=V(d.operations,`${a}/operations`,20);(O.length===0||O.some(b=>b.length>64||!/^[A-Za-z0-9][A-Za-z0-9:._*-]{0,63}$/.test(b)))&&_("NATIVE_AUTHORIZATION_PROJECTION_OPERATIONS_INVALID",`${a}/operations`),Md(d,a,l)}}function jd(e,t,n){let o=Q(e,t),r=n.get(o);return r||_("NATIVE_AUTHORIZATION_PROJECTION_RESOURCE_MISSING",t),r}function Ud(e,t,n){let o=Rn(e,n);ci(o)||_("NATIVE_AUTHORIZATION_PROJECTION_USER_FIELD_INVALID",t)}function Md(e,t,n){if(e.failureMode!=="strict"&&_("NATIVE_AUTHORIZATION_PROJECTION_FAILURE_MODE_INVALID",`${t}/failureMode`),e.enabledField!==void 0){let o=J(e.enabledField,`${t}/enabledField`);n.get(o)?.type!=="boolean"&&_("NATIVE_AUTHORIZATION_PROJECTION_ENABLED_FIELD_INVALID",`${t}/enabledField`)}for(let o of["effectiveFromField","effectiveToField"]){if(e[o]===void 0)continue;let r=J(e[o],`${t}/${o}`);["date","datetime"].includes(String(n.get(r)?.type))||_("NATIVE_AUTHORIZATION_PROJECTION_EFFECTIVE_FIELD_INVALID",`${t}/${o}`)}}function xf(e){let t=new Set,n=new Set;e.forEach((o,r)=>{let i=`/config/backend/secrets/${r}`,s=N(o,i);R(s,["name","env","description","required","exposure"],i,!0);let a=k(s.name,`${i}/name`,128),d=k(s.env,`${i}/env`,128);Wu.test(a)||_("NATIVE_SECRET_NAME_INVALID",`${i}/name`),(!xu.test(d)||d.startsWith("OPENXIANGDA_")||["NODE_ENV","PORT"].includes(d))&&_("NATIVE_SECRET_ENV_INVALID",`${i}/env`),t.has(a)&&_("NATIVE_SECRET_NAME_DUPLICATE",`${i}/name`),n.has(d)&&_("NATIVE_SECRET_ENV_DUPLICATE",`${i}/env`),t.add(a),n.add(d),x(s.exposure,"active_only",`${i}/exposure`),s.required!==void 0&&_n(s.required,`${i}/required`),s.description!==void 0&&Qi(s.description,`${i}/description`,2e3)})}function jf(e){let t=new Set,n=new Map,o=new Map(e.data.resources.map(A=>[String(A.code),A])),r=new Map(e.frontend.routes.map((A,I)=>{let O=N(A,`/config/frontend/routes/${I}`);return[F(O.code,`/config/frontend/routes/${I}/code`),O]}));for(let[A,I]of e.workflows.definitions.entries()){let O=`/config/workflows/definitions/${A}`,b=N(I,O);if(R(b,["version","definition","launch"],O,["detailRouteCode"]),rc(b.launch,`${O}/launch`),b.detailRouteCode!==void 0){let v=ic(b.detailRouteCode,`${O}/detailRouteCode`);for(let[P,H,ne]of[["desktop",v.desktop,["admin","user"]],["mobile",v.mobile,["user"]]]){let Z=`${O}/detailRouteCode/${P}`,Ce=r.get(H);Ce||_("NATIVE_WORKFLOW_DETAIL_ROUTE_MISSING",Z),ne.some(fe=>fe===Ce.surface)||_("NATIVE_WORKFLOW_DETAIL_ROUTE_SURFACE_INVALID",Z);let Ee=Je(Ce.path,Z),Ie=[...Ee.matchAll(/:([A-Za-z][A-Za-z0-9_]*)/g)].map(fe=>fe[1]);(Ee.includes("*")||Ie.length!==1||Ie[0]!=="instanceId")&&_("NATIVE_WORKFLOW_DETAIL_ROUTE_PATH_INVALID",Z)}}let g=N(b.definition,`${O}/definition`),y=`${g.code}:${gn(b.version,`${O}/version`)}`;t.has(y)&&_("NATIVE_WORKFLOW_DEFINITION_DUPLICATE",O),t.add(y),Mf(g,`${O}/definition`);let h=Pi(g);h.length&&_(h[0],`${O}/definition/launchPreflight`);let u=gd(g);u.length&&_(u[0],`${O}/definition/approvedDelegation`);let E=fd(g,e.backend.operations);E.length&&_(E[0],`${O}/definition/commandHandlers`),Uf(g.subject,o,`${O}/definition/subject`);let w=g.commandHandlers?.resubmit?.derivedSubjectFields||[],S=o.get(g.subject.resourceCode);for(let v of w){let P=S?.schema.fields.find(H=>H.code===v);(!P||P.system===!0||S?.surface?.fields?.[v]?.system===!0)&&_("WORKFLOW_CORRECTION_DERIVED_SUBJECT_FIELDS_INVALID",`${O}/definition/commandHandlers/resubmit/derivedSubjectFields`)}let T=zo(g,new Map((o.get(g.subject.resourceCode)?.schema.fields||[]).map(v=>[v.code,{...o.get(g.subject.resourceCode)?.surface?.fields?.[v.code],...v,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(v.code)}])),new Map([...o].map(([v,P])=>[v,new Map(P.schema.fields.map(H=>[H.code,{...P.surface?.fields?.[H.code],...H,system:["id","revision","createdAt","updatedAt","createdBy","updatedBy"].includes(H.code)}]))])),fo(o.get(g.subject.resourceCode)?.schema||{}));T.length&&_(T[0],`${O}/definition/taskPages`);let C=Qa(g,{appCode:e.appCode,capabilities:e.authz.capabilities.map(v=>v.code),fields:new Map((o.get(g.subject.resourceCode)?.schema.fields||[]).map(v=>[v.code,v]))});C.length&&_("NATIVE_WORKFLOW_INSTANCE_COMMAND_POLICY_INVALID",`${O}/definition/instanceCommands`,{errors:C}),g.title===g.code&&_("NATIVE_WORKFLOW_USER_TITLE_REQUIRED",`${O}/definition/title`),n.set(y,g)}let i=new Set,s=new Map;for(let[A,I]of e.workflows.bindings.entries()){let O=N(I,`/config/workflows/bindings/${A}`),b=N(O.binding,`/config/workflows/bindings/${A}/binding`),g=`${b.workflowCode}:${gn(O.version,`/config/workflows/bindings/${A}/version`)}`;i.has(g)&&_("NATIVE_WORKFLOW_BINDING_DUPLICATE",`/config/workflows/bindings/${A}`),i.add(g),Bf(b,`/config/workflows/bindings/${A}/binding`),s.set(g,b)}let a=new Set(e.authz.roles.map(A=>A.code));for(let[A,I]of e.workflows.bindings.entries())for(let[O,b]of Object.entries(I.binding.bindings))if(b.provider==="conditional")for(let g of ae(b)){let y=[...Yn(g),...Object.values(g.routing?.sources||{}).map(h=>h.roleCode)];for(let h of y)a.has(h)||_("WORKFLOW_CONDITIONAL_ROLE_UNDECLARED",`/config/workflows/bindings/${A}/binding/bindings/${O}`)}let d=new Set,c=new Map;for(let[A,I]of e.workflows.activations.entries()){let O=`/config/workflows/activations/${A}`,b=N(I,O);R(b,["workflowCode","definitionVersion","bindingVersion","acceptedCommandDeactivationPolicy"],O,["environmentKey","sourceBase"]);let g=F(b.workflowCode,`${O}/workflowCode`);if(d.has(g)&&_("NATIVE_WORKFLOW_ACTIVATION_DUPLICATE",O),d.add(g),b.sourceBase!==void 0){let T=N(b.sourceBase,`${O}/sourceBase`);R(T,["definitionDigest","bindingDigest"],`${O}/sourceBase`);for(let C of["definitionDigest","bindingDigest"])/^(sha256:)?[a-f0-9]{64}$/.test(String(T[C]||""))||_("NATIVE_WORKFLOW_SOURCE_BASE_INVALID",`${O}/sourceBase/${C}`)}let y=`${g}:${gn(b.definitionVersion,`${O}/definitionVersion`)}`,h=`${g}:${gn(b.bindingVersion,`${O}/bindingVersion`)}`;t.has(y)||_("NATIVE_WORKFLOW_DEFINITION_REFERENCE_MISSING",`${O}/definitionVersion`),i.has(h)||_("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${O}/bindingVersion`);let u=n.get(y),E=s.get(h),w=Pi(u,E);w.length&&_(w[0],O);let S=ki(u,E);S.length&&_(S[0],O),(!["finish-pinned","cancel-on-deactivate"].includes(b.acceptedCommandDeactivationPolicy)||b.acceptedCommandDeactivationPolicy!==u.acceptedCommandDeactivationPolicy)&&_("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_MISMATCH",`${O}/acceptedCommandDeactivationPolicy`),Kf(u,E,`/config/workflows/activations/${A}`);try{let T=o.get(u.subject.resourceCode)?.schema.fields||[];Bs(u,E,new Map(T.map(C=>[C.code,C])),`${O}/bindings`,new Map([...o].map(([C,v])=>[C,new Map(v.schema.fields.map(P=>[P.code,P]))])))}catch(T){throw T instanceof $t&&_(T.code,T.pointer),T}c.set(g,E)}let l=Ts([...c.values()].map(A=>co(A)));l.length&&_(l[0],"/config/workflows/activations");let f=new Set;e.workflows.providers.forEach((A,I)=>{let O=`/config/workflows/providers/${I}`,b=N(A,O);R(b,["code","endpointPath","timeoutMs"],O,!0);let g=F(b.code,`${O}/code`);f.has(g)&&_("NATIVE_WORKFLOW_PROVIDER_DUPLICATE",`${O}/code`),f.add(g),Je(b.endpointPath,`${O}/endpointPath`),b.timeoutMs!==void 0&&Ae(b.timeoutMs,`${O}/timeoutMs`,100,1e4)});for(let[A,I]of c.entries())for(let[O,b]of Object.entries(N(I.bindings,"/config/workflows/bindings/*/binding/bindings"))){let g=N(b,`/config/workflows/${A}/bindings/${O}`);g.provider==="application_provider"&&!f.has(g.providerCode)&&_("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`/config/workflows/${A}/bindings/${O}/providerCode`)}let p=new Set(e.authz.roles.map(A=>A.code)),m=new Set;e.workflows.editableParameters.forEach((A,I)=>{let O=`/config/workflows/editableParameters/${I}`,b=N(A,O);R(b,["code","workflowCode","bindingKey","label","valueType","required","allowedRoleCodes","allowedProviderCodes","maxItems"],O,!0);let g=F(b.code,`${O}/code`);m.has(g)&&_("NATIVE_WORKFLOW_EDITABLE_PARAMETER_DUPLICATE",`${O}/code`),m.add(g);let y=or(b.workflowCode,`${O}/workflowCode`),h=Qo(b.bindingKey,`${O}/bindingKey`),u=c.get(y);(!u||!N(u.bindings,`${O}/bindingKey`)[h])&&_("NATIVE_WORKFLOW_EDITABLE_BINDING_MISSING",`${O}/bindingKey`),k(b.label,`${O}/label`,255),["role_code","user_ids","provider_code"].includes(b.valueType)||_("NATIVE_WORKFLOW_EDITABLE_VALUE_TYPE_INVALID",`${O}/valueType`);for(let E of V(b.allowedRoleCodes||[],`${O}/allowedRoleCodes`,100))p.has(E)||_("NATIVE_ROLE_REFERENCE_MISSING",`${O}/allowedRoleCodes`);for(let E of V(b.allowedProviderCodes||[],`${O}/allowedProviderCodes`,100))f.has(E)||_("NATIVE_WORKFLOW_PROVIDER_REFERENCE_MISSING",`${O}/allowedProviderCodes`);b.required!==void 0&&_n(b.required,`${O}/required`),b.maxItems!==void 0&&Ae(b.maxItems,`${O}/maxItems`,1,200)})}function Uf(e,t,n){let o=N(e,n);R(o,["resourceCode","factProjection"],n,["summaryFields"]);let r=Q(o.resourceCode,`${n}/resourceCode`),i=t.get(r);i||_("NATIVE_WORKFLOW_SUBJECT_RESOURCE_MISSING",`${n}/resourceCode`);let s=new Set(D(N(i.schema,`${n}/resourceCode`).fields,`${n}/resourceCode`,500).map((c,l)=>J(N(c,`${n}/resourceCode/${l}`).code,`${n}/resourceCode/${l}`))),a=N(o.factProjection,`${n}/factProjection`),d=Object.entries(a);(d.length<1||d.length>64)&&_("NATIVE_WORKFLOW_SUBJECT_FACT_PROJECTION_INVALID",`${n}/factProjection`);for(let[c,l]of d){Mu.test(c)||_("NATIVE_WORKFLOW_SUBJECT_FACT_KEY_INVALID",`${n}/factProjection/${c}`);let f=J(l,`${n}/factProjection/${c}`);s.has(f)||_("NATIVE_WORKFLOW_SUBJECT_FIELD_MISSING",`${n}/factProjection/${c}`)}if(o.summaryFields!==void 0){let c=V(o.summaryFields,`${n}/summaryFields`,Bu).map((A,I)=>J(A,`${n}/summaryFields/${I}`)),l=t.get(r),f=l.surface&&typeof l.surface=="object"&&!Array.isArray(l.surface)?l.surface:{},p=f.fields&&typeof f.fields=="object"&&!Array.isArray(f.fields)?f.fields:{},m=new Map(D(N(l.schema,`${n}/resourceCode`).fields,`${n}/resourceCode`,500).map((A,I)=>{let O=N(A,`${n}/resourceCode/${I}`);return[String(O.code),O]}));for(let[A,I]of c.entries()){let O=m.get(I),b=p[I],g=String(O?.type||""),y=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(I)||!qu.has(g)||g==="text.long"&&typeof y=="number"&&Number.isFinite(y)&&y>Ku)&&_("NATIVE_WORKFLOW_SUBJECT_SUMMARY_FIELDS_INVALID",`${n}/summaryFields/${A}`)}}}function Mf(e,t){R(e,["schemaVersion","code","title","subject","acceptedCommandDeactivationPolicy","startAt","inputSchema","nodes"],t,["authoring","organizationContext","instanceCommands","readability","taskPages","rejectionNotification","commandHandlers","launchPreflight","approvedDelegation"]),x(e.schemaVersion,"openxiangda.workflow-definition/v2",`${t}/schemaVersion`),or(e.code,`${t}/code`),k(e.title,`${t}/title`,255),["finish-pinned","cancel-on-deactivate"].includes(e.acceptedCommandDeactivationPolicy)||_("NATIVE_WORKFLOW_COMMAND_DEACTIVATION_POLICY_REQUIRED",`${t}/acceptedCommandDeactivationPolicy`);let n=N(e.nodes,`${t}/nodes`),o=Object.keys(n);(o.length===0||o.length>200)&&_("NATIVE_WORKFLOW_NODE_COUNT_INVALID",`${t}/nodes`);let r=k(e.startAt,`${t}/startAt`,128),i=Ls(e);i.length&&_(i[0],`${t}/authoring/peopleSources`);let s=ed(e);s.length&&_(s[0],`${t}/readability`);let a=ki(e);a.length&&_(a[0],`${t}/nodes`);let d=Li(e);d.length&&_(d[0],`${t}/nodes`);let c=Vn(e);c.length&&_(c[0],`${t}/nodes`);let l=cd(e);l.length&&_(l[0],`${t}/nodes`);let f=ud(e);f.length&&_(f[0],`${t}/rejectionNotification`);let p=Si(e);p.length&&_(p[0],`${t}/nodes`);let m=zo(e);m.length&&_(m[0],`${t}/taskPages`);let A=ko(e);A.length&&_(A[0],`${t}/nodes`);let I=Do(e);I.length&&_(I[0],`${t}/nodes`);let O=Po(e);O.length&&_(O[0],`${t}/nodes`);let b=vo(e);b.length&&_(b[0],`${t}/nodes`);let g=eo(e);g.length&&_(g[0],`${t}/nodes`),n[r]||_("NATIVE_WORKFLOW_START_NODE_MISSING",`${t}/startAt`);let y=new Map;for(let[w,S]of Object.entries(n)){let T=`${t}/nodes/${w}`,C=N(S,T);x(C.id,w,`${T}/id`),["approval","handle","condition","end","cc","action","correction","parallel","join"].includes(C.kind)||_("NATIVE_WORKFLOW_NODE_KIND_INVALID",`${T}/kind`);let v=[];if(C.kind==="approval"||C.kind==="handle"){k(C.title,`${T}/title`,255),Qo(C.binding,`${T}/binding`),["single","any","all","sequence"].includes(C.mode)||_("NATIVE_WORKFLOW_APPROVAL_MODE_INVALID",`${T}/mode`),C.kind==="handle"?v.push(k(C.next,`${T}/next`,128)):v.push(k(C.onApprove,`${T}/onApprove`,128),k(C.onReject,`${T}/onReject`,128));for(let P of V(C.returnTargets||[],`${T}/returnTargets`,200))n[P]||_("NATIVE_WORKFLOW_TARGET_MISSING",`${T}/returnTargets`);for(let P of V(C.allowedOperations||[],`${T}/allowedOperations`,20))Gu.has(P)||_("NATIVE_WORKFLOW_OPERATION_INVALID",`${T}/allowedOperations`)}else if(C.kind==="correction"){let P=_d(e);P.length&&_(P[0],T)}else if(C.kind==="action")v.push(k(C.next,`${T}/next`,128));else if(C.kind==="cc")k(C.title,`${T}/title`,255),Qo(C.binding,`${T}/binding`),v.push(k(C.next,`${T}/next`,128));else if(C.kind==="parallel"){k(C.title,`${T}/title`,255),v.push(k(C.join,`${T}/join`,128));for(let[P,H]of D(C.branches,`${T}/branches`,8).entries()){let ne=N(H,`${T}/branches/${P}`);ne.when!==void 0&&mn(ne.when,`${T}/branches/${P}/when`,0),v.push(k(ne.target,`${T}/branches/${P}/target`,128))}}else if(C.kind==="join")k(C.title,`${T}/title`,255),v.push(k(C.next,`${T}/next`,128));else if(C.kind==="condition"){let P=D(C.branches,`${T}/branches`,100);P.length===0&&_("NATIVE_WORKFLOW_BRANCH_REQUIRED",`${T}/branches`),P.forEach((H,ne)=>{let Z=N(H,`${T}/branches/${ne}`);mn(Z.when,`${T}/branches/${ne}/when`,0),v.push(k(Z.target,`${T}/branches/${ne}/target`,128))}),v.push(k(C.otherwise,`${T}/otherwise`,128))}else k(C.title,`${T}/title`,255),k(C.outcome,`${T}/outcome`,128);for(let P of v)n[P]||_("NATIVE_WORKFLOW_TARGET_MISSING",T);y.set(w,v)}let h=new Set,u=new Set,E=w=>{if(u.has(w)&&_("NATIVE_WORKFLOW_CYCLE_FORBIDDEN",`${t}/nodes/${w}`),!h.has(w)){h.add(w),u.add(w);for(let S of y.get(w)||[])E(S);u.delete(w)}};E(r);for(let w of[...h]){let S=n[w];if(S?.kind==="approval"||S?.kind==="handle")for(let T of ot(S))n[T]?.kind==="correction"&&h.add(T)}h.size!==o.length&&_("NATIVE_WORKFLOW_NODE_UNREACHABLE",`${t}/nodes`)}function mn(e,t,n){n>20&&_("NATIVE_WORKFLOW_EXPRESSION_DEPTH_EXCEEDED",t);let o=N(e,t),r=k(o.op,`${t}/op`,16);if(r!=="literal"){if(r==="path"){let i=k(o.path,`${t}/path`,255);(!/^[A-Za-z][A-Za-z0-9_.-]{0,254}$/.test(i)||i.split(".").some(s=>["__proto__","constructor","prototype"].includes(s)))&&_("NATIVE_WORKFLOW_EXPRESSION_PATH_INVALID",`${t}/path`);return}if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(r)){mn(o.left,`${t}/left`,n+1),mn(o.right,`${t}/right`,n+1);return}if(["and","or"].includes(r)){let i=D(o.values,`${t}/values`,100);i.length===0&&_("NATIVE_WORKFLOW_EXPRESSION_EMPTY",`${t}/values`),i.forEach((s,a)=>mn(s,`${t}/values/${a}`,n+1));return}if(["not","exists"].includes(r)){mn(o.value,`${t}/value`,n+1);return}_("NATIVE_WORKFLOW_EXPRESSION_OPERATOR_INVALID",`${t}/op`)}}function Bf(e,t){x(e.schemaVersion,"openxiangda.workflow-binding/v2",`${t}/schemaVersion`),or(e.workflowCode,`${t}/workflowCode`);let n=N(e.bindings,`${t}/bindings`);Object.keys(n).length>200&&_("NATIVE_WORKFLOW_BINDING_LIMIT_EXCEEDED",`${t}/bindings`);for(let[o,r]of Object.entries(n)){Qo(o,`${t}/bindings/${o}`);let i=N(r,`${t}/bindings/${o}`);if(i.provider==="conditional"){let l=De(i);l.length&&_(l[0],`${t}/bindings/${o}`);continue}let s=Ht(i);s.length&&_(s[0],`${t}/bindings/${o}`);let a=Xn(i);a.length&&_(a[0],`${t}/bindings/${o}/selectedInputPath`);let d=qt(i);d.length&&_(d[0],`${t}/bindings/${o}/roleCodes`);let c=k(i.provider,`${t}/bindings/${o}/provider`,64);if(["fixed_users","initiator","input_users","form_field_users","department_supervisor","supervisor_chain","app_role","app_role_in_scope","business_relation","previous_node_actor","initiator_select","application_provider"].includes(c)||_("NATIVE_WORKFLOW_BINDING_PROVIDER_INVALID",`${t}/bindings/${o}/provider`),c==="fixed_users"&&(Array.isArray(i.users)||_("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${t}/bindings/${o}/users`),D(i.users,`${t}/bindings/${o}/users`,200)),["input_users","form_field_users"].includes(c)&&k(i.inputPath,`${t}/bindings/${o}/inputPath`,255),["app_role","app_role_in_scope","initiator_select"].includes(c)&&i.roleCodes===void 0&&F(i.roleCode,`${t}/bindings/${o}/roleCode`),c==="department_supervisor"&&k(i.departmentIdFrom,`${t}/bindings/${o}/departmentIdFrom`,255),c==="application_provider"&&F(i.providerCode,`${t}/bindings/${o}/providerCode`),i.routing!==void 0){let l=Yt(i.routing);l.length&&_(l[0],`${t}/bindings/${o}/routing`)}}}function Kf(e,t,n){let o=Xt(e,t);o.length&&_(o[0],n);let r=At(e,t);r.length&&_(r[0],n),x(t.workflowCode,e.code,`${n}/workflowCode`);let i=N(t.bindings,`${n}/bindings`);for(let[c,l]of Object.entries(i))l.provider==="fixed_users"&&!l.users.length&&!ad(e,c)&&_("NATIVE_WORKFLOW_BINDING_USERS_REQUIRED",`${n}/bindings/${c}/users`);let s=Li(e,t);s.length&&_(s[0],n);let a=Si(e,t);a.length&&_(a[0],n);let d=eo(e,t);d.length&&_(d[0],n);for(let[c,l]of Object.entries(N(e.nodes,`${n}/nodes`))){let f=N(l,`${n}/nodes/${c}`);["approval","handle","cc"].includes(f.kind)&&!i[f.binding]&&_("NATIVE_WORKFLOW_BINDING_REFERENCE_MISSING",`${n}/nodes/${c}/binding`)}}function qf(e,t,n){let o=N(t.routeManifest,"/contracts/routeManifest"),r=N(e.routeManifest,"/contracts/routeManifest"),i=new Map;for(let l of D(n.data?.resources,"/config/data/resources",q.resources)){let f=N(l,"/config/data/resources");i.set(String(f.code||""),f)}let s=new Set(D(r.routes,"/contracts/routeManifest/routes",q.routes).map(l=>String(N(l,"/contracts/routeManifest/routes").code||""))),a=[];for(let l of D(o.routes,"/contracts/routeManifest/routes",q.routes)){let f=N(l,"/contracts/routeManifest/routes"),p=String(f.kind||"");if(p!=="resource-records"&&p!=="resource-submit")continue;let m=String(f.resourceCode||""),A=i.get(m);A||_("NATIVE_ROUTE_MANIFEST_RESOURCE_UNKNOWN","/contracts/routeManifest/routes");let O=`user.${m}.${p==="resource-records"?"records":"submit"}`;x(String(f.code||""),O,"/contracts/routeManifest/routes/code");let b=p==="resource-records"?"read":"create",g=String(N(A.capabilities,"/config/data/resources/capabilities")[b]||"");for(let y of["desktop","mobile"]){let h=N(f[y],`/contracts/routeManifest/routes/${y}`),u=y==="mobile"?"/m/my/":"/my/",E=p==="resource-records"?`${u}${m}`:`${u}${m}/submit`;x(String(h.path||""),E,`/contracts/routeManifest/routes/${y}/path`),x(String(h.capability||""),g,`/contracts/routeManifest/routes/${y}/capability`),x(String(h.routeCode||""),`${O}.${y}`,`/contracts/routeManifest/routes/${y}/routeCode`)}(s.has(O)||a.some(y=>String(y.code)===O))&&_("NATIVE_ROUTE_MANIFEST_DUPLICATE","/contracts/routeManifest/routes/code"),a.push(f)}if(!a.length)return;r.routes=D([...r.routes,...a],"/contracts/routeManifest/routes",1e3).sort((l,f)=>Pe(String(N(l,"x").code||""),String(N(f,"x").code||"")));let d=String(N(o.rootEntry,"x").code||"");if(a.find(l=>String(l.code)===d&&l.kind==="resource-records")){let l=N(o.rootEntry,"x");r.rootEntry={code:d,desktop:String(l.desktop||""),mobile:String(l.mobile||"")}}r.digest=ee({schemaVersion:r.schemaVersion,appCode:r.appCode,devicePolicy:r.devicePolicy,rootEntry:r.rootEntry,authentication:r.authentication,routes:r.routes})}function Ut(e,t,n){let o=N(e,t);R(o,["schemaVersion","appCode","code","name","schema","surface","invariants","decimalReservationLifecycle","uniqueKeys","workflowHistory","recordPrint","recordComments","recordDeletion","capabilities","dataPolicyCode","organization","fieldPolicies"],t,!0),x(o.schemaVersion,"openxiangda.data-resource/v2",`${t}/schemaVersion`),x(o.appCode,n,`${t}/appCode`);let r=Q(o.code,`${t}/code`),i=k(o.name,`${t}/name`,255),s=N(o.schema,`${t}/schema`);R(s,["fields","ownedRowLimit"],`${t}/schema`,!0),s.ownedRowLimit!==void 0&&!On(s.ownedRowLimit)&&_("NATIVE_DATA_OWNED_ROW_LIMIT_INVALID",`${t}/schema/ownedRowLimit`);let a,d,c,l;try{c=si(o.decimalReservationLifecycle,`${t}/decimalReservationLifecycle`),a=bn(s.fields,`${t}/schema/fields`),l=Ka(o.uniqueKeys,a,`${t}/uniqueKeys`),d=Zs(o.invariants,a,`${t}/invariants`),ti(o.surface,a,`${t}/surface`)}catch(A){throw(A instanceof We||A instanceof $t||A instanceof rn||A instanceof vn)&&_(A.code,A.pointer),A}if(o.recordComments!==void 0){let A=N(o.recordComments,`${t}/recordComments`);R(A,["read","create"],`${t}/recordComments`);for(let I of["read","create"]){let O=A[I];(!Array.isArray(O)||O.length>20||O.some(b=>typeof b!="string"||!b.trim())||new Set(O).size!==O.length)&&_("NATIVE_RECORD_COMMENTS_POLICY_INVALID",`${t}/recordComments/${I}`)}}if(o.recordDeletion!==void 0){let A=N(o.recordDeletion,`${t}/recordDeletion`);R(A,["delete"],`${t}/recordDeletion`);let I=A.delete;(!Array.isArray(I)||I.length>20||I.some(O=>typeof O!="string"||!O.trim())||new Set(I).size!==I.length)&&_("NATIVE_RECORD_DELETION_DELETE_INVALID",`${t}/recordDeletion/delete`)}if(o.recordPrint!==void 0){let A=N(o.recordPrint,`${t}/recordPrint`);R(A,["read"],`${t}/recordPrint`);let I=A.read;(!Array.isArray(I)||I.length>20||I.some(O=>typeof O!="string"||!O.trim())||new Set(I).size!==I.length)&&_("NATIVE_RECORD_PRINT_READ_INVALID",`${t}/recordPrint/read`)}if(o.workflowHistory!==void 0){let A=N(o.workflowHistory,`${t}/workflowHistory`);R(A,["read"],`${t}/workflowHistory`);let I=A.read;(!Array.isArray(I)||I.length>20||I.some(O=>typeof O!="string"||!O.trim())||new Set(I).size!==I.length)&&_("NATIVE_WORKFLOW_HISTORY_READ_INVALID",`${t}/workflowHistory/read`)}let f=new Set(a.map(A=>A.code)),p=N(o.capabilities,`${t}/capabilities`);R(p,["read","create","update","delete"],`${t}/capabilities`);let m=N(o.fieldPolicies,`${t}/fieldPolicies`);for(let[A,I]of Object.entries(m)){!f.has(A)&&!Vt(A)&&_("NATIVE_DATA_FIELD_POLICY_FIELD_MISSING",`${t}/fieldPolicies/${A}`);let O=`${t}/fieldPolicies/${A}`,b=N(I,O);Vt(A)&&(R(b,["read"],O,!0),(!Array.isArray(b.read)||b.read.length>20||b.read.some(g=>typeof g!="string"||!g.trim())||new Set(b.read).size!==b.read.length)&&_("NATIVE_DATA_AUDIT_READ_POLICY_INVALID",`${O}/read`)),R(b,["read","create","update","mask"],O,!0),b.mask!==void 0&&!["omit","null"].includes(b.mask)&&_("NATIVE_DATA_FIELD_POLICY_MASK_INVALID",`${O}/mask`)}return{...o,code:r,name:i,schema:{fields:a,...s.ownedRowLimit!==void 0?{ownedRowLimit:s.ownedRowLimit}:{}},...o.invariants===void 0?{}:{invariants:d},...c?{decimalReservationLifecycle:c}:{},...l!==void 0?{uniqueKeys:l}:{},capabilities:p,fieldPolicies:m}}function sc(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,n])=>({code:t,kind:"platform",name:n,source:"platform"}))]}function Bd(e,t,n,o){let r=e.toString("utf8"),i;try{i=JSON.parse(r)}catch{_(n,t)}let s=N(i,t);return re(s)!==r&&_(o,t),s}function Yo(e,t,n){let o=0,r=(i,s,a)=>{if(o+=1,o>n&&_("NATIVE_ARTIFACT_NODE_LIMIT_EXCEEDED",s),a>Yu&&_("NATIVE_ARTIFACT_DEPTH_LIMIT_EXCEEDED",s),typeof i=="string"){Buffer.byteLength(i)>qi&&_("NATIVE_ARTIFACT_STRING_LIMIT_EXCEEDED",s);return}if(Array.isArray(i)){i.forEach((d,c)=>r(d,`${s}/${c}`,a+1));return}if(!(!i||typeof i!="object"))for(let[d,c]of Object.entries(i))["__proto__","prototype","constructor"].includes(d)&&_("NATIVE_ARTIFACT_DANGEROUS_KEY",`${s}/${d}`),zf(d)&&_("NATIVE_ARTIFACT_RUNTIME_FIELD_FORBIDDEN",`${s}/${d}`),r(c,`${s}/${d}`,a+1)};r(e,t,0)}function zf(e){return["environmentKey","environmentId","secretValue","ciphertext","oauthClient","oauthClientId","oauthClientSecret","signingSecret","kubernetesNamespace","nodePort","productionUrl"].includes(e)}function pn(e){return{value:e,digest:ee(e)}}function Kd(e,t,n,o){typeof e!="string"&&!Buffer.isBuffer(e)&&!(e instanceof Uint8Array)&&_("NATIVE_ARTIFACT_BYTES_REQUIRED",n);let r=Buffer.isBuffer(e)?e:Buffer.from(e);return r.byteLength===0&&_("NATIVE_ARTIFACT_EMPTY",n),r.byteLength>t&&_(o,n),r}function qd(e,t,n,o){let r=er.createHash("sha256").update(e).digest("hex");er.timingSafeEqual(Buffer.from(r),Buffer.from(t))||_(o,n)}function N(e,t){return(!e||typeof e!="object"||Array.isArray(e))&&_("NATIVE_OBJECT_REQUIRED",t),e}function D(e,t,n){return Array.isArray(e)||_("NATIVE_ARRAY_REQUIRED",t),e.length>n&&_("NATIVE_ARRAY_LIMIT_EXCEEDED",t),e}function V(e,t,n){let o=D(e,t,n).map((r,i)=>k(r,`${t}/${i}`,255));return new Set(o).size!==o.length&&_("NATIVE_ARRAY_DUPLICATE",t),o}function k(e,t,n){return(typeof e!="string"||e.length===0||e.length>n)&&_("NATIVE_STRING_INVALID",t),e}function Qi(e,t,n){return(typeof e!="string"||e.length>n)&&_("NATIVE_STRING_INVALID",t),e}function F(e,t){let n=k(e,t,128);return Pu.test(n)||_("NATIVE_CODE_INVALID",t),n}function Q(e,t){let n=k(e,t,64);return Fu.test(n)||_("NATIVE_RESOURCE_CODE_INVALID",t),n}function J(e,t){let n=k(e,t,63);return Vu.test(n)||_("NATIVE_FIELD_CODE_INVALID",t),n}function or(e,t){let n=k(e,t,128);return ju.test(n)||_("NATIVE_WORKFLOW_CODE_INVALID",t),n}function Qo(e,t){let n=k(e,t,128);return Uu.test(n)||_("NATIVE_WORKFLOW_BINDING_CODE_INVALID",t),n}function ve(e,t,n){let o=k(e,t,255);return vu.test(o)||_("NATIVE_CAPABILITY_CODE_INVALID",t),!o.startsWith(`app:${n}:`)&&!sc(n).some(r=>r.code===o)&&_("NATIVE_CAPABILITY_APP_MISMATCH",t),o}function Je(e,t){let n=k(e,t,2048);return(!n.startsWith("/")||n.startsWith("//")||n.includes("..")||n.includes("?")||n.includes("#"))&&_("NATIVE_ABSOLUTE_PATH_INVALID",t),n}function gn(e,t){return(!Number.isInteger(e)||Number(e)<1)&&_("NATIVE_POSITIVE_INTEGER_REQUIRED",t),Number(e)}function Ae(e,t,n,o){return(!Number.isInteger(e)||Number(e)<n||Number(e)>o)&&_("NATIVE_INTEGER_OUT_OF_RANGE",t),Number(e)}function _n(e,t){return typeof e!="boolean"&&_("NATIVE_BOOLEAN_REQUIRED",t),e}function Hi(e,t){let n=k(e,t,64).toLowerCase();return ku.test(n)||_("NATIVE_DIGEST_INVALID",t),n}function x(e,t,n){e!==t&&_("NATIVE_VALUE_MISMATCH",n)}function R(e,t,n,o=!1){let r=new Set([...t,...Array.isArray(o)?o:[]]);for(let i of Object.keys(e))r.has(i)||_("NATIVE_PROPERTY_UNKNOWN",`${n}/${i}`);if(o!==!0)for(let i of t)Object.prototype.hasOwnProperty.call(e,i)||_("NATIVE_PROPERTY_REQUIRED",`${n}/${i}`)}function ue(e,t){return[...e].sort((n,o)=>Pe(t(n),t(o)))}function K(e){return[...new Set(e)].sort(Pe)}function zd(e){return[...new Set(e)].sort((t,n)=>t-n)}function Pe(e,t){return e===t?0:e<t?-1:1}function ac(e){return!e||typeof e!="object"||Object.isFrozen(e)||(Object.freeze(e),Object.values(e).forEach(t=>ac(t))),e}function Yi(e,t,n){if(Ki(e,t))return n;if(Array.isArray(e)&&Array.isArray(t)){let o=Math.max(e.length,t.length);for(let r=0;r<o;r+=1)if(!Ki(e[r],t[r]))return Yi(e[r],t[r],`${n}/${r}`)}if(e&&t&&typeof e=="object"&&typeof t=="object"&&!Array.isArray(e)&&!Array.isArray(t)){let o=K([...Object.keys(e),...Object.keys(t)]);for(let r of o){let i=e[r],s=t[r];if(!Ki(i,s))return Yi(i,s,`${n}/${r}`)}}return n}function Ki(e,t){return e===void 0||t===void 0?e===t:re(e)===re(t)}function _(e,t,n={}){throw new Gi(e,t,n)}var kE="openxiangda.workflow-step-data-command/v1",Gf="openxiangda.workflow-step-data-resolution/v1";function LE(e,t,n=!1){let o=a=>!!a&&typeof a=="object"&&!Array.isArray(a),r=a=>typeof a=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(a),i=()=>{throw new Error("WORKFLOW_STEP_DATA_RESPONSE_INVALID")};if(!o(e)||e.schemaVersion!==Gf||e.executionId!==t||Object.keys(e).some(a=>!["schemaVersion","executionId","outcome","transaction"].includes(a)))return i();if(e.outcome==="not_observed"&&!Object.hasOwn(e,"transaction")&&!n)return e;let s=e.transaction;if(e.outcome!=="committed"||!o(s)||s.schemaVersion!=="openxiangda.data-transaction-result/v2"||s.idempotencyKey!==`workflow-step:${t}`||typeof s.replayed!="boolean"||!Array.isArray(s.items)||s.items.length<1||s.items.length>Ks||s.evaluatedAt!==void 0&&(typeof s.evaluatedAt!="string"||!Number.isFinite(Date.parse(s.evaluatedAt))))return i();for(let[a,d]of s.items.entries()){if(!o(d)||d.index!==a)return i();if(d.operation==="emitEvent"){if(typeof d.eventType!="string"||!d.eventType||!r(d.eventId))return i()}else if(!["create","update","delete","increment"].includes(d.operation)||typeof d.resourceCode!="string"||!d.resourceCode||!r(d.id)||!Number.isSafeInteger(d.revision)||d.revision<1)return i()}return e}var PE=50,$E=131072,es=class extends Error{constructor(n){super("OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID");this.pointer=n}pointer;code="OPENXIANGDA_NATIVE_AUTHZ_BATCH_INPUT_INVALID";status=400};function FE(e){let t=f=>{throw new es(f)},n=(f,p)=>((!f||typeof f!="object"||Array.isArray(f))&&t(p),f),o=(f,p,m)=>{for(let A of Object.keys(f))p.includes(A)||t(`${m}/${A}`)},r=(f,p,m)=>((typeof f!="string"||!f.trim()||f.length>p)&&t(m),f),i=(f,p)=>{let m=r(f,36,p);return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(m)||t(p),m.toLowerCase()},s=n(e,""),a;try{a=new TextEncoder().encode(JSON.stringify(s)).byteLength}catch{t("")}a>131072&&t(""),o(s,["schemaVersion","environmentKey","items"],""),s.schemaVersion!=="openxiangda.native-role-membership-batch-request/v2"&&t("/schemaVersion"),s.environmentKey!==void 0&&!["preproduction","production"].includes(String(s.environmentKey))&&t("/environmentKey"),(!Array.isArray(s.items)||s.items.length<1||s.items.length>50)&&t("/items");let d=new Set,c=new Set,l;for(let[f,p]of s.items.entries()){let m=`/items/${f}`,A=n(p,m);["create","update","revoke"].includes(String(A.operation))||t(`${m}/operation`),l??=A.operation,l!==A.operation&&t(`${m}/operation`),o(A,["operation","operationId","reason",...l==="create"?["userId","roleCode","organizationId"]:["membershipId","expectedRevision"],...l!=="revoke"?["scopeGrants","validFrom","validTo"]:[]],m);let I=i(A.operationId,`${m}/operationId`);d.has(I)&&t(`${m}/operationId`),d.add(I),r(A.reason,1e3,`${m}/reason`);let O;if(l==="create"){let b=r(A.userId,255,`${m}/userId`),g=r(A.roleCode,128,`${m}/roleCode`);/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/.test(g)||t(`${m}/roleCode`);let y=A.organizationId===void 0?null:i(A.organizationId,`${m}/organizationId`);O=JSON.stringify([b,g,y])}else O=i(A.membershipId,`${m}/membershipId`),(!Number.isSafeInteger(A.expectedRevision)||Number(A.expectedRevision)<1)&&t(`${m}/expectedRevision`);c.has(O)&&t(m),c.add(O),A.scopeGrants!==void 0&&(!Array.isArray(A.scopeGrants)||A.scopeGrants.length>100)&&t(`${m}/scopeGrants`);for(let b of["validFrom","validTo"])A[b]!==void 0&&A[b]!==null&&r(A[b],64,`${m}/${b}`)}}var uc="openxiangda.workflow-delegation-administration/v2",fc="openxiangda.workflow-delegation-mutation/v2",dc="openxiangda.workflow-delegation-preview/v2";var Kn={type:"string",format:"uuid",pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$"},$e={type:"string",minLength:1,maxLength:255},Mt={type:"string",format:"date-time"},An={type:"integer",minimum:1},Jf={anyOf:[Mt,{type:"null"}]},ts={anyOf:[$e,{type:"null"}]},pc={anyOf:[{type:"string",pattern:"^[A-Za-z0-9._:-]{1,128}$"},{type:"null"}]},rr={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}$"},mc={const:"future-assignments-only"},ns={schemaVersion:{const:uc},id:Kn,appCode:$e,environmentKey:$e,workflowCode:ts,nodeId:pc,delegatorUserId:$e,delegateUserId:$e,delegatorRoleSubjectKey:rr,delegateRoleSubjectKey:rr,validFrom:Mt,validTo:Mt,status:{enum:["active","revoked","expired"]},reason:{type:"string",minLength:1,maxLength:4e3},createdBy:$e,createdAt:Mt,revokedAt:Jf,revision:An,roleCode:$e,roleName:$e,delegatorDisplayName:$e,delegateDisplayName:$e,delegatorRoleSubjectRevision:An,delegateRoleSubjectRevision:An,effectiveState:{enum:["active","scheduled","expired","revoked","ineligible"]},evaluatedAt:Mt,issues:{type:"array",maxItems:20,uniqueItems:!0,items:$e},canRevoke:{type:"boolean"},revokedBy:ts,revokeReason:{type:["string","null"],maxLength:4e3},taskPolicy:mc},os={type:"object",additionalProperties:!1,required:Object.keys(ns).filter(e=>e!=="nodeId"),properties:ns},WE={$id:uc,...os},gc={schemaVersion:{const:fc},operationId:Kn,environmentKey:{enum:["preproduction","production"]},reason:{type:"string",minLength:1,maxLength:2e3,pattern:"\\S"}},cc={...gc,operation:{const:"create"},workflowCode:ts,nodeId:pc,delegatorRoleSubjectKey:rr,expectedDelegatorRevision:An,delegateUserId:$e,delegateRoleSubjectKey:rr,expectedDelegateRevision:An,validFrom:Mt,validTo:Mt},lc={...gc,operation:{const:"revoke"},delegationId:Kn,expectedRevision:An},Hf={$id:fc,type:"object",oneOf:[{type:"object",additionalProperties:!1,required:Object.keys(cc).filter(e=>e!=="nodeId"),properties:cc,if:{required:["nodeId"],properties:{nodeId:{type:"string"}}},then:{properties:{workflowCode:$e}}},{type:"object",additionalProperties:!1,required:Object.keys(lc),properties:lc}]},Yf={type:"string",pattern:"^[0-9a-f]{64}$"},xE={$id:dc,type:"object",additionalProperties:!1,required:["schemaVersion","operationId","operation","requestDigest","before","after","taskPolicy"],properties:{schemaVersion:{const:dc},operationId:Kn,operation:{enum:["create","revoke"]},requestDigest:Yf,before:{anyOf:[os,{type:"null"}]},after:{...os,properties:{...ns,id:{anyOf:[Kn,{type:"null"}]}}},taskPolicy:mc}};function ME(e){return e===void 0?"":`
10
+ ${ee(e)}`}function BE(e,t){let n=e.handlers.find(o=>o.code===t);return ee(n?.workflowStep?n:e)}var qE="openxiangda.data-business-command/v1",Xf="openxiangda.data-business-command-resolution/v1",zE=65536;function GE(e){let t=0,n=0,o=new Set,r=new TextEncoder,i=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_INTENT_INVALID")},s=d=>(n+=r.encode(d).byteLength,n>65536&&i(),d),a=(d,c)=>{if(++t>1e4||c>32)return i();if(d===null||typeof d=="string"||typeof d=="boolean")return s(JSON.stringify(d));if(typeof d=="number")return Number.isFinite(d)?s(JSON.stringify(d)):i();if(!d||typeof d!="object"||o.has(d)||Object.getOwnPropertySymbols(d).length)return i();o.add(d);let l;if(Array.isArray(d))return Object.keys(d).length!==d.length?i():(l=s("[")+d.map((p,m)=>(m?s(","):"")+a(p,c+1)).join("")+s("]"),o.delete(d),l);let f=Object.getPrototypeOf(d);return f!==Object.prototype&&f!==null?i():(l=s("{")+Object.keys(d).sort().map((p,m)=>(m?s(","):"")+s(JSON.stringify(p))+s(":")+a(d[p],c+1)).join("")+s("}"),o.delete(d),l)};return!e||typeof e!="object"||Array.isArray(e)?i():a(e,0)}function JE(e,t,n=!1){let o=e,r=()=>{throw new Error("OPENXIANGDA_DATA_COMMAND_RESPONSE_INVALID")};if(!o||typeof o!="object"||o.schemaVersion!==Xf)return r();for(let d of["appCode","environmentKey","operationCode","idempotencyKey","intentDigest"])if(o[d]!==t[d])return r();if(typeof o.observedAt!="string"||!Number.isFinite(Date.parse(o.observedAt)))return r();if(o.outcome==="not_observed"&&o.receipt===null&&!n)return o;if(o.outcome!=="committed"||!o.receipt)return r();let i=o.receipt,s=d=>typeof d=="string"&&/^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(d);if(!s(i.id)||!s(i.appVersionId)||!Number.isSafeInteger(i.environmentHeadRevision)||i.environmentHeadRevision<1||typeof i.completedAt!="string"||!Number.isFinite(Date.parse(i.completedAt)))return r();let a=i.transaction;if(!a||a.schemaVersion!=="openxiangda.data-transaction-result/v2"||a.idempotencyKey!==t.idempotencyKey||typeof a.replayed!="boolean"||!Array.isArray(a.items)||!a.items.length||a.items.length>1e3)return r();for(let[d,c]of a.items.entries()){if(!c||c.index!==d)return r();if(c.operation==="emitEvent"){if(!s(c.eventId)||typeof c.eventType!="string"||!c.eventType)return r()}else if(!["create","update","delete","increment"].includes(c.operation)||!s(c.id)||typeof c.resourceCode!="string"||!c.resourceCode||!Number.isSafeInteger(c.revision)||c.revision<1)return r()}return o}var _c=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,ir=e=>!!e&&typeof e=="object"&&!Array.isArray(e),qn=(e,t)=>typeof e=="string"&&e.length<=t&&e.trim().length>0&&e===e.trim(),rs=(e,t,n=[])=>t.every(o=>Object.hasOwn(e,o))&&Object.keys(e).every(o=>[...t,...n].includes(o));function YE(e){if(!ir(e)||!rs(e,["kind","errorCode","anyOf"],["allowAppSuperAdmin"])||e.kind!=="actor-authority"||!qn(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(n=>{if(!ir(n)||!rs(n,["roleCode"],["scope"])||!qn(n.roleCode,100)||!_c.test(n.roleCode))return!1;if(Object.hasOwn(n,"scope")){let i=n.scope;if(!ir(i)||!rs(i,["dimensionCode","value","operation"])||!qn(i.dimensionCode,100)||!_c.test(i.dimensionCode)||!qn(i.value,255)||!qn(i.operation,64)||!/^[A-Za-z0-9*][A-Za-z0-9*._:-]*$/.test(i.operation))return!1}let o=n.scope,r=JSON.stringify([n.roleCode,o?.dimensionCode,o?.value,o?.operation]);return t.has(r)?!1:(t.add(r),!0)})}function XE(e,t,n){if(t.roleSource!=="package"||t.roleCode!==e.roleCode||!n||!t.capabilityCodes.includes(n))return!1;if(!e.scope)return!0;let o;try{o=JSON.parse(t.scopeGrantsJson)}catch{return!1}if(!Array.isArray(o))return!1;let r=e.scope;return o.some(i=>ir(i)&&i.dimensionCode===r.dimensionCode&&Array.isArray(i.values)&&i.values.includes(r.value)&&(i.operations===void 0||i.operations===null||Array.isArray(i.operations)&&(!i.operations.length||i.operations.includes("*")||i.operations.includes(r.operation))))}var sr=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_]{0,62}$/.test(e),Ac=new Set(["eq","neq","gt","gte","lt","lte"]);function Ec(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Object.keys(t);return t.kind==="value"?n.some(o=>!["kind","field","operator","value","path"].includes(o))||!sr(t.field)||typeof t.operator!="string"||!Wo.has(t.operator)||Object.hasOwn(t,"path")&&(typeof t.path!="string"||!t.path||t.path.length>128)?!1:Ha.has(t.operator)?!Object.hasOwn(t,"value"):Object.hasOwn(t,"value"):t.kind==="field"?n.length===4&&["kind","leftField","operator","rightField"].every(o=>n.includes(o))&&sr(t.leftField)&&sr(t.rightField)&&Ac.has(String(t.operator)):t.kind==="database-now"?n.length===3&&["kind","field","operator"].every(o=>n.includes(o))&&sr(t.field)&&Ac.has(String(t.operator)):!1}var Zf=500,Qf=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,is=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function nI(e){if(!is(e)||e.kind!=="record-set-match"||Object.keys(e).some(n=>!["kind","resourceCode","errorCode","records","where","assertions"].includes(n))||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>Zf||Object.hasOwn(e,"where")&&!is(e.where)||Object.hasOwn(e,"assertions")&&(!Array.isArray(e.assertions)||!e.assertions.length||e.assertions.length>20||!e.assertions.every(Ec)))return!1;let t=new Set;return e.records.every(n=>{if(!is(n)||Object.keys(n).length!==2||typeof n.id!="string"||!Qf.test(n.id)||!Number.isSafeInteger(n.expectedRevision)||Number(n.expectedRevision)<1)return!1;let o=n.id.toLowerCase();return t.has(o)?!1:(t.add(o),!0)})}var ep="openxiangda.development-configuration/v2",Ic="openxiangda.development-configuration-manifest/v1",sI="application.development-configuration",aI="/openxiangda-api/v2/applications/{appCode}/dev-sessions/configuration",ss=class extends Error{constructor(n,o){super(n);this.code=n;this.pointer=o;this.data={pointer:o}}code;pointer;status=400;data};function Tt(e){throw new ss("OPENXIANGDA_CONNECTED_DEV_CONFIGURATION_INVALID",e)}function tp(e){(!e||typeof e!="object"||Array.isArray(e))&&Tt("/packageManifest");let t=e,n=["schemaVersion","appCode","version","configDigest","contractDigest","source","toolchain","artifacts"];(Object.keys(t).some(r=>!n.includes(r))||t.schemaVersion!==Ic||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}`)&&Tt("/packageManifest"),(!t.source||typeof t.source!="object"||Array.isArray(t.source)||Object.keys(t.source).some(r=>!["repository","commit","dirty"].includes(r))||![null,"string"].includes(t.source.repository===null?null:typeof t.source.repository)||t.source.repository!==null&&(t.source.repository.length>1024||/[\r\n\0]/.test(t.source.repository))||t.source.commit!==null&&(typeof t.source.commit!="string"||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(t.source.commit))||typeof t.source.dirty!="boolean")&&Tt("/packageManifest/source"),(!t.toolchain||Object.keys(t.toolchain).some(r=>!["version","contractVersion"].includes(r))||typeof t.toolchain.version!="string"||!/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/.test(t.toolchain.version)||t.toolchain.contractVersion!==xi)&&Tt("/packageManifest/toolchain");let o=[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}];return re(t.artifacts)!==re(o)&&Tt("/packageManifest/artifacts"),t}function dI(e,t){return tp({schemaVersion:Ic,appCode:e,version:`development-${t.configDigest}`,configDigest:t.configDigest,contractDigest:t.contractDigest,source:{...t.source},toolchain:{version:t.toolchainVersion,contractVersion:xi},artifacts:[{kind:"config",digest:t.configDigest,mediaType:"application/json"},{kind:"contracts",digest:t.contractDigest,mediaType:"application/json"}]})}function cI(e,t,n){return(!Number.isSafeInteger(t)||t<1)&&Tt("/expectedHeadRevision"),`development:${ee({manifest:e,expectedHeadRevision:t,...n?{actorUserId:n}:{}})}`}function lI(e,t,n){(!e||typeof e!="object"||Array.isArray(e))&&Tt("/result");let o=e,r=["schemaVersion","appCode","environmentKey","environmentId","appVersionId","configurationRunId","headRevision","publishedAppVersionId","selection","configDigest","contractDigest","reused","runtimeArtifactsDeployed","backendEventsAvailable"],i=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i;return(Object.keys(o).some(s=>!r.includes(s))||o.schemaVersion!==ep||o.appCode!==t||o.environmentKey!=="preproduction"||o.configDigest!==n.configDigest||o.contractDigest!==n.contractDigest||!i.test(o.environmentId)||!i.test(o.appVersionId)||!i.test(o.publishedAppVersionId)||o.appVersionId===o.publishedAppVersionId||o.selection!=="session"||!i.test(o.configurationRunId)||typeof o.reused!="boolean"||!Number.isSafeInteger(o.headRevision)||o.headRevision<1||o.headRevision!==n.expectedHeadRevision||o.runtimeArtifactsDeployed!==!1||o.backendEventsAvailable!==!1)&&Tt("/result"),o}var fI="application.development-backend-events",pI="openxiangda.development-backend/v1",mI="application.development-backend-invocations",np="openxiangda.development-backend-invocation/v1",gI=262144,_I=1048576,AI=131072,EI=131072,II=8,yI=45,OI=/^\/__platform\/events\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function bI(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 hI(e){return`connected-development:${e}`}function op(e){if(typeof e!="string"||e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e))return null;let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=e.endsWith("==")?2:e.endsWith("=")?1:0;return n&&t.indexOf(e[e.length-n-1])%(n===2?16:4)!==0?null:e.length/4*3-n}function rp(e,t,n){if(!["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"].includes(e)||n.method!==e||typeof t!="string"||t.length>2048||!t.startsWith("/")||t.startsWith("//")||t.startsWith("/__platform")||/[\\?#\s\u0000-\u001f\u007f]/.test(t))return!1;let o=t.split("/"),r=String(n.path||"").split("/");return o.length!==r.length?!1:o.every((i,s)=>{if(s===0)return r[s]==="";let a;try{a=decodeURIComponent(i)}catch{return!1}return!a||[".",".."].includes(a)||/[\/\\\s\u0000-\u001f\u007f]/.test(a)?!1:/^:[A-Za-z][A-Za-z0-9_]*$/.test(r[s]||"")||i===r[s]})}var ip=/^(?:authorization|content-type|content-length|accept|if-match|idempotency-key|x-request-id|x-openxiangda-(?:gateway-assertion|forwarded-by|perspective|csrf-token|mcp-bus-token|dev-selection))$/i,sp=/^(?:content-type|content-disposition|cache-control|etag|last-modified|retry-after)$/i;function ap(e,t=!1){if(!e||typeof e!="object"||Array.isArray(e))return!1;let n=Object.entries(e),o=n.map(([r])=>r.toLowerCase());return n.length<=24&&new Set(o).size===o.length&&n.every(([r,i])=>(t?sp:ip).test(r)&&typeof i=="string"&&i.length<=8192&&!/[\r\n\u0000]/.test(i))}function NI(e){let t=op(e.body);return e.schemaVersion===np&&!!e.operation&&typeof e.operation.code=="string"&&e.operation.code.length<=128&&e.operation.code.length>0&&rp(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&&ap(e.headers)&&Object.entries(e.headers).some(([n,o])=>n.toLowerCase()==="authorization"&&/^Bearer \S+$/.test(o))&&Object.entries(e.headers).some(([n,o])=>n.toLowerCase()==="x-openxiangda-gateway-assertion"&&!!o)}var RI=Object.freeze({version:"rich-text-html/1",maxBytes:1048576,maxNodes:25e3,maxDepth:128,maxImages:20,imageMaxBytes:10485760,maxVideos:4,videoMaxBytes:104857600,imageTypes:["image/png","image/jpeg","image/webp","image/gif"],videoTypes:["video/mp4","video/webm"],fonts:["Arial","Verdana","Tahoma","Times New Roman","Courier New","\u5B8B\u4F53","\u5FAE\u8F6F\u96C5\u9ED1","SimSun","Microsoft YaHei","sans-serif","serif","monospace"]});function dp(e,t,n){let o=e.nodes,r=o[t],i=o[n];if(!r||!["approval","handle"].includes(r.kind)||!i||!["approval","handle","correction"].includes(i.kind)||t===n)return{allowed:!1,reason:"\u4E0D\u662F\u53EF\u9000\u56DE\u7684\u529E\u7406\u8282\u70B9"};let s=rt(e).regions;for(let c of s){let l=c.branches.find(p=>p.nodeIds.includes(t)),f=c.branches.find(p=>p.nodeIds.includes(n));if(l?.id!==f?.id&&(l||f))return{allowed:!1,reason:"\u5E76\u884C\u5206\u652F\u5185\u53EA\u80FD\u9000\u56DE\u672C\u5206\u652F\u7684\u8282\u70B9\uFF0C\u4E0D\u80FD\u8DE8\u8D8A\u6C47\u5408\u8FB9\u754C"}}let a=[n],d=new Set;for(;a.length;){let c=a.shift();if(c===t)return{allowed:!0};if(d.has(c))continue;d.add(c);let l=o[c];l&&a.push(...Lo(l).filter(f=>!d.has(f)))}return{allowed:!1,reason:"\u8BE5\u8282\u70B9\u4E0D\u5728\u672C\u8282\u70B9\u4E4B\u524D\u7684\u53EF\u8FBE\u6D41\u8F6C\u8DEF\u5F84\u4E0A"}}function yc(e){return Object.values(e.nodes||{}).flatMap(t=>t.kind==="approval"||t.kind==="handle"?ot(t).filter(n=>!dp(e,t.id,n).allowed).map(n=>`WORKFLOW_RETURN_TARGET_UNREACHABLE:${t.id}:${n}`):[])}var zn=e=>`canvas_${e}`,Oc=(e,t)=>[...e==="approval"?["approve","reject"]:["complete"],...t?["save_form"]:[],"return","transfer","delegate",...e==="approval"?["add_assignee"]:[]];function dr(e,t,n="",o=""){let r=new Map;for(let i of[...Object.values(e.nodes),...e.authoring?.businessSteps||[]])!("handler"in i)||ie(i)||r.set(`${i.handler.code}@${i.handler.version}`,{title:i.title,handler:i.handler,inputSchema:i.inputSchema,outputSchema:i.outputSchema});return{appVersionId:n,digest:o,taskPages:e.taskPages||{},steps:[...r.values()],peopleSources:{...t.bindings,...Object.fromEntries((e.authoring?.peopleSources||[]).map(i=>[`authoring:${i.code}`,i.entry]))},...e.authoring?.peopleSources?.length?{peopleSourceTemplates:JSON.parse(JSON.stringify(e.authoring.peopleSources))}:{}}}function cp(e,t,n,o,r,i={},s=o){let a=zn(e);if(t==="cc")return{id:e,kind:t,title:n,next:o,binding:a,emptyPolicy:"block",notify:!0,administration:{assigneeProviders:["fixed_users","app_role"]}};let d=r?i[r]:void 0,c=Oc(t,!!d),l={id:e,title:n,binding:a,mode:"single",allowedOperations:c,requiredOperations:[t==="approval"?"approve":"complete"],administration:{modes:["single","any","all","sequence"],assigneeProviders:["fixed_users","app_role"],operations:c},fieldPolicy:{default:"readonly",fields:Object.fromEntries((d?.fields||[]).map(f=>[f.code,f.readonly?"readonly":f.required?"edit_required":"edit"]))},operationPolicy:{...t==="approval"?{approve:{opinion:"optional",minimumOpinion:"optional"},reject:{opinion:"required",minimumOpinion:"required"}}:{complete:{opinion:"optional",minimumOpinion:"optional"}},return:{opinion:"required",minimumOpinion:"required"},transfer:{opinion:"required",minimumOpinion:"required"},delegate:{opinion:"required",minimumOpinion:"required"},...t==="approval"?{add_assignee:{opinion:"required",minimumOpinion:"required"}}:{}},...d?{taskPageCode:r}:{}};return t==="approval"?{...l,kind:t,onApprove:o,onReject:s}:{...l,kind:t,next:o}}var ar=(e,t)=>{let n=o=>Array.isArray(o)?o.map(n):o&&typeof o=="object"?Object.fromEntries(Object.keys(o).sort().filter(r=>o[r]!==void 0).map(r=>[r,n(o[r])])):o;return JSON.stringify(n(e))===JSON.stringify(n(t))};function bc(e,t){if(!["approval","handle","cc"].includes(e.kind)||!("binding"in e)||e.binding!==zn(e.id))return["WORKFLOW_DESIGNER_CANVAS_BINDING_REQUIRED"];if(e.kind==="cc")return ar(e.administration,{assigneeProviders:["fixed_users","app_role"]})?[]:["WORKFLOW_DESIGNER_CODE_OWNED:administration"];if(e.kind!=="approval"&&e.kind!=="handle")return[];let n=cp(e.id,e.kind,e.title,"",e.taskPageCode,t.taskPages),o=[];for(let s of["administration","requiredOperations"])ar(e[s],n[s])||o.push(`WORKFLOW_DESIGNER_CODE_OWNED:${e.id}.${s}`);e.taskPageCode&&!t.taskPages[e.taskPageCode]&&o.push(`WORKFLOW_DESIGNER_PAGE_UNRELEASED:${e.id}`);let r=n.fieldPolicy;e.fieldPolicy?.default&&e.fieldPolicy.default!=="readonly"&&o.push(`WORKFLOW_DESIGNER_FIELD_CEILING:${e.id}`);for(let[s,a]of Object.entries(e.fieldPolicy?.fields||{}))(!(s in r.fields)||!["readonly","edit","edit_required"].includes(a)||["edit","edit_required"].includes(a)&&r.fields[s]==="readonly")&&o.push(`WORKFLOW_DESIGNER_FIELD_CEILING:${e.id}.${s}`);let i=Oc(e.kind,!!e.taskPageCode);(e.allowedOperations||i).some(s=>!i.includes(s))&&o.push(`WORKFLOW_DESIGNER_OPERATION_NOT_ALLOWED:${e.id}`);for(let[s,a]of Object.entries(e.operationPolicy||{})){let d=n.operationPolicy?.[s];(!i.includes(s)||!ar(a.minimumOpinion,d?.minimumOpinion)||["none","optional","required"].indexOf(xt(s,a))<["none","optional","required"].indexOf(ln(s,d)))&&o.push(`WORKFLOW_DESIGNER_OPINION_MINIMUM:${e.id}.${s}`)}return o}function hc(e,t,n=!1,o){if(e.provider==="conditional"){if(!t.conditionalAssignments||!o)return["WORKFLOW_DESIGNER_CONDITIONAL_ASSIGNMENT_UNAVAILABLE"];let i=o.definition.nodes[o.nodeId];if(!i||!["approval","handle"].includes(i.kind))return["WORKFLOW_CONDITIONAL_HUMAN_REQUIRED"];if("emptyPolicy"in i&&i.emptyPolicy==="skip")return["WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED"];let s;try{s=Object.fromEntries(Object.entries(t.peopleSources).flatMap(([a,d])=>ae(d).map((c,l)=>[`${a}/${l}`,c])))}catch{return["WORKFLOW_CONDITIONAL_BINDING_INVALID"]}return Zt(e,{...o,releasedSources:s,peopleSourceTemplates:t.peopleSourceTemplates,standardProviders:["fixed_users","app_role"]},{allowIncomplete:n})}if(Object.values(t.peopleSources).some(i=>ar(i,e))||io(e,t.peopleSourceTemplates))return o?Lr(e,o.definition,o.nodeId):[];let r=Object.keys(e);if(e.provider==="fixed_users"&&r.every(i=>["provider","users"].includes(i))&&Array.isArray(e.users)&&e.users.length<=200&&(n||e.users.length>0)&&new Set(e.users).size===e.users.length&&e.users.every(i=>typeof i=="string"&&!!i.trim()&&i.length<=255))return[];if(e.provider==="app_role"&&r.every(i=>["provider","roleCode","roleCodes"].includes(i))){let i=e.roleCodes||(e.roleCode?[e.roleCode]:[]);if(!(e.roleCode&&e.roleCodes)&&(n||i.length>0)&&i.length<=8&&new Set(i).size===i.length&&i.every(s=>/^[a-z][a-z0-9_-]{0,127}$/.test(s)))return[]}return["WORKFLOW_DESIGNER_BINDING_UNRELEASED"]}function FI(e,t,n){return{...t,bindings:Object.fromEntries(Object.entries(t.bindings).filter(([o])=>Object.hasOwn(n.bindings,o)||!o.startsWith("canvas_")||Object.values(e.nodes).some(r=>"binding"in r&&r.binding===o)))}}var Ne=e=>!!e&&typeof e=="object"&&!Array.isArray(e),cr=e=>Array.isArray(e)?e.map(cr):Ne(e)?Object.fromEntries(Object.keys(e).sort().map(t=>[t,cr(e[t])])):e,Fe=(e,t)=>JSON.stringify(cr(e))===JSON.stringify(cr(t));function lr(e){return e.kind==="approval"?[e.onApprove,e.onReject]:e.kind==="parallel"?[...(e.branches||[]).map(t=>t.target),e.join]:e.kind==="condition"?[...(e.branches||[]).map(t=>t.target),e.otherwise]:"next"in e?[e.next]:[]}function wc(e,t,n,o,r={}){let i=[...Do(t),...At(t,o)];if(!Ne(t)||!Ne(t.nodes)||!Ne(o?.bindings))return["WORKFLOW_DESIGNER_DOCUMENT_INVALID"];let s=new Set(["title","startAt","nodes","readability"]);for(let c of new Set([...Object.keys(e),...Object.keys(t)]))!s.has(c)&&!Fe(e[c],t[c])&&i.push(`WORKFLOW_DESIGNER_CODE_OWNED:${c}`);(n.workflowCode!==o.workflowCode||n.schemaVersion!==o.schemaVersion)&&i.push("WORKFLOW_DESIGNER_BINDING_IDENTITY");let a=r.catalog||dr(e,n),d=a.steps;for(let[c,l]of Object.entries(t.nodes)){if(!Ne(l)||l.id!==c||!["approval","handle","condition","cc","action","correction","end","parallel","join"].includes(l.kind)){i.push(`WORKFLOW_DESIGNER_NODE_INVALID:${c}`);continue}let f=e.nodes[c];f&&"binding"in f&&"binding"in l&&f.binding!==l.binding&&i.push(`WORKFLOW_DESIGNER_BINDING_CODE_OWNED:${c}`),"taskPageCode"in l&&l.taskPageCode&&!a.taskPages[l.taskPageCode]&&i.push(`WORKFLOW_DESIGNER_PAGE_UNRELEASED:${c}`),l.kind==="action"&&!ie(l)&&!d.some(m=>Fe(m.handler,l.handler)&&Fe(m.inputSchema,l.inputSchema)&&Fe(m.outputSchema,l.outputSchema))&&i.push(`WORKFLOW_DESIGNER_STEP_UNRELEASED:${c}`),["approval","handle"].includes(l.kind)&&"allowedOperations"in l&&l.allowedOperations&&(!Array.isArray(l.allowedOperations)||!l.allowedOperations.includes(l.kind==="handle"?"complete":"approve"))&&i.push(`WORKFLOW_DESIGNER_REQUIRED_ACTION:${c}.approve`);let p=e.nodes[c]||(l.kind==="approval"||l.kind==="handle"?Object.values(e.nodes).find(m=>{if(m.kind!==l.kind||!["approval","handle"].includes(m.kind)||!["fieldPolicy","administration","requiredOperations","taskPageCode"].every(O=>Fe(m[O],l[O])))return!1;let A=m;if(l.mode!==A.mode&&!A.administration?.modes?.includes(l.mode))return!1;let I=["none","optional","required"];return Object.entries(A.operationPolicy||{}).every(([O,b])=>{let g=l.operationPolicy?.[O];return Fe(b?.minimumOpinion,g?.minimumOpinion)&&I.indexOf(xt(O,g))>=I.indexOf(ln(O,b))})}):void 0);if(!p&&["approval","handle","cc"].includes(l.kind)&&("binding"in l&&l.binding!==zn(c)?i.push(`WORKFLOW_DESIGNER_APPROVAL_TEMPLATE_REQUIRED:${c}`):i.push(...bc(l,a).map(m=>`${m}:${c}`))),(p?.kind==="approval"||p?.kind==="handle")&&(l.kind==="approval"||l.kind==="handle")){l.mode!==p.mode&&!p.administration?.modes?.includes(l.mode)&&i.push(`WORKFLOW_DESIGNER_MODE_NOT_ALLOWED:${c}`);for(let m of["requiredOperations","fieldPolicy","administration"])Fe(p[m],l[m])||i.push(`WORKFLOW_DESIGNER_CODE_OWNED:${c}.${m}`);for(let m of p.requiredOperations||[])l.allowedOperations&&!l.allowedOperations.includes(m)&&i.push(`WORKFLOW_DESIGNER_REQUIRED_ACTION:${c}.${m}`);for(let[m,A]of Object.entries(p.operationPolicy||{})){let I=l.operationPolicy?.[m],O=["none","optional","required"];(!Fe(A?.minimumOpinion,I?.minimumOpinion)||O.indexOf(xt(m,I))<O.indexOf(ln(m,A)))&&i.push(`WORKFLOW_DESIGNER_CODE_OWNED:${c}.${m}.minimumOpinion`)}}"binding"in l&&!o.bindings[l.binding]&&i.push(`WORKFLOW_DESIGNER_BINDING_MISSING:${c}`)}Fe(e.readability?.logic,t.readability?.logic)||i.push("WORKFLOW_DESIGNER_CODE_OWNED:readability.logic");for(let[c,l]of Object.entries(o.bindings)){let f=n.bindings[c],p=Object.values(t.nodes).find(m=>"binding"in m&&m.binding===c&&c===zn(m.id));!f&&p&&!e.nodes[p.id]?i.push(...hc(l,a,r.allowIncomplete,{definition:t,nodeId:p.id}).map(m=>`${m}:${c}`)):!f&&!Object.values(n.bindings).some(m=>Fe(m,l))&&i.push(`WORKFLOW_DESIGNER_BINDING_UNRELEASED:${c}`),f&&!Fe(f,l)&&i.push(`WORKFLOW_DESIGNER_BINDING_CODE_OWNED:${c}`)}return i.push(...as(t)),[...new Set(i)]}function lp(e,t){if(t.type==="insert_parallel"||t.type==="insert_start_parallel"){if(e.nodes[t.joinId]||t.joinId===t.id||t.branches.length<2||t.branches.length>8)throw new Error("WORKFLOW_DESIGNER_PARALLEL_INSERT_INVALID");let r={id:t.id,kind:"parallel",title:t.title,join:t.joinId,branches:t.branches.map(s=>({...s,target:t.joinId}))},i=lp(e,t.type==="insert_start_parallel"?{type:"insert_start",target:t.target,node:r}:{type:"insert",from:t.from,target:t.target,node:r,...t.edge===void 0?{}:{edge:t.edge}});return i.nodes[t.joinId]={id:t.joinId,kind:"join",title:"\u5168\u90E8\u5B8C\u6210\u540E\u7EE7\u7EED",parallel:t.id,next:t.target},i}let n=structuredClone(e);if(t.type==="insert_start"){if(e.startAt!==t.target||!n.nodes[t.target]||n.nodes[t.node.id]||t.node.kind==="correction"||t.node.kind==="end"||t.node.kind==="join")throw new Error("WORKFLOW_DESIGNER_INSERT_INVALID");n.nodes[t.node.id]=structuredClone(t.node),n.startAt=t.node.id;for(let r of Object.values(n.nodes))r.kind==="correction"&&r.next===e.startAt&&(r.next=n.startAt);return n}let o=(r,i,s)=>{if(r.kind==="approval")r.onApprove===i&&(r.onApprove=s),r.onReject===i&&(r.onReject=s);else if(r.kind==="condition"){for(let a of r.branches)a.target===i&&(a.target=s);r.otherwise===i&&(r.otherwise=s)}else if(r.kind==="parallel")for(let a of r.branches)a.target===i&&(a.target=s);else"next"in r&&r.next===i&&(r.next=s)};if(t.type==="insert"){let r=n.nodes[t.from];if(!r||n.nodes[t.node.id]||!lr(r).includes(t.target)||!n.nodes[t.target])throw new Error("WORKFLOW_DESIGNER_INSERT_INVALID");if(n.nodes[t.node.id]=structuredClone(t.node),r.kind==="approval"){let i=t.edge==="reject"?"onReject":"onApprove";if(r[i]!==t.target)throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");r[i]=t.node.id}else if(r.kind==="parallel"){if(typeof t.edge!="number"||r.branches[t.edge]?.target!==t.target)throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");r.branches[t.edge].target=t.node.id}else if(r.kind==="condition")if(typeof t.edge=="number"&&r.branches[t.edge]?.target===t.target)r.branches[t.edge].target=t.node.id;else if(t.edge==="default"&&r.otherwise===t.target)r.otherwise=t.node.id;else throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID");else if("next"in r)r.next=t.node.id;else throw new Error("WORKFLOW_DESIGNER_INSERT_EDGE_INVALID")}else if(t.type==="remove_parallel_branch"){let r=n.nodes[t.nodeId];if(r?.kind!=="parallel"||r.branches.length<=2)throw new Error("WORKFLOW_PARALLEL_BRANCH_LIMIT");let s=rt(n).regions.find(a=>a.parallelNodeId===r.id)?.branches.find(a=>a.id===t.branchId);if(!s)throw new Error("WORKFLOW_DESIGNER_PARALLEL_BRANCH_MISSING");r.branches=r.branches.filter(a=>a.id!==t.branchId);for(let a of s.nodeIds)delete n.nodes[a]}else if(t.type==="remove"){let r=n.nodes[t.nodeId];if(r?.kind==="parallel"){let s=n.nodes[r.join],a=rt(n).regions.find(c=>c.parallelNodeId===r.id);if(s?.kind!=="join"||!a)throw new Error("WORKFLOW_DESIGNER_PARALLEL_PAIR_INVALID");let d=new Set([r.id,s.id,...a.branches.flatMap(c=>c.nodeIds)]);for(let c of Object.values(n.nodes))if(!d.has(c.id))for(let l of d)o(c,l,s.next);for(let c of d)delete n.nodes[c];return n.startAt===r.id&&(n.startAt=s.next),n}let i=t.reconnectTo||(r?.kind==="approval"?r.onApprove:r&&"next"in r?r.next:void 0);if(!r||!i||i===r.id||!n.nodes[i]||r.kind==="end"||r.kind==="correction"||r.kind==="join")throw new Error("WORKFLOW_DESIGNER_REMOVE_INVALID");for(let s of Object.values(n.nodes))o(s,r.id,i),(s.kind==="approval"||s.kind==="handle")&&s.returnTargets&&(s.returnTargets=s.returnTargets.filter(a=>a!==r.id)),(s.kind==="approval"||s.kind==="handle")&&s.returnPolicy&&(s.returnPolicy.targets=s.returnPolicy.targets.filter(a=>a.nodeId!==r.id));n.startAt===r.id&&(n.startAt=i),delete n.nodes[r.id]}else{let r=n.nodes[t.nodeId];if(!r)throw new Error("WORKFLOW_DESIGNER_NODE_MISSING");if(t.type==="node"){if("id"in t.patch||"kind"in t.patch)throw new Error("WORKFLOW_DESIGNER_NODE_ID_IMMUTABLE");Object.assign(r,t.patch)}else{if(r.kind!=="condition"||t.index<0||t.index>r.branches.length)throw new Error("WORKFLOW_DESIGNER_BRANCH_INVALID");r.branches[t.index]={when:structuredClone(t.when),target:t.target,...t.label?{label:t.label}:{}}}}return n}var Nc=(e,t)=>t.split(".").reduce((n,o)=>Ne(n)&&Object.hasOwn(n,o)?n[o]:void 0,e),Rc=(e,t)=>t.includes(",")?t.split(",").some(n=>Rc(e,n)):t==="unknown"?!0:t==="null"?e===null:t==="number"||t==="integer"?typeof e=="number"&&Number.isFinite(e)&&(t!=="integer"||Number.isInteger(e)):t==="array"?Array.isArray(e):t==="object"?Ne(e):typeof e===t;function JI(e,t,n){if(n.held)return{outcome:"held",reason:"\u5DF2\u6307\u5B9A\u4FDD\u7559\u5728\u539F\u7248\u672C"};let o=n.activeNodeIds?.length?n.activeNodeIds:n.currentNodeId?[n.currentNodeId]:[];if(!o.length)return{outcome:"excepted",reason:"\u5F53\u524D\u8FD0\u884C\u4F4D\u7F6E\u65E0\u6CD5\u786E\u5B9A"};if(o.some(a=>!t.nodes[a]))return{outcome:"excepted",reason:"\u5F53\u524D\u8282\u70B9\u5DF2\u88AB\u5220\u9664"};if(o.some(a=>e.nodes[a]?.kind!==t.nodes[a]?.kind))return{outcome:"excepted",reason:"\u5F53\u524D\u8282\u70B9\u7C7B\u578B\u5DF2\u6539\u53D8"};if((n.returnTargetNodeIds||[]).some(a=>!t.nodes[a]))return{outcome:"excepted",reason:"\u6B63\u5728\u9000\u56DE\u7684\u76EE\u6807\u8282\u70B9\u5DF2\u88AB\u5220\u9664"};if(!Fe(e.subject,t.subject)||!Fe(e.inputSchema,t.inputSchema))return{outcome:"excepted",reason:"\u7533\u8BF7\u6570\u636E\u6216\u53D8\u91CF\u5B9A\u4E49\u5DF2\u6539\u53D8\uFF0C\u9700\u8981\u660E\u786E\u7684\u6570\u636E\u8F6C\u6362"};if(n.forkNodeId){let a=e.nodes[n.forkNodeId],d=t.nodes[n.forkNodeId];if(a?.kind!=="parallel"||d?.kind!=="parallel"||a.join!==d.join)return{outcome:"excepted",reason:"\u6B63\u5728\u8FD0\u884C\u7684\u5E76\u884C\u5206\u652F\u6216\u6C47\u5408\u70B9\u5DF2\u6539\u53D8"};let c=rt(e).regions.find(f=>f.parallelNodeId===a.id),l=rt(t).regions.find(f=>f.parallelNodeId===d.id);for(let f of n.unarrivedBranchIds||[]){let p=l?.branches.find(m=>m.id===f);if(!p||o.some(m=>c?.branches.find(A=>A.id===f)?.nodeIds.includes(m)&&!p.nodeIds.includes(m)))return{outcome:"excepted",reason:"\u5C1A\u672A\u5B8C\u6210\u7684\u5E76\u884C\u5206\u652F\u6216\u5176\u5F53\u524D\u8282\u70B9\u5DF2\u6539\u53D8"}}}if(n.businessStepPending)return{outcome:"deferred",reason:"\u4E1A\u52A1\u6B65\u9AA4\u6267\u884C\u4E2D\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u66F4\u65B0"};let r=new Set,i=[...o];for(;i.length;){let a=i.pop();r.has(a)||(r.add(a),i.push(...lr(t.nodes[a]||{}).filter(d=>!!t.nodes[d])))}let s=Mo(t,"preview");for(let a of Object.values(t.nodes)){if(!r.has(a.id))continue;let d=a.kind==="condition"?a.branches.map(c=>c.when):a.kind==="action"?Object.values(a.inputs).filter(c=>c.source==="fact").map(c=>({op:"path",path:c.path})):[];for(let c of d)for(let l of Fn(c).paths){let f=s.variables.find(m=>m.path===l),p=Nc(n.facts,l);if(p===void 0&&f?.source.kind==="step_output"&&r.has(f.source.nodeId)&&!o.includes(f.source.nodeId)){let m=new Set,A=[...o];for(;A.length;){let I=A.pop();I===f.source.nodeId||m.has(I)||(m.add(I),A.push(...lr(t.nodes[I]||{}).filter(O=>!!t.nodes[O])))}if(!m.has(a.id))continue}if(!(p===void 0&&f&&!f.required&&(f.source.kind!=="step_output"||Ne(Nc(n.facts,`steps.${f.source.nodeId}`))))&&(p===void 0||f&&!Rc(p,f.type)))return{outcome:"excepted",reason:`\u540E\u7EED\u6761\u4EF6\u9700\u8981\u7684\u6570\u636E\u5728\u8BE5\u7533\u8BF7\u4E2D\u4E0D\u5B58\u5728\u6216\u7C7B\u578B\u4E0D\u517C\u5BB9\uFF1A${f?.label||l}`}}}return{outcome:"eligible"}}function as(e){if(!Ne(e?.nodes))return["WORKFLOW_DESIGNER_DOCUMENT_INVALID"];let t=[];t.push(...vo(e),...Po(e),...ko(e),...yc(e),...Qn(e));let n=Object.values(e.nodes);if(n.length>200||!n.length)return["WORKFLOW_DESIGNER_NODE_LIMIT"];for(let c of n)!Ne(c)||!["approval","handle","condition","cc","action","correction","end","parallel","join"].includes(c.kind)?t.push("WORKFLOW_DESIGNER_NODE_INVALID"):c.kind==="condition"&&(!Array.isArray(c.branches)||!c.branches.length||c.branches.length>32||c.branches.some(l=>!Ne(l)||!Ne(l.when)||typeof l.target!="string"))&&t.push(`WORKFLOW_DESIGNER_BRANCH_INVALID:${c.id}`);if(t.length)return[...new Set(t)];let o=Mo(e,"draft").variables,r=0,i=(c,l,f=0)=>{if(!Ne(c)||f>16||++r>4096)return t.push(`WORKFLOW_DESIGNER_EXPRESSION_LIMIT:${l}`),"invalid";if(c.op==="literal"){let p=c.value;return p===null?"null":Array.isArray(p)?"array":typeof p=="object"?"object":typeof p}if(c.op==="path"){let p=o.find(A=>A.path===c.path);(!p||p.type==="unknown")&&t.push(`WORKFLOW_DESIGNER_VARIABLE_UNKNOWN:${l}:${c.path}`);let m=p?.type.split(",").find(A=>A!=="null")||p?.type||"unknown";return m==="integer"?"number":m}if(c.op==="and"||c.op==="or"){if(!Array.isArray(c.values)||c.values.length<1||c.values.length>32)return t.push(`WORKFLOW_DESIGNER_CONDITION_GROUP:${l}`),"invalid";for(let p of c.values)i(p,l,f+1)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${l}`)}else if(c.op==="not"||c.op==="exists"){let p=i(c.value,l,f+1);c.op==="not"&&p!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${l}`)}else if(["eq","neq","gt","gte","lt","lte","in","contains"].includes(c.op)&&"left"in c){let p=i(c.left,l,f+1),m=i(c.right,l,f+1);(c.op==="in"?m==="array":c.op==="contains"?p==="array"||p==="string"&&m==="string":["gt","gte","lt","lte"].includes(c.op)?p===m&&["number","string"].includes(p):p===m||p==="null"||m==="null")||t.push(`WORKFLOW_DESIGNER_CONDITION_TYPE:${l}`)}else t.push(`WORKFLOW_DESIGNER_CONDITION_OPERATOR:${l}`);return"boolean"},s=new Set,a=new Set,d=c=>{if(a.has(c)){t.push(`WORKFLOW_DESIGNER_CYCLE:${c}`);return}if(s.has(c))return;let l=e.nodes[c];if(!l){t.push(`WORKFLOW_DESIGNER_TARGET_MISSING:${c}`);return}a.add(c);for(let f of lr(l))d(f);a.delete(c),s.add(c)};for(let c of n){if((!/^[a-z][a-z0-9_-]{0,127}$/.test(c.id)||e.nodes[c.id]!==c)&&t.push(`WORKFLOW_DESIGNER_NODE_ID:${c.id}`),c.kind==="parallel")for(let l of c.branches)l.when&&i(l.when,c.id)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${c.id}`);if(c.kind==="condition"){(!c.branches.length||c.branches.length>32)&&t.push(`WORKFLOW_DESIGNER_BRANCH_LIMIT:${c.id}`);for(let l of c.branches)i(l.when,c.id)!=="boolean"&&t.push(`WORKFLOW_DESIGNER_CONDITION_BOOLEAN:${c.id}`)}}d(e.startAt);for(let c of n)!s.has(c.id)&&c.kind!=="correction"&&t.push(`WORKFLOW_DESIGNER_UNREACHABLE:${c.id}`);return[...new Set(t)]}function HI(e){let t={...e.readability?.variables},n=(o,r="",i=0)=>{if(!(i>8||!Ne(o)))if(o.type==="object"&&Ne(o.properties))for(let[s,a]of Object.entries(o.properties))n(a,r?`${r}.${s}`:s,i+1);else r&&(t[r]||={label:String(o.title||r)})};n(e.inputSchema);for(let o of Object.values(e.nodes))o.kind==="action"&&n(o.outputSchema,`steps.${o.id}`);return Mo({...e,readability:{...e.readability,variables:t}},"draft").variables.filter(o=>o.type!=="unknown")}function ur(e,t){return(t?(Array.isArray(e)?e:[]).filter(Array.isArray):[Array.isArray(e)?e.filter(o=>!Array.isArray(o)):[]]).map(o=>o[o.length-1]?.value).filter(o=>!!o)}var Tc=["province","city","district","street"];function Cc(e){for(let t=Tc.length-1;t>=0;t-=1){let n=Tc[t],o=n?e?.[n]:void 0;if(n&&o?.value)return{path:`${n}.value`,value:o.value}}}function ds(e){return!!(e&&typeof e=="object"&&!Array.isArray(e)&&"value"in e)}function cs(e){return ds(e)?String(e.value):e}function Sc(e){return(Array.isArray(e)?e:[e]).map(cs)}function up(e,t,n){let o=new Set(Object.keys(t.fields)),r=s=>{if(!o.has(s))throw new Error(`OPENXIANGDA_RESOURCE_QUERY_FIELD_NOT_DECLARED:${e}:${s}`);return s},i=n.where?[fr(e,t,n.where)]:[];if(n.createdBy!==void 0&&n.createdBy!==""&&i.push({field:"created_by",operator:"eq",value:n.createdBy}),n.keyword?.trim()){let s=(t.list?.searchableFields||[]).filter(a=>o.has(a));s.length&&i.push({or:s.map(a=>({field:r(a),operator:"contains",value:n.keyword.trim()}))})}for(let[s,a]of Object.entries(n.filters||{})){if(a==null||a===""||Array.isArray(a)&&a.length===0||!o.has(s))continue;let d=t.fields[s];if(d)if(d.type==="json")i.push({field:s,operator:"jsonContains",value:a});else if(d.type==="address"){let c=Cc(a);c&&i.push({field:s,operator:"jsonContains",path:c.path,value:c.value})}else if(d.type==="cascade.single"||d.type==="cascade.multiple"){let c=ur(a,d.type==="cascade.multiple");c.length&&i.push({field:s,operator:d.type==="cascade.multiple"?"hasAny":"has",value:d.type==="cascade.multiple"?c:c[0]})}else if((d.type==="date-range"||d.type==="datetime-range")&&a!==null&&typeof a=="object"&&!Array.isArray(a)){let c=a;c.start!==void 0&&c.end!==void 0&&i.push({field:s,operator:"overlaps",value:{start:c.start,end:c.end}})}else if(Array.isArray(a)&&a.length===2&&["date","datetime","number","money","percent"].includes(d.widget))a[0]!==void 0&&a[0]!==null&&a[0]!==""&&i.push({field:s,operator:"gte",value:a[0]}),a[1]!==void 0&&a[1]!==null&&a[1]!==""&&i.push({field:s,operator:"lte",value:a[1]});else if(d.type==="option.multiple"||d.type==="user.multiple"||d.type==="department.multiple"||d.type==="resource-ref.multiple")i.push({field:s,operator:"hasAny",value:Sc(a)});else{let[c]=Sc(a);i.push({field:s,operator:"eq",value:c})}}return i.length?{and:i}:void 0}function fr(e,t,n){if("and"in n)return{and:n.and.map(s=>fr(e,t,s))};if("or"in n)return{or:n.or.map(s=>fr(e,t,s))};if("not"in n)return{not:fr(e,t,n.not)};if(n.path!==void 0)return n;if(n.operator==="isEmpty"||n.operator==="isNotEmpty")return{field:n.field,operator:n.operator};let o=t.fields[n.field];if(n.operator==="has"){let s=o?.type==="cascade.single"&&Array.isArray(n.value)&&n.value.length>0&&n.value.every(ds);return{...n,value:s?ur(n.value,!1)[0]:cs(n.value)}}if(["in","between","hasAny","hasAll"].includes(n.operator)){if(!Array.isArray(n.value))return n;let s=o?.type==="cascade.multiple"&&["hasAny","hasAll"].includes(n.operator)&&n.value.length>0&&n.value.every(a=>Array.isArray(a)&&a.length>0&&a.every(ds));return{...n,value:s?ur(n.value,!0):n.value.map(cs)}}let r=up(e,t,{page:1,pageSize:20,filters:{[n.field]:n.value}}),i=r&&"and"in r?r.and[0]:void 0;return i&&"field"in i?{...i,operator:n.operator}:n}var Jn=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Gn=(e,t)=>Jn(e)&&Object.keys(e).every(n=>t.includes(n)),Hn=e=>JSON.parse(JSON.stringify(e));function He(){throw new Error("WORKFLOW_BUNDLE_HANDLING_INVALID")}function ls(e,t){if(Jn(e)||He(),e.kind==="named_people")return(!Gn(e,["kind","count"])||!Number.isSafeInteger(e.count)||e.count<0||e.count>200)&&He(),t?{provider:"fixed_users",users:["source-private-leaf"]}:void 0;(!Gn(e,["kind","binding"])||e.kind!=="binding"||!Jn(e.binding)||["fixed_users","conditional"].includes(e.binding.provider))&&He();let n=e.binding;return De({provider:"conditional",cases:[{when:{op:"literal",value:!0},assignee:n}],otherwise:n}).length&&He(),Hn(n)}function pr(e,t){if(Jn(e)||He(),e.kind==="roles"){(!Gn(e,["kind","roleCodes"])||!Array.isArray(e.roleCodes))&&He();let s=e.roleCodes.length===1?{provider:"app_role",roleCode:e.roleCodes[0]}:{provider:"app_role",roleCodes:e.roleCodes};return De({provider:"conditional",cases:[{when:{op:"literal",value:!0},assignee:s}],otherwise:s}).length&&He(),Hn(s)}if(e.kind!=="conditional")return ls(e,t);(!Gn(e,["kind","cases","otherwise"])||!Array.isArray(e.cases)||!e.cases.length||e.cases.length>20)&&He();let n=!1,o=e.cases.map(s=>{Gn(s,["label","when","assignee"])||He();let a=ls(s.assignee,t);return a||(n=!0),{...s.label!==void 0?{label:s.label}:{},when:s.when,assignee:a||{provider:"fixed_users",users:["source-private-leaf"]}}}),r=ls(e.otherwise,t);r||(n=!0);let i={provider:"conditional",cases:o,otherwise:r||{provider:"fixed_users",users:["source-private-leaf"]}};return De(i).length&&He(),n?void 0:Hn(i)}function oy(e){let t=o=>o.provider==="fixed_users"?{kind:"named_people",count:o.users?.length||0}:{kind:"binding",binding:Hn(o)};if(e.provider==="conditional")return De(e).length&&He(),{kind:"conditional",cases:e.cases.map(o=>({...o.label!==void 0?{label:o.label}:{},when:Hn(o.when),assignee:t(o.assignee)})),otherwise:t(e.otherwise)};let n=t(e);return pr(n,!0),n}function ry(e){return pr(e,!1)}function iy(e){if(!e)return{present:!1,count:0};pr(e,!0);let n=(e.kind==="conditional"?[...e.cases.map(o=>o.assignee),e.otherwise]:[e]).filter(o=>o.kind==="named_people");return{present:n.length>0,count:n.reduce((o,r)=>o+r.count,0)}}function Dc(e,t,n){try{let o=pr(e,!0);if(!o)return["WORKFLOW_BUNDLE_HANDLING_INVALID"];let r=t.nodes[n];if(!r||!("binding"in r))return["WORKFLOW_BUNDLE_HANDLING_INVALID"];if(o.provider!=="conditional"&&Jn(e)&&e.kind!=="binding")return[];let i=o.provider==="conditional"?o:{provider:"conditional",cases:[{when:{op:"literal",value:!0},assignee:o}],otherwise:o},s="$source-handling-validation",a={...t,nodes:{...t.nodes,[n]:{...r,binding:s}}};return"emptyPolicy"in r&&r.emptyPolicy==="skip"?["WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED"]:Xt(a,{schemaVersion:"openxiangda.workflow-binding/v2",workflowCode:t.code,bindings:{[s]:i}})}catch{return["WORKFLOW_BUNDLE_HANDLING_INVALID"]}}var kc="openxiangda.workflow-source-bundle/v1",us="openxiangda.workflow-source-bundle/v2",fp=3*1024*1024,mt=(e,t)=>e.replace(/^sha256:/,"")===t.replace(/^sha256:/,""),Kt=(e,t)=>mt(e.definitionDigest,t.definitionDigest)&&mt(e.bindingDigest,t.bindingDigest),mr=e=>!!e&&typeof e=="object"&&!Array.isArray(e),Bt=(e,t)=>mr(e)&&Object.keys(e).every(n=>t.includes(n)&&!["__proto__","constructor","prototype"].includes(n)),fs=e=>typeof e=="string"&&/^[A-Za-z][A-Za-z0-9_-]{0,127}$/.test(e),pp=e=>typeof e=="string"&&/^(sha256:)?[a-f0-9]{64}$/.test(e);function mp(e,t,n){let o=new Set(Object.values(e.nodes).flatMap(i=>"taskPageCode"in i&&i.taskPageCode?[i.taskPageCode]:[])),r=new Map;for(let i of Object.values(e.nodes))i.kind==="action"&&r.set(`${i.handler.code}@${i.handler.version}`,{code:i.handler.code,version:i.handler.version,digest:n({handler:i.handler,inputSchema:i.inputSchema,outputSchema:i.outputSchema})});return{taskPages:[...o].sort().map(i=>({code:i,digest:n(e.taskPages?.[i])})),steps:[...r.values()].sort((i,s)=>i.code.localeCompare(s.code)||i.version-s.version),bindingKeys:Object.keys(t.bindings).sort(),roles:[...new Set(Object.values(t.bindings).flatMap(i=>ae(i).flatMap(s=>[...Yn(s),...i.provider==="conditional"?Object.values(s.routing?.sources||{}).map(a=>a.roleCode):[]])))].sort()}}function gp(e,t){try{return _p(e,t)}catch{return["WORKFLOW_BUNDLE_CORRUPT"]}}function _p(e,t){let n=[];if(!Bt(e,["schemaVersion","appCode","workflowCode","origin","definition","binding","references","handling"])||![kc,us].includes(e.schemaVersion)||!fs(e.appCode)||!fs(e.workflowCode))return["WORKFLOW_BUNDLE_CORRUPT"];if(new TextEncoder().encode(JSON.stringify(e)).length>fp)return["WORKFLOW_BUNDLE_TOO_LARGE"];let o=e,r=o.origin;if(!Bt(r,["environmentKey","headRevision","definitionVersion","bindingVersion","definitionDigest","bindingDigest","handlingDigest","catalogDigest"])||!["preproduction","production"].includes(r.environmentKey)||![r.headRevision,r.definitionVersion,r.bindingVersion].every(i=>Number.isSafeInteger(i)&&i>=1)||![r.definitionDigest,r.bindingDigest,r.handlingDigest,r.catalogDigest].every(pp))return["WORKFLOW_BUNDLE_CORRUPT"];if(!mr(o.definition?.nodes)||!mr(o.binding?.bindings)||o.definition.code!==o.workflowCode||o.binding.workflowCode!==o.workflowCode)return["WORKFLOW_BUNDLE_CORRUPT"];if(o.schemaVersion===kc&&Object.values(o.binding.bindings).some(i=>i.provider==="conditional"))return["WORKFLOW_SOURCE_CONDITIONAL_EXPORT_UNAVAILABLE"];if(o.schemaVersion===us){n.push(...Xt(o.definition,o.binding));for(let i of Object.values(o.definition.nodes))"binding"in i&&o.binding.bindings[i.binding]?.provider==="conditional"&&"emptyPolicy"in i&&i.emptyPolicy==="skip"&&n.push("WORKFLOW_APPROVAL_EMPTY_PROVIDER_UNSUPPORTED")}if(as(o.definition).length&&n.push("WORKFLOW_BUNDLE_DEFINITION_INVALID"),(!mt(t(o.definition),r.definitionDigest)||!mt(t(o.binding),r.bindingDigest)||!mt(t(o.handling),r.handlingDigest)||!mt(t(o.references),r.catalogDigest))&&n.push("WORKFLOW_BUNDLE_CORRUPT"),mt(t(mp(o.definition,o.binding,t)),t(o.references))||n.push("WORKFLOW_BUNDLE_CATALOG_CORRUPT"),!mr(o.handling)||Object.keys(o.handling).length>200)n.push("WORKFLOW_BUNDLE_HANDLING_INVALID");else for(let[i,s]of Object.entries(o.handling)){if(!o.definition.nodes[i]||!Bt(s,["mode","operations","assignee"])){n.push("WORKFLOW_BUNDLE_HANDLING_INVALID");continue}if(s.mode!==void 0&&!["single","any","all","sequence"].includes(s.mode)&&n.push("WORKFLOW_BUNDLE_HANDLING_INVALID"),s.operations!==void 0){let d=["complete","approve","reject","save_form","return","transfer","delegate","add_assignee"];if(!Bt(s.operations,d))n.push("WORKFLOW_BUNDLE_HANDLING_INVALID");else for(let c of Object.values(s.operations))(!Bt(c,["enabled","label","opinion","commentRequired","reasonRequired"])||c.enabled!==void 0&&typeof c.enabled!="boolean"||c.commentRequired!==void 0&&typeof c.commentRequired!="boolean"||c.reasonRequired!==void 0&&typeof c.reasonRequired!="boolean"||c.label!==void 0&&(typeof c.label!="string"||!c.label.trim()||c.label.length>255)||c.opinion!==void 0&&!["none","optional","required"].includes(c.opinion))&&n.push("WORKFLOW_BUNDLE_HANDLING_INVALID")}let a=s.assignee;if(a&&o.schemaVersion===us){let d=o.definition.nodes[i],c={...o.definition,nodes:{...o.definition.nodes,[i]:{...d,..."mode"in d&&s.mode?{mode:s.mode}:{}}}},l=Dc(a,c,i);l.length&&n.push("WORKFLOW_BUNDLE_HANDLING_INVALID",...l)}else a&&(a.kind==="named_people"?!Bt(a,["kind","count"])||!Number.isSafeInteger(a.count)||a.count<0||a.count>200:a.kind!=="roles"||!Bt(a,["kind","roleCodes"])||!Array.isArray(a.roleCodes)||a.roleCodes.length>200||!a.roleCodes.every(fs))&&n.push("WORKFLOW_BUNDLE_HANDLING_INVALID")}return[...new Set(n)]}function py(e){if(!e.head)return"not_active";if(Kt(e.declared,e.head))return"in_sync";let t=e.base||e.activeDeclaration;return t&&Kt(t,e.head)?"ahead":!t||Kt(e.declared,t)?"behind":"diverged"}function my(e){return e.head?Kt(e.declared,e.head)?"reuse":e.activeDeclaration&&Kt(e.declared,e.activeDeclaration)?"preserve":e.base&&Kt(e.base,e.head)||e.activeDeclaration&&Kt(e.activeDeclaration,e.head)?"advance":"diverged":"advance"}function gy(e,t,n,o){let r=gp(n,o);if(r.length)return r;r.push(...wc(e,n.definition,t,n.binding).map(s=>`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:${s}`));for(let s of n.references.taskPages)(!e.taskPages?.[s.code]||!mt(o(e.taskPages[s.code]),s.digest))&&r.push(`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:taskPage:${s.code}`);let i=dr(e,t).steps.map(s=>({code:s.handler.code,version:s.handler.version,digest:o({handler:s.handler,inputSchema:s.inputSchema,outputSchema:s.outputSchema})}));for(let s of n.references.steps)i.some(a=>a.code===s.code&&a.version===s.version&&mt(a.digest,s.digest))||r.push(`WORKFLOW_IMPORT_CODE_OWNED_DRIFT:step:${s.code}@${s.version}`);return[...new Set(r)]}var ps="openxiangda.workflow-definition/v2",ms="openxiangda.workflow-binding/v2";var G={type:"string",minLength:1},Ep={type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},Ye=e=>({type:"string",minLength:1,maxLength:e,pattern:"\\S"}),Lc={type:"array",maxItems:32,uniqueItems:!0,items:Ye(256)},Ip={type:"object",additionalProperties:!1,minProperties:1,properties:{variables:{type:"object",maxProperties:128,propertyNames:Ye(256),additionalProperties:{type:"object",additionalProperties:!1,required:["label"],properties:{label:Ye(160),unit:Ye(32),description:Ye(2e3)}}},logic:{type:"array",maxItems:32,items:{type:"object",additionalProperties:!1,required:["code","title","description","phase","inputPaths"],properties:{code:{type:"string",pattern:"^[a-z][a-z0-9-]{2,63}$"},title:Ye(160),description:Ye(4e3),phase:{enum:["submission","node_input","completion"]},nodeId:Ye(128),inputPaths:Lc,outputPaths:Lc,source:{type:"object",additionalProperties:!1,required:["path","digest"],properties:{path:Ye(256),symbol:Ye(160),digest:{type:"string",pattern:"^sha256:[a-f0-9]{64}$"}}}}}}}},yp={type:"object",additionalProperties:!1,required:["id","kind","title","binding","next","emptyPolicy"],properties:{id:G,kind:{const:"cc"},title:G,binding:G,next:G,emptyPolicy:{enum:["block","skip"]},notify:{type:"boolean"},administration:{type:"object",additionalProperties:!1,properties:{assigneeProviders:{type:"array",minItems:1,maxItems:3,uniqueItems:!0,items:{enum:["fixed_users","app_role","app_role_in_scope"]}}}}}},gs={type:"object",additionalProperties:!1,required:["afterSeconds","everySeconds","max","to"],properties:{afterSeconds:{type:"integer",minimum:1,maximum:2592e3},everySeconds:{type:"integer",minimum:1,maximum:2592e3},max:{type:"integer",minimum:1,maximum:10},to:{type:"array",minItems:1,maxItems:1,items:{const:"handlers"}}}},Op={type:"object",additionalProperties:!1,required:["id","kind","title","next","handler","inputSchema","outputSchema","inputs"],properties:{id:G,kind:{const:"action"},title:G,next:G,handler:{type:"object",additionalProperties:!1,required:["code","version","mode"],properties:{code:{type:"string",pattern:"^[a-z][a-z0-9-]{0,100}$"},version:{type:"integer",minimum:1,maximum:1e6},mode:{enum:["pure","reconciled-effect"]},dataTransaction:{const:!0}},allOf:[{if:{required:["dataTransaction"]},then:{properties:{mode:{const:"reconciled-effect"}}}}]},notification:{type:"object",additionalProperties:!1,required:["template","recipients"],properties:{template:{const:"workflow_message"},recipients:{oneOf:[{type:"object",additionalProperties:!1,required:["provider"],properties:{provider:{const:"initiator"}}},{type:"object",additionalProperties:!1,required:["provider","users"],properties:{provider:{const:"fixed_users"},users:{type:"array",minItems:1,maxItems:50,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:255}}}},{type:"object",additionalProperties:!1,required:["provider","roleCode"],properties:{provider:{const:"app_role"},roleCode:G}},{type:"object",additionalProperties:!1,required:["provider","inputPath"],properties:{provider:{const:"form_field_users"},inputPath:G}}]}}},inputSchema:{type:"object"},outputSchema:{type:"object"},inputs:{type:"object",maxProperties:32,additionalProperties:{oneOf:[{type:"object",additionalProperties:!1,required:["source","path"],properties:{source:{const:"fact"},path:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["source","value"],properties:{source:{const:"literal"},value:{}}}]}}}},vc={type:"object",additionalProperties:!1,required:["targets"],properties:{targets:{type:"array",maxItems:20,items:{type:"object",additionalProperties:!1,required:["nodeId","routes","defaultRoute"],properties:{nodeId:G,routes:{type:"array",minItems:1,maxItems:2,uniqueItems:!0,items:{enum:["replay","resume"]}},defaultRoute:{enum:["replay","resume"]}}}}}},bp={oneOf:[{type:"object",additionalProperties:!1,required:["id","kind","title","binding","mode","next","allowedOperations","requiredOperations"],properties:{id:G,kind:{const:"handle"},title:G,reminders:gs,binding:G,mode:{enum:["single","any","all","sequence"]},next:G,emptyPolicy:{const:"block"},taskPageCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},allowedOperations:{type:"array",uniqueItems:!0,items:{enum:["complete","save_form","return","transfer","delegate"]}},requiredOperations:{type:"array",uniqueItems:!0,items:{enum:["complete","save_form","return","transfer","delegate"]}},returnPolicy:vc,returnTargets:{type:"array",items:G,uniqueItems:!0},operationPolicy:{type:"object",additionalProperties:!1,properties:Object.fromEntries(["complete","save_form","return","transfer","delegate"].map(e=>[e,{type:"object",additionalProperties:!1,minProperties:1,properties:{label:{type:"string",minLength:1,maxLength:40},...e!=="save_form"?{opinion:{enum:["none","optional","required"]},minimumOpinion:{enum:["none","optional","required"]}}:{},...e==="complete"?{commentRequired:{type:"boolean"}}:{},...["return","transfer","delegate"].includes(e)?{reasonRequired:{type:"boolean"}}:{}}}]))},administration:{type:"object",additionalProperties:!1,properties:{modes:{type:"array",uniqueItems:!0,minItems:1,maxItems:4,items:{enum:["single","any","all","sequence"]}},assigneeProviders:{type:"array",uniqueItems:!0,minItems:1,maxItems:3,items:{enum:["fixed_users","app_role","app_role_in_scope"]}},operations:{type:"array",uniqueItems:!0,minItems:1,maxItems:5,items:{enum:["complete","save_form","return","transfer","delegate"]}}}},fieldPolicy:{type:"object",additionalProperties:!1,properties:{default:{enum:["hidden","readonly","edit","edit_required"]},fields:{type:"object",additionalProperties:{enum:["hidden","readonly","edit","edit_required"]}}}}}},{type:"object",additionalProperties:!1,required:["id","kind","title","binding","mode","onApprove","onReject"],properties:{id:G,kind:{const:"approval"},reminders:gs,title:G,binding:G,mode:{enum:["single","any","all","sequence"]},emptyPolicy:{enum:["block","skip"]},initiatorApprovalPolicy:{enum:["manual","auto_approve"]},completionDeadline:{type:"object",additionalProperties:!1,required:["afterSeconds","action"],properties:{afterSeconds:{type:"integer",minimum:1,maximum:2592e3},action:{const:"approve"}}},onApprove:G,onReject:G,taskPageCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},operationPolicy:{type:"object",additionalProperties:!1,properties:Object.fromEntries(Nt.map(e=>[e,{type:"object",additionalProperties:!1,minProperties:1,properties:{label:{type:"string",minLength:1,maxLength:40,pattern:"^(?!.*[\\u0000-\\u001f\\u007f])(?=.*\\S).*$"},...e!=="save_form"?{opinion:{enum:["none","optional","required"]},minimumOpinion:{enum:["none","optional","required"]}}:{},...["complete","approve","reject"].includes(e)?{commentRequired:{type:"boolean"}}:{},...["transfer","delegate","add_assignee","return"].includes(e)?{reasonRequired:{type:"boolean"}}:{}}}]))},administration:{type:"object",additionalProperties:!1,properties:{modes:{type:"array",minItems:1,maxItems:4,uniqueItems:!0,items:{enum:["single","any","all","sequence"]}},assigneeProviders:{type:"array",minItems:1,maxItems:3,uniqueItems:!0,items:{enum:["fixed_users","app_role","app_role_in_scope"]}},operations:{type:"array",minItems:1,maxItems:8,uniqueItems:!0,items:{enum:[...Nt]}}}},requiredOperations:{type:"array",minItems:1,maxItems:7,uniqueItems:!0,items:{enum:[...Nt]}},allowedOperations:{type:"array",uniqueItems:!0,items:{enum:["approve","reject","return","transfer","delegate","add_assignee","resubmit","save_form","admin_reassign","admin_override"]}},returnPolicy:vc,returnTargets:{type:"array",uniqueItems:!0,items:G},fieldPolicy:{type:"object",additionalProperties:!1,properties:{default:{enum:["hidden","readonly","edit","edit_required"]},fields:{type:"object",additionalProperties:{enum:["hidden","readonly","edit","edit_required"]}}}}}},{type:"object",additionalProperties:!1,required:["id","kind","branches","otherwise"],properties:{id:G,kind:{const:"condition"},title:{type:"string"},branches:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["when","target"],properties:{when:kt,target:G,label:{type:"string"}}}},otherwise:G}},{type:"object",additionalProperties:!1,required:["id","kind","title","outcome"],properties:{id:G,kind:{const:"end"},title:G,outcome:G}},yp,Op,{type:"object",additionalProperties:!1,required:["id","kind","title","taskPageCode","next"],properties:{id:G,kind:{const:"correction"},title:G,reminders:gs,taskPageCode:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},next:G}}]},hp={$id:ps,type:"object",additionalProperties:!1,required:["schemaVersion","code","title","acceptedCommandDeactivationPolicy","subject","startAt","inputSchema","nodes"],properties:{schemaVersion:{const:ps},authoring:{type:"object",additionalProperties:!1,properties:{peopleSources:{type:"array",maxItems:32,items:{type:"object",additionalProperties:!1,required:["code","title","entry","parameters"],properties:{code:{type:"string",pattern:"^[a-z][a-z0-9-]{0,63}$"},title:Ye(160),entry:Dt,parameters:{type:"object",minProperties:1,maxProperties:8,additionalProperties:{oneOf:[{type:"object",additionalProperties:!1,required:["values"],properties:{values:{type:"array",minItems:1,maxItems:32}}},{type:"object",additionalProperties:!1,required:["minimum","maximum"],properties:{minimum:{type:"integer",minimum:1,maximum:200},maximum:{type:"integer",minimum:1,maximum:200}}}]}}}}},businessSteps:{type:"array",maxItems:100,items:{type:"object",additionalProperties:!1,required:["title","handler","inputSchema","outputSchema"],properties:{title:{type:"string",minLength:1,maxLength:160},handler:{type:"object",additionalProperties:!1,required:["code","version","mode"],properties:{code:{type:"string",pattern:"^[a-z][a-z0-9_-]{0,127}$"},version:{type:"integer",minimum:1},mode:{enum:["pure","reconciled-effect"]},dataTransaction:{const:!0}}},inputSchema:{type:"object"},outputSchema:{type:"object"}}}}}},code:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},title:G,launchPreflight:{type:"object",additionalProperties:!1,required:["requiredApprovalNodes"],properties:{requiredApprovalNodes:{type:"array",minItems:1,maxItems:20,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"}}}},approvedDelegation:{type:"object",additionalProperties:!1,required:["confirmationNodeId","confirmer","requestsField","maxRequests"],properties:{confirmationNodeId:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_-]{0,127}$"},confirmer:{enum:["initiator","delegate"]},requestsField:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},maxRequests:{type:"integer",minimum:1,maximum:500}}},commandHandlers:{type:"object",additionalProperties:!1,minProperties:1,properties:Object.fromEntries(["approve","reject","withdraw","resubmit"].map(e=>[e,{type:"object",additionalProperties:!1,required:["operationCode"],properties:{operationCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$"},...e==="approve"?{transitionPolicy:{const:"workflow"}}:{},...e==="resubmit"?{derivedSubjectFields:{type:"array",minItems:1,maxItems:32,uniqueItems:!0,items:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"}}}:{}}}]))},taskPages:{type:"object",minProperties:1,maxProperties:16,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_-]{0,63}$"},additionalProperties:{type:"object",additionalProperties:!1,required:["title","fields"],properties:{title:{type:"string",minLength:1,maxLength:160},fields:{type:"array",minItems:1,maxItems:200,items:{type:"object",additionalProperties:!1,required:["code"],properties:{code:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},readonly:{type:"boolean"},required:{type:"boolean"},visibleWhen:kt,requiredWhen:kt}}}}}},acceptedCommandDeactivationPolicy:{enum:["finish-pinned","cancel-on-deactivate"]},rejectionNotification:{type:"object",additionalProperties:!1,required:["recipient","title","summary"],properties:{recipient:{const:"record_last_modifier"},title:{type:"string",minLength:1,maxLength:160,pattern:"\\S"},summary:{type:"string",minLength:1,maxLength:500,pattern:"\\S"}}},instanceCommands:{type:"object",additionalProperties:!1,minProperties:1,properties:{withdraw:{type:"object",additionalProperties:!1,minProperties:1,properties:{beforeFact:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"},reasonRequired:{type:"boolean"}}},terminate:{type:"object",additionalProperties:!1,required:["capability"],properties:{capability:{type:"string",maxLength:255,pattern:"^app:[a-z][a-z0-9]*(?:-[a-z0-9]+)*:[A-Za-z0-9:._-]+$"},beforeFact:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"}}}}},subject:{type:"object",additionalProperties:!1,required:["resourceCode","factProjection","summaryFields"],properties:{resourceCode:{type:"string",pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},factProjection:{type:"object",minProperties:1,maxProperties:64,propertyNames:{pattern:"^[A-Za-z][A-Za-z0-9_.]{0,127}$"},additionalProperties:{type:"string",pattern:"^[A-Za-z][A-Za-z0-9_]{0,62}$"}},summaryFields:{type:"array",maxItems:16,uniqueItems:!0,items:Ep}}},startAt:G,inputSchema:{type:"object",required:["type","additionalProperties"],properties:{type:{const:"object"},additionalProperties:{const:!1}}},readability:Ip,organizationContext:{type:"object",additionalProperties:!1,properties:{department:{type:"object",additionalProperties:!1,required:["source"],properties:{source:{enum:["none","user_primary_department","choose_if_multiple","always_choose","fixed","from_input","from_role_scope"]},required:{type:"boolean"},value:{type:"string"},path:{type:"string"},dimension:{type:"string"}}}}},nodes:{type:"object",minProperties:1,maxProperties:200,additionalProperties:bp}}},Np={$id:ms,type:"object",additionalProperties:!1,required:["schemaVersion","workflowCode","bindings"],properties:{schemaVersion:{const:ms},workflowCode:G,bindings:{type:"object",maxProperties:200,additionalProperties:{oneOf:[Dt,Sr]}}}};var gr=["definition.read","draft.edit","publication.publish","handling.configure"],Ty=2,wp={memberships:400,grants:512,targets:200,receiptGrantIds:8};function Cy(e){let t=new Set(e.filter(n=>gr.includes(n)));return t.size&&t.add("definition.read"),gr.filter(n=>t.has(n))}function Sy(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/,o=/^[a-z][a-z0-9_-]{0,127}$/;return typeof t.subjectRoleCode=="string"&&t.subjectRoleCode.length<=100&&n.test(t.subjectRoleCode)&&typeof t.manageAllWorkflows=="boolean"&&Array.isArray(t.managedWorkflowCodes)&&t.managedWorkflowCodes.length<=wp.targets&&(t.manageAllWorkflows?t.managedWorkflowCodes.length===0:t.managedWorkflowCodes.length>0)&&t.managedWorkflowCodes.every(r=>typeof r=="string"&&o.test(r))&&new Set(t.managedWorkflowCodes).size===t.managedWorkflowCodes.length&&Array.isArray(t.actions)&&t.actions.length>0&&t.actions.length<=gr.length&&t.actions.every(r=>gr.includes(r))&&new Set(t.actions).size===t.actions.length&&typeof t.reason=="string"&&t.reason.trim().length>0&&t.reason.length<=1e3&&Object.keys(t).every(r=>["subjectRoleCode","manageAllWorkflows","managedWorkflowCodes","actions","reason"].includes(r))}var ky=316224e5;function Rp(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===2&&e.kind==="database-accepted-time"&&Object.hasOwn(e,"offsetMilliseconds")&&Number.isSafeInteger(e.offsetMilliseconds)&&Math.abs(e.offsetMilliseconds)<=316224e5}function Ly(e=0){let t={kind:"database-accepted-time",offsetMilliseconds:e};if(!Rp(t))throw new Error("DATA_TRANSACTION_ACCEPTED_TIME_VALUE_INVALID");return t}var Py="38472b05b5129138cbaf87116049a43a6f2fec0cc612567a4d55895e904afebd";export{Ca as APPLICATION_AGENT_LIMITS_V2,kn as AuthenticatedPublicReadContractError,_o as DATA_AUDIT_METADATA_FIELDS,zE as DATA_BUSINESS_COMMAND_INTENT_MAX_BYTES,Xf as DATA_BUSINESS_COMMAND_RESOLUTION_SCHEMA,qE as DATA_BUSINESS_COMMAND_SCHEMA,zi as DATA_EVENT_TYPES_V2,Lm as DATA_FORM_DRAFT_MAX_BYTES,uo as DATA_RESOURCE_MAX_FIELDS,Fr as DATA_SUBTABLE_DEFAULT_TOTAL_ROWS,lt as DATA_SUBTABLE_MAX_ROWS,en as DATA_SUBTABLE_MAX_TOTAL_ROWS,ml as DATA_SYSTEM_SORT_FIELD_CODES,km as DATA_TRANSACTION_MAX_BYTES,Ks as DATA_TRANSACTION_MAX_OPERATIONS,Zf as DATA_TRANSACTION_RECORD_SET_MAX_RECORDS,ky as DATA_TRANSACTION_TIME_MAX_OFFSET_MILLISECONDS,eA as DATE_EVENT_RESERVED_DATA_FIELDS_V2,yI as DEVELOPMENT_BACKEND_CONNECTION_TTL_SECONDS,OI as DEVELOPMENT_BACKEND_ENDPOINT_PATTERN,fI as DEVELOPMENT_BACKEND_FEATURE,mI as DEVELOPMENT_BACKEND_INVOCATION_FEATURE,gI as DEVELOPMENT_BACKEND_INVOCATION_MAX_REQUEST_BYTES,_I as DEVELOPMENT_BACKEND_INVOCATION_MAX_RESPONSE_BYTES,np as DEVELOPMENT_BACKEND_INVOCATION_SCHEMA,II as DEVELOPMENT_BACKEND_MAX_INFLIGHT,EI as DEVELOPMENT_BACKEND_MAX_REQUEST_BYTES,AI as DEVELOPMENT_BACKEND_MAX_RESPONSE_BYTES,pI as DEVELOPMENT_BACKEND_SCHEMA,aI as DEVELOPMENT_CONFIGURATION_ENDPOINT,sI as DEVELOPMENT_CONFIGURATION_FEATURE,Ic as DEVELOPMENT_CONFIGURATION_MANIFEST_SCHEMA,ep as DEVELOPMENT_CONFIGURATION_SCHEMA,Ko as DateEventProjectionV2Error,ss as DevelopmentConfigurationContractError,wi as EventWorkerEffectContractError,nu as FIELD_VALUE_SCHEMAS,wn as ManagedConcurrencyContractError,_e as NATIVE_ARTIFACT_CAPACITY_V2,Py as NATIVE_CONFIGURATION_VALIDATOR_DIGEST,q as NATIVE_CONTRACT_CAPACITY_V2,Kg as NATIVE_DATA_POLICY_EXPRESSION_MAX_CLAUSES,Ug as NATIVE_DATA_POLICY_EXPRESSION_MAX_DEPTH,Mg as NATIVE_DATA_POLICY_EXPRESSION_MAX_GROUP_ITEMS,Bg as NATIVE_DATA_POLICY_EXPRESSION_MAX_LEAVES,qg as NATIVE_DATA_POLICY_EXPRESSION_MAX_OCCURRENCES,gl as NATIVE_DATA_QUERY_OPERATORS_V2,ya as NATIVE_DIRECTORY_ROLE_SOURCE_LIMITS,fn as NATIVE_HIGH_DENSITY_ARTIFACT_CAPACITY_V2,$E as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_BYTES,PE as NATIVE_ROLE_MEMBERSHIP_BATCH_MAX_ITEMS,n_ as NATIVE_UNIQUE_KEY_MAX_BYTES,Ba as NATIVE_UNIQUE_KEY_NORMALIZERS,gr as NATIVE_WORKFLOW_MANAGEMENT_ACTIONS,mi as NativeApplicationAgentContractError,Gi as NativeConfigurationCompilerError,We as NativeDataFieldContractV2Error,Dn as NativeDataPolicyExpressionV2Error,rn as NativeDecimalLifecycleContractError,xo as NativeEventActionContractError,Cn as NativeOrganizationAuthorizationError,Te as NativeParentReadPolicyError,es as NativeRoleMembershipBatchInputError,di as NativeScopeSourceFieldPathV2Error,vn as NativeUniqueKeyContractError,rl as OPENXIANGDA_NATIVE_DATA_FIELD_TYPES_V2,It as OPENXIANGDA_NATIVE_DATA_SURFACE_KEYS_V2,Zr as OPENXIANGDA_NATIVE_DRAFT_STATE_KEYS_V2,zr as OPENXIANGDA_NATIVE_SYSTEM_FIELDS_V2,tn as OPENXIANGDA_NATIVE_SYSTEM_FIELD_MAP_V2,RI as RICH_TEXT_POLICY_V2,Cm as USER_CANDIDATE_MAX_SELECTIONS,nl as USER_CANDIDATE_SCOPE_FIELD_TYPES,$t as UserCandidateContractError,sd as WORKFLOW_APPROVAL_EMPTY_PROVIDERS,H_ as WORKFLOW_APPROVED_DELEGATION_MAX_BYTES,J_ as WORKFLOW_APPROVED_DELEGATION_MAX_REQUESTS,nd as WORKFLOW_AUTOMATIC_CC_DEFAULT_RECIPIENTS,od as WORKFLOW_AUTOMATIC_CC_MAX_RECIPIENTS,_u as WORKFLOW_AUTOMATIC_CC_PROVIDERS,Ir as WORKFLOW_BUSINESS_STEP_EVENT,Vp as WORKFLOW_BUSINESS_STEP_EVENTS,Wp as WORKFLOW_BUSINESS_STEP_FACTS_KEY,br as WORKFLOW_BUSINESS_STEP_MAX_BYTES,xc as WORKFLOW_BUSINESS_STEP_MAX_RECEIPT_BYTES,yn as WORKFLOW_CONDITIONAL_ASSIGNMENT_LEAF_PROVIDERS,Cr as WORKFLOW_CONDITIONAL_ASSIGNMENT_MAX_BYTES,no as WORKFLOW_CONDITIONAL_ASSIGNMENT_MAX_CASES,Nt as WORKFLOW_CONFIGURABLE_OPERATIONS,Bo as WORKFLOW_CONFIGURABLE_PROVIDERS,Ty as WORKFLOW_DESIGNER_CLIENT_CONTRACT,Mn as WORKFLOW_EVENT_TYPES_V2,Vr as WORKFLOW_LAUNCH_MAX_INPUTS,hu as WORKFLOW_LAUNCH_PREFLIGHT_PROVIDERS,wp as WORKFLOW_MANAGEMENT_LIMITS,lu as WORKFLOW_PARALLEL_MAX_BRANCHES,cu as WORKFLOW_PARALLEL_MIN_BRANCHES,vp as WORKFLOW_PLATFORM_NOTIFY_CAPABILITY,Fc as WORKFLOW_PLATFORM_NOTIFY_HANDLER,Vc as WORKFLOW_PLATFORM_NOTIFY_INPUT_SCHEMA,Wc as WORKFLOW_PLATFORM_NOTIFY_OUTPUT_SCHEMA,x_ as WORKFLOW_REJECTION_NOTIFICATION_MAX_BYTES,bu as WORKFLOW_REJECTION_NOTIFICATION_SCHEMA,Sp as WORKFLOW_ROLE_UNION_MAX_ROLES,Jp as WORKFLOW_ROUTING_MAX_BYTES,Gp as WORKFLOW_ROUTING_MAX_MATCHED_RULES,zp as WORKFLOW_ROUTING_MAX_RULES,fp as WORKFLOW_SOURCE_BUNDLE_MAX_BYTES,kc as WORKFLOW_SOURCE_BUNDLE_SCHEMA,us as WORKFLOW_SOURCE_BUNDLE_V2_SCHEMA,kE as WORKFLOW_STEP_DATA_COMMAND_SCHEMA,Gf as WORKFLOW_STEP_DATA_RESOLUTION_SCHEMA,Cu as WORKFLOW_TASK_PAGE_DEFINITION_MAX_BYTES,Vi as WORKFLOW_TASK_PAGE_MAX_BYTES,Tu as WORKFLOW_TASK_PAGE_MAX_FIELDS,yd as WORKFLOW_TASK_SUBTABLE_MAX_ROWS,Ed as WORKFLOW_TASK_SUBTABLE_MAX_TOTAL_ROWS,st as WorkflowTaskPageError,Su as applyWorkflowTaskPageValues,iA as applyWorkflowTaskSubtableRows,ou as assertApplicationAgentInstructionPathV2,tp as assertDevelopmentConfigurationManifest,lI as assertDevelopmentConfigurationResult,FE as assertNativeRoleMembershipBatchInput,Hg as assertWorkflowNativeStageGuard,ja as assertWorkflowNativeStagePolicy,Yg as assertWorkflowNativeStageSourceGuard,Go as assertWorkflowOwnedSubjectCreate,wd as assertWorkflowOwnedSubjectCreateResources,up as buildResourceWhere,GE as canonicalDataBusinessIntent,JI as classifyWorkflowAdoption,my as classifyWorkflowSourceDeployment,fr as compileAdvancedWhere,Sa as compileApplicationAgentsV2,Ya as compileEventWorkerEffect,wE as compileNativeApplicationConfiguration,Xa as compileNativeEventAction,ef as compileNativeEventCapturePlansV2,Qu as compileRequiredPlatformCapabilitiesV3,Nr as compileWorkflowBusinessStepHandlers,dI as createDevelopmentConfigurationManifest,cp as createWorkflowHumanNode,fo as dataOwnedRowLimit,Ly as databaseAcceptedTime,tA as dateEventProjectionEnvelopeSchemaV2,Ad as dateEventProjectionFieldsV2,fi as departmentReferenceValueSchema,op as developmentBackendBase64Bytes,ap as developmentBackendInvocationHeadersValid,NI as developmentBackendInvocationRequestValid,hI as developmentBackendInvocationRevision,rp as developmentBackendOperationMatches,cI as developmentConfigurationKey,bg as directoryRoleSourceSchema,lp as editWorkflowDesignerDefinition,vs as evaluateWorkflowExpression,wt as evaluateWorkflowTaskPageExpression,u_ as eventWorkerEffectSignatureContent,Ro as fieldValueSchemaForDefinition,V_ as formatWorkflowCompletionDeadline,jo as formatWorkflowExpression,Kp as formatWorkflowSupervisorChain,Cd as generatedCrudCapabilityOperations,Qs as hasDataAuditReadPolicy,yi as hasNativeParentReadPolicy,rt as inspectWorkflowParallel,Vt as isDataAuditMetadataField,On as isDataOwnedRowLimit,Ao as isDataSystemSortField,Rp as isDataTransactionAcceptedTimeValue,YE as isDataTransactionActorAuthorityGuard,nI as isDataTransactionRecordSetMatchGuard,jm as isNativeDataQueryOperatorV2,go as isNativeMultiValueFieldV2,Sy as isWorkflowManagementGrantRequest,ie as isWorkflowPlatformNotify,j_ as isWorkflowRejectionNotificationSnapshot,XE as matchesDataActorAuthorityMembership,Ig as materializeNativeDataQueryPathTypesV2,Na as nativeAgentFieldHintSchemaV2,au as nativeAgentFieldSelectorV2,an as nativeDataPolicyExpressionLeavesV2,ka as nativeDataPolicyExpressionToCnfV2,yg as nativeDataQueryPathPlanV2,Mm as nativeFieldAggregatePlanV2,dg as nativeFieldColumnDefinitionV2,cg as nativeFieldDefaultSqlV2,lg as nativeFieldHasDefaultV2,mg as nativeFieldIndexStatementsV2,Et as nativeFieldRequiresCreateInputV2,pg as nativeFieldSequenceGrantStatementsV2,fg as nativeFieldSequenceOwnershipStatementsV2,ug as nativeFieldSequenceStatementsV2,oa as nativeFieldSupportsFilterV2,Um as nativeFieldSupportsOperatorV2,Yr as nativeFieldSupportsSearchV2,Nn as nativeFieldSupportsSortV2,na as nativeOperatorsForFieldV2,Vl as nativePhysicalFieldV2,ag as nativePhysicalFieldsV2,yt as nativePhysicalObjectNameV2,Ag as nativeScopeSourceFieldValueV2,Ea as nativeScopeSourceGrantPathSupportedV2,ci as nativeScopeSourceSubjectPathSupportedV2,gg as nativeSubtableConstraintStatementsV2,qa as nativeUniqueKeysContractVersion,o_ as nativeUniqueKeysJsonSchema,Ei as normalizeDataMutationGrants,uA as normalizeWorkflowOwnedSubjectCreate,JE as parseDataBusinessCommandResolution,lo as parseDataFieldUserCandidates,si as parseDecimalReservationLifecycle,bn as parseNativeDataFieldsV2,Zs as parseNativeDataResourceInvariantsV2,pu as parseNativeParentReadPolicy,Ka as parseNativeUniqueKeys,LE as parseWorkflowStepDataResolution,pi as projectDataResourceView,ni as projectNativeDataResourceViewV2,v_ as projectWorkflowConfiguredAssignment,Mo as projectWorkflowGraph,rd as projectWorkflowNodePolicy,oy as projectWorkflowSourceAssignment,FI as pruneWorkflowCanvasBindings,Re as quoteNativeIdentifierV2,sA as refreshWorkflowTaskPageFacts,xr as requiresAggregateOwnedSubtableCapacity,Kr as requiresDateTimeMinutePrecision,bI as requiresDevelopmentBackendCredential,Jo as requiresExtendedArtifactCapacity,Mi as requiresExtendedConfigurationBytes,Ui as requiresExtendedDeclarationCapacity,Wr as requiresExtendedFieldCapacity,jr as requiresExtendedOwnedSubtableCapacity,ji as requiresExtendedRoleCapacity,Ho as requiresHighDensityArtifactCapacity,qr as requiresOwnedSubtableMinimumRows,$r as requiresUserCandidateLaunchScope,kp as requiresWorkflowRoleInputSelection,Dp as requiresWorkflowRoleUnion,$o as resolveNativeParentReadBinding,Rn as resolveNativeScopeSourceFieldPathV2,K_ as resolveWorkflowCommandHandler,ol as resolveWorkflowUserCandidates,ba as resourceReferenceValueSchema,ry as restoreWorkflowSourceAssignment,Xp as selectWorkflowAssignmentRoutingRules,Nm as selectWorkflowConditionalAssignment,vm as serializedDataBytes,Sm as userCandidateScopeValue,li as userReferenceValueSchema,Ma as validateAuthenticatedPublicRead,fa as validateDecimalReservationLifecycles,l_ as validateEventWorkerMutationPlan,c_ as validateEventWorkerQuery,la as validateManagedConcurrency,sa as validateNativeDataDraftStateV2,Xs as validateNativeDataResourceReferencesV2,ti as validateNativeDataResourceSurfaceV2,Oa as validateNativeOrganizationAuthorization,$a as validateNativeParentReadPolicies,Ms as validateUserCandidateReferences,ki as validateWorkflowAdministration,Li as validateWorkflowApprovalEmptyPolicy,gd as validateWorkflowApprovedDelegation,Lr as validateWorkflowAssignmentLeafFacts,Ts as validateWorkflowAssignmentRoutingBindings,Yt as validateWorkflowAssignmentRoutingPolicy,Hp as validateWorkflowAssignmentRoutingRules,Mc as validateWorkflowAuthoringSteps,Si as validateWorkflowAutomaticCc,jp as validateWorkflowBusinessStepHandlerContract,xp as validateWorkflowBusinessStepRequest,jc as validateWorkflowBusinessStepResult,Jt as validateWorkflowBusinessStepSchema,bs as validateWorkflowBusinessStepSubscriptions,eo as validateWorkflowBusinessSteps,hc as validateWorkflowCanvasBinding,bc as validateWorkflowCanvasHuman,fd as validateWorkflowCommandHandlers,cd as validateWorkflowCompletionDeadlines,Zt as validateWorkflowConditionalAssignment,De as validateWorkflowConditionalAssignmentShape,Xt as validateWorkflowConditionalBindingDefinition,_d as validateWorkflowCorrections,wc as validateWorkflowDesignerCapabilities,as as validateWorkflowDesignerDocument,Po as validateWorkflowHandlingNodes,Vn as validateWorkflowInitiatorApprovalPolicy,Qa as validateWorkflowInstanceCommandPolicies,Pi as validateWorkflowLaunchPreflight,Di as validateWorkflowNodeConfigurationPatch,vo as validateWorkflowParallel,Ls as validateWorkflowPeopleSourceTemplates,Qn as validateWorkflowPlatformNotify,ed as validateWorkflowReadability,ud as validateWorkflowRejectionNotification,Do as validateWorkflowReminders,yc as validateWorkflowReturnEligibility,ko as validateWorkflowReturnPolicies,Xn as validateWorkflowRoleInputSelection,qt as validateWorkflowRoleUnion,Dc as validateWorkflowSourceAssignment,gp as validateWorkflowSourceBundle,Lt as validateWorkflowStandardAssignment,Ht as validateWorkflowSupervisorChainBinding,At as validateWorkflowSupervisorChains,zo as validateWorkflowTaskPages,Bs as validateWorkflowUserCandidateBindings,$_ as workflowApprovalCanSkip,Y_ as workflowApprovedDelegationRequests,co as workflowAssignmentLeafBinding,ae as workflowAssignmentLeaves,Yp as workflowAssignmentRoutingFacts,Rs as workflowAssignmentRoutingPolicySchema,Gc as workflowAssignmentRoutingSemantic,dr as workflowAuthoringCatalog,ad as workflowBindingAllowsEmptyUsers,Yn as workflowBindingRoleCodes,Np as workflowBindingSchema,B_ as workflowBusinessCommandInvocationSchema,_t as workflowBusinessStepFactSchema,BE as workflowBusinessStepHandlerDigest,Up as workflowBusinessStepInput,Uc as workflowBusinessStepPath,ME as workflowBusinessStepReceiptSignatureSuffix,Gt as workflowBusinessStepValueMatches,zn as workflowCanvasBindingKey,so as workflowConditionalAssignmentFact,Sr as workflowConditionalAssignmentSchema,hp as workflowDefinitionSchema,Hf as workflowDelegationMutationRequestSchema,lr as workflowDesignerTargets,HI as workflowDesignerVariables,Fn as workflowExpressionPaths,Lo as workflowForwardTargets,Oc as workflowHumanOperations,w_ as workflowInitiatorApprovalCanComplete,E_ as workflowInstanceCommandDeadlineError,__ as workflowInstanceTerminateCapabilityAllowed,A_ as workflowInstanceWithdrawalReasonRequired,Cy as workflowManagementActions,Xg as workflowNativeStagePolicySchema,cn as workflowNodeAllowedOperations,Ou as workflowNodeAssignmentUsesReleasedSource,Pp as workflowNotificationBinding,Eu as workflowOperationCommentRequired,ln as workflowOperationMinimumOpinion,xt as workflowOperationOpinion,Iu as workflowOperationReasonRequired,lA as workflowOwnedSubjectCreateSchema,io as workflowPeopleSourceTemplateAllows,Xc as workflowPeopleSourceTemplateMatches,Za as workflowPolicyTimestamp,Vg as workflowPositionActive,Bi as workflowProducedEventTypes,dp as workflowReturnEligibility,Pg as workflowReturnTargetPolicy,ot as workflowReturnTargets,_s as workflowRoleCodesSchema,mt as workflowSourceDigestEqual,gy as workflowSourceImportDrift,iy as workflowSourceNamedAssignmentSummary,mp as workflowSourceReferences,py as workflowSourceStatus,hd as workflowTaskPageFieldState,aA as workflowTaskPageReplayCoversInvalidation,L_ as workflowTaskSaveEnabled,rA as workflowTaskSubtableRows,gu as workflowVariableLabel};