@microi.net/cli 5.8.2 → 5.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/.codebuddy-plugin/marketplace.json +2 -2
  2. package/.codebuddy-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/.workbuddy-plugin/marketplace.json +2 -2
  5. package/.workbuddy-plugin/plugin.json +1 -1
  6. package/assets/build-meta.json +4 -4
  7. package/cordis.patch.yml +1 -1
  8. package/package.json +1 -1
  9. package/scripts/mcp-server.js +3 -3
  10. package/scripts/microi-skills.meta.json +217 -217
  11. package/skills/.microi-skills-version.json +2 -2
  12. package/skills/.progressive-disclosure-manifest.json +35 -35
  13. package/skills/ai-engine/references/self-hosted-digital-human.md +14 -0
  14. package/skills/app-store/SKILL.md +71 -0
  15. package/skills/dos-orm/SKILL.md +1 -0
  16. package/skills/job-engine/SKILL.md +4 -0
  17. package/skills/microi-client-frontend/SKILL.md +4 -1
  18. package/skills/microi-codex/SKILL.md +4 -1
  19. package/skills/microi-deployment/SKILL.md +7 -7
  20. package/skills/microi-form-engine/SKILL.md +5 -3
  21. package/skills/microi-microservice/SKILL.md +3 -0
  22. package/skills/module-engine/SKILL.md +5 -0
  23. package/skills/playwright-e2e/SKILL.md +2 -3
  24. package/skills/ui-design/references/motion-and-media.md +7 -0
  25. package/skills/unity-integration/SKILL.md +16 -0
  26. package/skills/v8-crud-api/SKILL.md +2 -1
  27. package/skills/v8-file-upload/SKILL.md +4 -4
  28. package/skills/v8-file-upload/references/progressive-01-/345/205/254/346/234/211/346/241/266-vs-/347/247/201/346/234/211/346/241/266.md +24 -1
  29. package/skills/v8-saas-multi-tenant/SKILL.md +37 -0
  30. package/skills/v8-security/SKILL.md +4 -0
  31. package/skills/v8-utilities/SKILL.md +8 -0
  32. package/skills/workspace-conventions/SKILL.md +3 -3
  33. package/skills/workspace-conventions/references/progressive-02-microi-net-api-/346/234/254/345/234/260/345/220/257/345/212/250/347/272/246/345/256/232.md +7 -6
@@ -130,14 +130,14 @@ Content-Type: application/octet-stream\r
130
130
  ]))`;continue}}if(r.s&&n[c]==="."){i+=a?`${n[c]}\r
131
131
  `:`[${n[c]}\r
132
132
  ]`;continue}i+=n[c],n[c]==="\\"?o=!0:a&&n[c]==="]"?a=!1:!a&&n[c]==="["&&(a=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function Pd(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===M.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,i)=>({...n,[i]:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??Ye(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===M.ZodString&&t.keyType._def.checks?.length){let{type:n,...i}=Rd(t.keyType._def,e);return{...r,propertyNames:i}}else{if(t.keyType?._def.typeName===M.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===M.ZodBranded&&t.keyType._def.type._def.typeName===M.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...i}=Ad(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function vP(t,e){if(e.mapStrategy==="record")return Pd(t,e);let r=Q(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ye(e),n=Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ye(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function xP(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),i=Array.from(new Set(n.map(o=>typeof o)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function wP(t){return t.target==="openAi"?void 0:{not:Ye({...t,currentPath:[...t.currentPath,"not"]})}}function _P(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Yc={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function EP(t,e){if(e.target==="openApi3")return SP(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Yc&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,o)=>{let a=Yc[o._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((i,o)=>{let a=typeof o._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":if(o._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){let i=n.filter((o,a,s)=>s.indexOf(o)===a);return{type:i.length>1?i:i[0],enum:r.reduce((o,a)=>o.includes(a._def.value)?o:[...o,a._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(o=>!n.includes(o))],[])};return SP(t,e)}var SP=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>Q(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function kP(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Yc[t.innerType._def.typeName],nullable:!0}:{type:[Yc[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Q(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function TP(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",yv(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}function CP(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},i=[],o=t.shape();for(let s in o){let c=o[s];if(c===void 0||c._def===void 0)continue;let l=cH(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=Q(c._def,{...e,currentPath:[...e.currentPath,"properties",s],propertyPath:[...e.currentPath,"properties",s]});u!==void 0&&(n.properties[s]=u,l||i.push(s))}i.length&&(n.required=i);let a=sH(t,e);return a!==void 0&&(n.additionalProperties=a),n}function sH(t,e){if(t.catchall._def.typeName!=="ZodNever")return Q(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function cH(t){try{return t.isOptional()}catch{return!0}}var IP=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Q(t.innerType._def,e);let r=Q(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ye(e)},r]}:Ye(e)};var AP=(t,e)=>{if(e.pipeStrategy==="input")return Q(t.in._def,e);if(e.pipeStrategy==="output")return Q(t.out._def,e);let r=Q(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Q(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function RP(t,e){return Q(t.type._def,e)}function PP(t,e){let n={type:"array",uniqueItems:!0,items:Q(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function $P(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Q(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Q(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function OP(t){return{not:Ye(t)}}function NP(t){return Ye(t)}var MP=(t,e)=>Q(t.innerType._def,e);var DP=(t,e,r)=>{switch(e){case M.ZodString:return Rd(t,r);case M.ZodNumber:return TP(t,r);case M.ZodObject:return CP(t,r);case M.ZodBigInt:return uP(t,r);case M.ZodBoolean:return pP();case M.ZodDate:return bv(t,r);case M.ZodUndefined:return OP(r);case M.ZodNull:return _P(r);case M.ZodArray:return lP(t,r);case M.ZodUnion:case M.ZodDiscriminatedUnion:return EP(t,r);case M.ZodIntersection:return gP(t,r);case M.ZodTuple:return $P(t,r);case M.ZodRecord:return Pd(t,r);case M.ZodLiteral:return yP(t,r);case M.ZodEnum:return hP(t);case M.ZodNativeEnum:return xP(t);case M.ZodNullable:return kP(t,r);case M.ZodOptional:return IP(t,r);case M.ZodMap:return vP(t,r);case M.ZodSet:return PP(t,r);case M.ZodLazy:return()=>t.getter()._def;case M.ZodPromise:return RP(t,r);case M.ZodNaN:case M.ZodNever:return wP(r);case M.ZodEffects:return mP(t,r);case M.ZodAny:return Ye(r);case M.ZodUnknown:return NP(r);case M.ZodDefault:return fP(t,r);case M.ZodBranded:return Ad(t,r);case M.ZodReadonly:return MP(t,r);case M.ZodCatch:return dP(t,r);case M.ZodPipeline:return AP(t,r);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(n=>{})(e)}};function Q(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==aP)return s}if(n&&!r){let s=lH(n,e);if(s!==void 0)return s}let i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);let o=DP(t,t.typeName,e),a=typeof o=="function"?Q(o(),e):o;if(a&&uH(t,e,a),e.postProcess){let s=e.postProcess(a,t,e);return i.jsonSchema=a,s}return i.jsonSchema=a,a}var lH=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Id(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ye(e)):e.$refStrategy==="seen"?Ye(e):void 0}},uH=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var wv=(t,e)=>{let r=cP(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:Q(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Ye(r)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=Q(t._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??Ye(r),a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(o.title=a),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let s=i===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:o}};return r.target==="jsonSchema7"?s.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(s.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in s||"oneOf"in s||"allOf"in s||"type"in s&&Array.isArray(s.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),s};function pH(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function _v(t,e){return Pn(t)?Jh(t,{target:pH(e?.target),io:e?.pipeStrategy??"input"}):wv(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Sv(t){let r=Ri(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ns(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ev(t,e){let r=Ai(t,e);if(!r.success)throw r.error;return r.data}var dH=6e4,$d=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Su,r=>{this._oncancel(r)}),this.setNotificationHandler(ku,r=>{this._onprogress(r)}),this.setRequestHandler(Eu,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Tu,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new U(G.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Iu,async(r,n)=>{let i=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(s.type==="response"||s.type==="error"){let c=s.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),s.type==="response")u(c);else{let p=c,f=new U(p.error.code,p.error.message,p.error.data);u(f)}else{let p=s.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(s.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new U(G.InvalidParams,`Task not found: ${o}`);if(!Pi(a.status))return await this._waitForTaskUpdate(o,n.signal),await i();if(Pi(a.status)){let s=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...s,_meta:{...s._meta,[di]:{taskId:o}}}}return await i()};return await i()}),this.setRequestHandler(Au,async(r,n)=>{try{let{tasks:i,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:o,_meta:{}}}catch(i){throw new U(G.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Pu,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new U(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(Pi(i.status))throw new U(G.InvalidParams,`Cannot cancel task in terminal status: ${i.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new U(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(i){throw i instanceof U?i:new U(G.InvalidRequest,`Failed to cancel task: ${i instanceof Error?i.message:String(i)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,i,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:i})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),U.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let i=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{i?.(o,a),Xs(o)||v1(o)?this._onresponse(o):ig(o)?this._onrequest(o,a):b1(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=U.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,i=this._transport,o=e.params?._meta?.[di]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:u,timestamp:Date.now()},i?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):i?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let s=h1(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,l={signal:a.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(a.signal.aborted)return;let p={relatedRequestId:e.id};o&&(p.relatedTask={taskId:o}),await this.notification(u,p)},sendRequest:async(u,p,f)=>{if(a.signal.aborted)throw new U(G.ConnectionClosed,"Request was cancelled");let m={...f,relatedRequestId:e.id};o&&!m.relatedTask&&(m.relatedTask={taskId:o});let h=m.relatedTask?.taskId??o;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,p,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:s?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{s&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(a.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async u=>{if(a.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:G.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),o=this._progressHandlers.get(i);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&a&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),a(c);return}o(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Xs(e))n(e);else{let a=new U(e.error.code,e.error.message,e.error.data);n(a)}return}let i=this._responseHandlers.get(r);if(i===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Xs(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let s=a.task;typeof s.taskId=="string"&&(o=!0,this._taskProgressTokens.set(s.taskId,r))}}if(o||this._progressHandlers.delete(r),Xs(e))i(e);else{let a=U.fromError(e.error.code,e.error.message,e.error.data);i(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:i}=n??{};if(!i){try{yield{type:"result",result:await this.request(e,r,n)}}catch(a){yield{type:"error",error:a instanceof U?a:new U(G.InternalError,String(a))}}return}let o;try{let a=await this.request(e,da,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new U(G.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:s},Pi(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:s.status==="failed"?yield{type:"error",error:new U(G.InternalError,`Task ${o} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new U(G.InternalError,`Task ${o} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof U?a:new U(G.InternalError,String(a))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a,task:s,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=b=>{u(b)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(b){p(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),s&&(m.params={...m.params,task:s}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[di]:c}});let h=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a}).catch(_=>this._onerror(new Error(`Failed to send cancellation: ${_}`)));let v=b instanceof U?b:new U(G.RequestTimeout,String(b));u(v)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let v=Ai(r,b.result);v.success?l(v.data):u(v.error)}catch(v){u(v)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let g=n?.timeout??dH,y=()=>h(U.fromError(G.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(f,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let x=c?.taskId;if(x){let b=v=>{let _=this._responseHandlers.get(f);_?_(v):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(x,{type:"request",message:m,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(f),u(v)})}else this._transport.send(m,{relatedRequestId:i,resumptionToken:o,onresumptiontoken:a}).catch(b=>{this._cleanupTimeout(f),u(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Cu,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},Ru,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},w1,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let s={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[di]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:s,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let s={...e,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[di]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[di]:r.relatedTask}}}),await this._transport.send(a,r)}setRequestHandler(e,r){let n=Sv(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,o)=>{let a=Ev(e,i);return Promise.resolve(r(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Sv(e);this._notificationHandlers.set(n,i=>{let o=Ev(e,i);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let i=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,i)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let i of n)if(i.type==="request"&&ig(i.message)){let o=i.message.id,a=this._requestResolvers.get(o);a?(a(new U(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(e);i?.pollInterval&&(n=i.pollInterval)}catch{}return new Promise((i,o)=>{if(r.aborted){o(new U(G.InvalidRequest,"Request cancelled"));return}let a=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(a),o(new U(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async i=>{if(!e)throw new Error("No request provided");return await n.createTask(i,e.id,{method:e.method,params:e.params},r)},getTask:async i=>{let o=await n.getTask(i,r);if(!o)throw new U(G.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(i,o,a)=>{await n.storeTaskResult(i,o,a,r);let s=await n.getTask(i,r);if(s){let c=rc.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Pi(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,o,a)=>{let s=await n.getTask(i,r);if(!s)throw new U(G.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Pi(s.status))throw new U(G.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,o,a,r);let c=await n.getTask(i,r);if(c){let l=rc.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Pi(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function FP(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function zP(t,e){let r={...t};for(let n in e){let i=n,o=e[i];if(o===void 0)continue;let a=r[i];FP(a)&&FP(o)?r[i]={...a,...o}:r[i]=o}return r}var F4=Te(g0(),1),z4=Te(D4(),1);function SX(){let t=new F4.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,z4.default)(t),t}var gf=class{constructor(e){this._ajv=e??SX()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var yf=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let i=e.messages[e.messages.length-1],o=Array.isArray(i.content)?i.content:[i.content],a=o.some(u=>u.type==="tool_result"),s=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],l=c.some(u=>u.type==="tool_use");if(a){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==p.size||![...u].every(f=>p.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},oc,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),i=e.mode??"form";switch(i){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=i==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},ha,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function L4(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function j4(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var bf=class extends $d{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ic.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let o=this._loggingLevels.get(i);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new gf,this.setRequestHandler(sg,n=>this._oninitialize(n)),this.setNotificationHandler(cg,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(hg,async(n,i)=>{let o=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:a}=n.params,s=ic.safeParse(a);return s.success&&this._loggingLevels.set(o,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new yf(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=zP(this._capabilities,e)}setRequestHandler(e,r){let i=Ri(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let o=ns(i);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let s=async(c,l)=>{let u=Ai(ma,c);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new U(G.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=u.data,f=await Promise.resolve(r(c,l));if(p.task){let h=Ai(da,f);if(!h.success){let g=h.error instanceof Error?h.error.message:String(h.error);throw new U(G.InvalidParams,`Invalid task creation result: ${g}`)}return h.data}let m=Ai(zu,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new U(G.InvalidParams,`Invalid tools/call result: ${h}`)}return m.data};return super.setRequestHandler(e,s)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){j4(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&L4(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:d1.includes(r)?r:rg,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},_u)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],i=Array.isArray(n.content)?n.content:[n.content],o=i.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=a?Array.isArray(a.content)?a.content:[a.content]:[],c=s.some(l=>l.type==="tool_use");if(o){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(s.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(i.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},gg,r):this.request({method:"sampling/createMessage",params:e},oc,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let i=e;return this.request({method:"elicitation/create",params:i},ha,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let i=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:i},ha,r);if(o.action==="accept"&&o.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(o.content);if(!s.valid)throw new U(G.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(a){throw a instanceof U?a:new U(G.InternalError,`Error validating elicitation response: ${a instanceof Error?a.message:String(a)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},yg,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var q4=Symbol.for("mcp.completable");function E0(t){return!!t&&typeof t=="object"&&q4 in t}function V4(t){return t[q4]?.complete}var B4;(function(t){t.Completable="McpCompletable"})(B4||(B4={}));var vf=class t{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,r,n){if(e.length>r)throw new Error(`${n} exceeds maximum length of ${r} characters (got ${e.length})`)}get variableNames(){return this.parts.flatMap(e=>typeof e=="string"?[]:e.names)}constructor(e){t.validateLength(e,1e6,"Template"),this.template=e,this.parts=this.parse(e)}toString(){return this.template}parse(e){let r=[],n="",i=0,o=0;for(;i<e.length;)if(e[i]==="{"){n&&(r.push(n),n="");let a=e.indexOf("}",i);if(a===-1)throw new Error("Unclosed template expression");if(o++,o>1e4)throw new Error("Template contains too many expressions (max 10000)");let s=e.slice(i+1,a),c=this.getOperator(s),l=s.includes("*"),u=this.getNames(s),p=u[0];for(let f of u)t.validateLength(f,1e6,"Variable name");r.push({name:p,operator:c,names:u,exploded:l}),i=a+1}else n+=e[i],i++;return n&&r.push(n),r}getOperator(e){return["+","#",".","/","?","&"].find(n=>e.startsWith(n))||""}getNames(e){let r=this.getOperator(e);return e.slice(r.length).split(",").map(n=>n.replace("*","").trim()).filter(n=>n.length>0)}encodeValue(e,r){return t.validateLength(e,1e6,"Variable value"),r==="+"||r==="#"?encodeURI(e):encodeURIComponent(e)}expandPart(e,r){if(e.operator==="?"||e.operator==="&"){let a=e.names.map(c=>{let l=r[c];if(l===void 0)return"";let u=Array.isArray(l)?l.map(p=>this.encodeValue(p,e.operator)).join(","):this.encodeValue(l.toString(),e.operator);return`${c}=${u}`}).filter(c=>c.length>0);return a.length===0?"":(e.operator==="?"?"?":"&")+a.join("&")}if(e.names.length>1){let a=e.names.map(s=>r[s]).filter(s=>s!==void 0);return a.length===0?"":a.map(s=>Array.isArray(s)?s[0]:s).join(",")}let n=r[e.name];if(n===void 0)return"";let o=(Array.isArray(n)?n:[n]).map(a=>this.encodeValue(a,e.operator));switch(e.operator){case"":return o.join(",");case"+":return o.join(",");case"#":return"#"+o.join(",");case".":return"."+o.join(".");case"/":return"/"+o.join("/");default:return o.join(",")}}expand(e){let r="",n=!1;for(let i of this.parts){if(typeof i=="string"){r+=i;continue}let o=this.expandPart(i,e);o&&((i.operator==="?"||i.operator==="&")&&n?r+=o.replace("?","&"):r+=o,(i.operator==="?"||i.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let o of e.names)t.validateLength(o,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let o=0;o<e.names.length;o++){let a=e.names[o],s=o===0?"\\"+e.operator:"&";r.push({pattern:s+this.escapeRegExp(a)+"=([^&]+)",name:a})}return r}let n,i=e.name;switch(e.operator){case"":n=e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)";break;case"+":case"#":n="(.+)";break;case".":n="\\.([^/,]+)";break;case"/":n="/"+(e.exploded?"([^/,]+(?:,[^/,]+)*)":"([^/,]+)");break;default:n="([^/]+)"}return r.push({pattern:n,name:i}),r}match(e){t.validateLength(e,1e6,"URI");let r="^",n=[];for(let s of this.parts)if(typeof s=="string")r+=this.escapeRegExp(s);else{let c=this.partToRegExp(s);for(let{pattern:l,name:u}of c)r+=l,n.push({name:u,exploded:s.exploded})}r+="$",t.validateLength(r,1e6,"Generated regex pattern");let i=new RegExp(r),o=e.match(i);if(!o)return null;let a={};for(let s=0;s<n.length;s++){let{name:c,exploded:l}=n[s],u=o[s+1],p=c.replace("*","");l&&u.includes(",")?a[p]=u.split(","):a[p]=u}return a}};var EX=/^[A-Za-z0-9._-]{1,128}$/;function kX(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!EX.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,i,o)=>o.indexOf(n)===i);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function TX(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function k0(t){let e=kX(t);return TX(t,e.warnings),e.isValid}var xf=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let i={taskSupport:"required",...r.execution};if(i.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,i,r._meta,n)}};var wf=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new bf(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new xf(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ji(Fu)),this.server.assertCanSetRequestHandler(ji(ma)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Fu,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let i=rs(r.inputSchema);return i?_v(i,{strictUnions:!0,pipeStrategy:"input"}):CX})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let i=rs(r.outputSchema);i&&(n.outputSchema=_v(i,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(ma,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new U(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new U(G.InvalidParams,`Tool ${e.params.name} disabled`);let i=!!e.params.task,o=n.execution?.taskSupport,a="createTask"in n.handler;if((o==="required"||o==="optional")&&!a)throw new U(G.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!i)throw new U(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!i&&a)return await this.handleAutomaticTaskPolling(n,e,r);let s=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,s,r);return i||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof U&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let o=rs(e.inputSchema)??e.inputSchema,a=await Td(o,r);if(!a.success){let s="error"in a?a.error:"Unknown error",c=Cd(s);throw new U(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return a.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new U(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let i=rs(e.outputSchema),o=await Td(i,r.structuredContent);if(!o.success){let a="error"in o?o.error:"Unknown error",s=Cd(a);throw new U(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${s}`)}}async executeToolHandler(e,r,n){let i=e.handler;if("createTask"in i){if(!n.taskStore)throw new Error("No task store provided.");let a={...n,taskStore:n.taskStore};if(e.inputSchema){let s=i;return await Promise.resolve(s.createTask(r,a))}else{let s=i;return await Promise.resolve(s.createTask(a))}}if(e.inputSchema){let a=i;return await Promise.resolve(a(r,n))}else{let a=i;return await Promise.resolve(a(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let i=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,a={...n,taskStore:n.taskStore},s=i?await Promise.resolve(o.createTask(i,a)):await Promise.resolve(o.createTask(a)),c=s.task.taskId,l=s.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let p=await n.taskStore.getTask(c);if(!p)throw new U(G.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ji(Lu)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Lu,async e=>{switch(e.params.ref.type){case"ref/prompt":return C1(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return I1(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new U(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new U(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Al;let o=Ri(n.argsSchema)?.[e.params.argument.name];if(!E0(o))return Al;let a=V4(o);if(!a)return Al;let s=await a(e.params.argument.value,e.params.context);return H4(s)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(a=>a.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Al;throw new U(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=n.resourceTemplate.completeCallback(e.params.argument.name);if(!i)return Al;let o=await i(e.params.argument.value,e.params.context);return H4(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ji($u)),this.server.assertCanSetRequestHandler(ji(Ou)),this.server.assertCanSetRequestHandler(ji(Nu)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler($u,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([o,a])=>a.enabled).map(([o,a])=>({uri:o,name:a.name,...a.metadata})),i=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let a=await o.resourceTemplate.listCallback(r);for(let s of a.resources)i.push({...o.metadata,...s})}return{resources:[...n,...i]}}),this.server.setRequestHandler(Ou,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Nu,async(e,r)=>{let n=new URL(e.params.uri),i=this._registeredResources[n.toString()];if(i){if(!i.enabled)throw new U(G.InvalidParams,`Resource ${n} disabled`);return i.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let a=o.resourceTemplate.uriTemplate.match(n.toString());if(a)return o.readCallback(n,a,r)}throw new U(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ji(Mu)),this.server.assertCanSetRequestHandler(ji(Du)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Mu,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?IX(r.argsSchema):void 0}))})),this.server.setRequestHandler(Du,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new U(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new U(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let i=rs(n.argsSchema),o=await Td(i,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",l=Cd(c);throw new U(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let a=o.data,s=n.callback;return await Promise.resolve(s(a,r))}else{let i=n.callback;return await Promise.resolve(i(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let i;typeof n[0]=="object"&&(i=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(e,void 0,r,i,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let a=this._createRegisteredResourceTemplate(e,void 0,r,i,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}registerResource(e,r,n,i){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,i,o){let a={name:e,title:r,metadata:i,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==n&&(delete this._registeredResources[n],s.uri&&(this._registeredResources[s.uri]=a)),typeof s.name<"u"&&(a.name=s.name),typeof s.title<"u"&&(a.title=s.title),typeof s.metadata<"u"&&(a.metadata=s.metadata),typeof s.callback<"u"&&(a.readCallback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,r,n,i,o){let a={resourceTemplate:n,title:r,metadata:i,readCallback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=a)),typeof l.title<"u"&&(a.title=l.title),typeof l.template<"u"&&(a.resourceTemplate=l.template),typeof l.metadata<"u"&&(a.metadata=l.metadata),typeof l.callback<"u"&&(a.readCallback=l.callback),typeof l.enabled<"u"&&(a.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,r,n,i,o){let a={title:r,description:n,argsSchema:i===void 0?void 0:Mo(i),callback:o,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=a)),typeof s.title<"u"&&(a.title=s.title),typeof s.description<"u"&&(a.description=s.description),typeof s.argsSchema<"u"&&(a.argsSchema=Mo(s.argsSchema)),typeof s.callback<"u"&&(a.callback=s.callback),typeof s.enabled<"u"&&(a.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,i&&Object.values(i).some(c=>{let l=c instanceof pr?c._def?.innerType:c;return E0(l)})&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,r,n,i,o,a,s,c,l){k0(e);let u={title:r,description:n,inputSchema:U4(i),outputSchema:U4(o),annotations:a,execution:s,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&k0(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Mo(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Mo(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,i,o,a;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(T0(c))i=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!T0(r[0])&&(a=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(l=>typeof l=="object"&&l!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=r.shift()}}let s=r[0];return this._createRegisteredTool(e,void 0,n,i,o,a,{taskSupport:"forbidden"},void 0,s)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:i,description:o,inputSchema:a,outputSchema:s,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,i,o,a,s,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let i;r.length>1&&(i=r.shift());let o=r[0],a=this._createRegisteredPrompt(e,void 0,n,i,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:i,description:o,argsSchema:a}=r,s=this._createRegisteredPrompt(e,i,o,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},_f=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new vf(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},CX={type:"object",properties:{}};function J4(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Z4(t){return"_def"in t||"_zod"in t||J4(t)}function T0(t){return typeof t!="object"||t===null||Z4(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(J4)}function U4(t){if(t){if(T0(t))return Mo(t);if(!Z4(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function IX(t){let e=Ri(t);return e?Object.entries(e).map(([r,n])=>{let i=nP(n),o=iP(n);return{name:r,description:i,required:!o}}):[]}function ji(t){let r=Ri(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ns(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function H4(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Al={completion:{values:[],hasMore:!1}};var nt=Te(require("node:crypto"),1),Et=Te(require("node:fs"),1),KO=require("node:net"),qt=Te(require("node:path"),1);function K4(t,e){t.tool("microi_manage_server_private_secret","Discover/store third-party App Secret, ClientSecret and API keys (including Changjet/T+ ERP) in \u7CFB\u7EDF\u8BBE\u7F6E \u2192 \u5B89\u5168\u4E0E\u670D\u52A1\u63A5\u5165. Use this EXISTING facility before proposing new server code/configuration. List returns metadata only. Save encrypts through the trusted settings endpoint and reads back HasSecret. Backend V8 uses V8.SysConfig.ServerPrivateSettings[ConfigKey]; frontend V8 and V8.OsClientModel cannot read it. Requires an interactive tenant administrator session; access-key sessions are rejected. No reveal or delete is exposed.",{action:d.enum(["List","Save"]),configKey:d.string().min(1).max(200).optional().describe("Stable key, e.g. Integration.Changjet.AppSecret."),value:d.string().min(1).max(1048576).optional().describe("Save only: user-supplied secret. Never include in source/output."),category:d.string().max(100).optional(),description:d.string().max(500).optional(),confirmExecution:d.string().optional().describe("Save requires SAVE:<ConfigKey>. Existing explicit user authorization is sufficient.")},async({action:r,configKey:n,value:i,category:o,description:a,confirmExecution:s})=>{let c=l=>({content:[{type:"text",text:l}],isError:!0});if(r==="Save"&&(!n||!i||s!==`SAVE:${n}`))return c("\u4FDD\u5B58\u9700\u8981 ConfigKey\u3001Value \u548C confirmExecution=SAVE:<ConfigKey>\u3002");try{if(r==="Save"){let f=await e.saveServerPrivateSecret({configKey:n,value:i,category:o,description:a});if(f.Code!==1)return c(`Secret \u4FDD\u5B58\u5931\u8D25\uFF08Code=${f.Code}\uFF09\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u79DF\u6237\u7BA1\u7406\u5458\u6743\u9650\u4E0E\u7CFB\u7EDF\u8BBE\u7F6E\u5E94\u7528\u3002`)}let l=await e.listServerPrivateSettings();if(l.Code!==1)return c("\u65E0\u6CD5\u56DE\u8BFB\u8BBE\u7F6E\uFF1B\u82E5\u521A\u4FDD\u5B58\uFF0C\u8BF7\u7528 List \u56DE\u8BFB\uFF0C\u4E0D\u8981\u91CD\u590D\u5199\u5165\u3002");let p=(Array.isArray(l.Data)?l.Data:[]).filter(f=>!n||f.ConfigKey===n).map(f=>({Id:f.Id,ConfigKey:f.ConfigKey,Category:f.Category,IsSecret:f.IsSecret,HasSecret:f.HasSecret,IsEnabled:f.IsEnabled}));return r==="Save"&&!p.some(f=>f.IsSecret&&f.HasSecret)?c("\u4FDD\u5B58\u54CD\u5E94\u5DF2\u8FD4\u56DE\uFF0C\u4F46 Secret \u72B6\u6001\u5C1A\u672A\u786E\u8BA4\uFF0C\u8BF7\u901A\u8FC7 List \u7EE7\u7EED\u56DE\u8BFB\u3002"):{content:[{type:"text",text:JSON.stringify({Data:p,Usage:"\u540E\u7AEF V8.SysConfig.ServerPrivateSettings[ConfigKey]\uFF1B\u7981\u6B62\u8BB0\u5F55\u3001\u8FD4\u56DE\u6216\u8F93\u51FA\u539F\u6587\u3002"},null,2)}]}}catch{return c("Secret \u64CD\u4F5C\u672A\u786E\u8BA4\u5B8C\u6210\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5\u5E76\u901A\u8FC7 List \u56DE\u8BFB\uFF1B\u4E0D\u4F1A\u81EA\u52A8\u91CD\u590D\u4FDD\u5B58\u6216\u8F93\u51FA\u79D8\u5BC6\u3002")}})}var C0=Te(require("node:crypto"),1),Bi=Te(require("node:fs"),1),Cr=Te(require("node:path"),1),I0=100*1024*1024,A0=Math.ceil(I0/3)*4+512,AX=new Set([".pdf",".png",".jpg",".jpeg",".gif",".bmp",".tif",".tiff",".webp"]);function W4(t){let e=String(t||"").trim();if(!e)return;if(e.includes("\0"))throw new Error("fileName \u4E0D\u80FD\u5305\u542B\u7A7A\u5B57\u7B26\u3002");let r=Cr.default.basename(e);if(!r||r==="."||r==="..")throw new Error("fileName \u65E0\u6548\u3002");if(r.length>255)throw new Error("fileName \u4E0D\u80FD\u8D85\u8FC7 255 \u4E2A\u5B57\u7B26\u3002");let n=Cr.default.extname(r).toLowerCase();if(n&&!AX.has(n))throw new Error("OCR \u4EC5\u652F\u6301 PDF\u3001PNG\u3001JPEG\u3001GIF\u3001BMP\u3001TIFF \u6216 WebP \u6587\u4EF6\u3002");return r}function RX(t){let e=t.trim(),r=/^data:[^;,]+;base64,/iu.test(e)?e.indexOf(","):-1,n=(r>=0?e.slice(r+1):e).replace(/\s/gu,"");if(!n)throw new Error("fileByteBase64 \u4E0D\u80FD\u4E3A\u7A7A\u3002");if(n.length>A0)throw new Error("OCR \u6587\u4EF6\u8D85\u8FC7 MCP 100 MB \u786C\u4E0A\u9650\u3002");if(n.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/u.test(n))throw new Error("fileByteBase64 \u4E0D\u662F\u6709\u6548\u7684 Base64 \u5185\u5BB9\u3002");let i=Buffer.from(n,"base64");if(i.toString("base64").replace(/=+$/u,"")!==n.replace(/=+$/u,""))throw new Error("fileByteBase64 \u4E0D\u662F\u89C4\u8303\u7684 Base64 \u5185\u5BB9\u3002");if(i.length===0||i.length>I0)throw new Error("OCR \u6587\u4EF6\u5FC5\u987B\u5927\u4E8E 0 \u5B57\u8282\u4E14\u4E0D\u8D85\u8FC7 MCP 100 MB \u786C\u4E0A\u9650\u3002");return i}function R0(t){let e=!!t.filePath?.trim(),r=!!t.fileByteBase64?.trim();if(e===r)throw new Error("filePath \u4E0E fileByteBase64 \u5FC5\u987B\u4E14\u53EA\u80FD\u63D0\u4F9B\u4E00\u4E2A\u3002");let n,i=W4(t.fileName);if(e){let o=String(t.filePath).trim();if(!Cr.default.isAbsolute(o))throw new Error("filePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let a=Bi.default.lstatSync(o);if(a.isSymbolicLink())throw new Error("filePath \u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\u3002");if(!a.isFile())throw new Error("filePath \u5FC5\u987B\u6307\u5411\u666E\u901A\u6587\u4EF6\u3002");if(a.size<=0||a.size>I0)throw new Error("OCR \u6587\u4EF6\u5FC5\u987B\u5927\u4E8E 0 \u5B57\u8282\u4E14\u4E0D\u8D85\u8FC7 MCP 100 MB \u786C\u4E0A\u9650\u3002");let s=W4(Cr.default.basename(o));if(!s||!Cr.default.extname(s))throw new Error("\u672C\u5730 OCR \u6587\u4EF6\u5FC5\u987B\u4F7F\u7528\u53D7\u652F\u6301\u7684\u6269\u5C55\u540D\u3002");if(i=i||s,n=Bi.default.readFileSync(o),n.length!==a.size)throw new Error("OCR \u6587\u4EF6\u5728\u8BFB\u53D6\u671F\u95F4\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002")}else n=RX(String(t.fileByteBase64));return{request:{FileByteBase64:n.toString("base64"),FileName:i,UseDocOrientationClassify:t.useDocOrientationClassify,UseDocUnwarping:t.useDocUnwarping,UseTextlineOrientation:t.useTextlineOrientation,TextRecScoreThresh:t.textRecScoreThresh,ReturnWordBox:t.returnWordBox},byteLength:n.length,sha256:C0.default.createHash("sha256").update(n).digest("hex"),auditFileName:i||"(unnamed OCR input)"}}function P0(t,e={}){if(!t)return null;let r=Math.max(1e3,Math.min(2e5,e.maxTextChars||1e5)),n=String(t.Text||""),i={Provider:t.Provider,TraceId:t.TraceId,FileName:t.FileName,FileType:t.FileType,Text:n.slice(0,r),AverageConfidence:t.AverageConfidence,PageCount:t.PageCount,ElapsedMilliseconds:t.ElapsedMilliseconds,TextTruncated:n.length>r};if(!e.includePages)return i;let o=r;return i.Pages=(t.Pages||[]).map(a=>{let s=String(a.Text||""),c=s.slice(0,o);return o=Math.max(0,o-c.length),c.length<s.length&&(i.TextTruncated=!0),{PageIndex:a.PageIndex,Text:c,AverageConfidence:a.AverageConfidence,...e.includeRegions?{Regions:a.Regions||[]}:{}}}),i}var $0=20*1024*1024,PX=25*1024*1024,O0=2*1024*1024,N0=Math.ceil($0/3)*4+512,$X=new Set([".txt",".html",".htm",".odt",".odp",".docx",".pptx",".xlsx",".epub",".pdf"]);function G4(t){let e=String(t||"").trim();if(!e||e.includes("\0"))throw new Error("fileName \u65E0\u6548\u3002");let r=Cr.default.basename(e);if(!r||r==="."||r===".."||r.length>255)throw new Error("fileName \u65E0\u6548\u6216\u8D85\u8FC7 255 \u4E2A\u5B57\u7B26\u3002");if(!$X.has(Cr.default.extname(r).toLowerCase()))throw new Error("\u6587\u4EF6\u7FFB\u8BD1\u4EC5\u652F\u6301 TXT\u3001HTML\u3001ODT\u3001ODP\u3001DOCX\u3001PPTX\u3001XLSX\u3001EPUB \u6216 PDF\u3002");return r}function OX(t){let e=t.trim(),r=/^data:[^;,]+;base64,/iu.test(e)?e.indexOf(","):-1,n=(r>=0?e.slice(r+1):e).replace(/\s/gu,"");if(!n||n.length>N0)throw new Error("\u7FFB\u8BD1\u6587\u4EF6\u5FC5\u987B\u5927\u4E8E 0 \u5B57\u8282\u4E14\u4E0D\u8D85\u8FC7 20 MB\u3002");if(n.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/u.test(n))throw new Error("fileByteBase64 \u4E0D\u662F\u6709\u6548\u7684 Base64 \u5185\u5BB9\u3002");let i=Buffer.from(n,"base64");if(i.length===0||i.length>$0||i.toString("base64").replace(/=+$/u,"")!==n.replace(/=+$/u,""))throw new Error("fileByteBase64 \u65E0\u6548\u6216\u8D85\u8FC7 20 MB\u3002");return i}function M0(t){let e=!!t.filePath?.trim(),r=!!t.fileByteBase64?.trim();if(e===r)throw new Error("filePath \u4E0E fileByteBase64 \u5FC5\u987B\u4E14\u53EA\u80FD\u63D0\u4F9B\u4E00\u4E2A\u3002");if(!String(t.targetLang||"").trim())throw new Error("targetLang \u4E0D\u80FD\u4E3A\u7A7A\u3002");let n,i;if(e){let o=String(t.filePath).trim();if(!Cr.default.isAbsolute(o))throw new Error("filePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let a=Bi.default.lstatSync(o);if(a.isSymbolicLink()||!a.isFile())throw new Error("filePath \u5FC5\u987B\u6307\u5411\u975E\u7B26\u53F7\u94FE\u63A5\u7684\u666E\u901A\u6587\u4EF6\u3002");if(a.size<=0||a.size>$0)throw new Error("\u7FFB\u8BD1\u6587\u4EF6\u5FC5\u987B\u5927\u4E8E 0 \u5B57\u8282\u4E14\u4E0D\u8D85\u8FC7 20 MB\u3002");if(i=G4(t.fileName||Cr.default.basename(o)),n=Bi.default.readFileSync(o),n.length!==a.size)throw new Error("\u7FFB\u8BD1\u6587\u4EF6\u5728\u8BFB\u53D6\u671F\u95F4\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002")}else i=G4(t.fileName),n=OX(String(t.fileByteBase64));return{request:{FileByteBase64:n.toString("base64"),FileName:i,FromLang:String(t.fromLang||"auto").trim()||"auto",Lang:String(t.targetLang).trim()},byteLength:n.length,sha256:C0.default.createHash("sha256").update(n).digest("hex"),auditFileName:i}}function D0(t){let e=String(t?.FileByteBase64||"").trim();if(!e)throw new Error("\u540E\u7AEF\u672A\u8FD4\u56DE\u7FFB\u8BD1\u6587\u4EF6\u5185\u5BB9\u3002");let r=Buffer.from(e,"base64");if(r.length===0||r.length>PX||r.toString("base64").replace(/=+$/u,"")!==e.replace(/=+$/u,""))throw new Error("\u540E\u7AEF\u8FD4\u56DE\u7684\u7FFB\u8BD1\u6587\u4EF6\u65E0\u6548\u6216\u8D85\u8FC7 25 MB\u3002");if(t?.ByteLength!==void 0&&Number(t.ByteLength)!==r.length)throw new Error("\u540E\u7AEF\u7FFB\u8BD1\u6587\u4EF6\u957F\u5EA6\u56DE\u8BFB\u4E0D\u4E00\u81F4\u3002");return r}function X4(t,e){let r=String(t||"").trim(),n=Cr.default.resolve(r);if(!Cr.default.isAbsolute(r))throw new Error("outputFilePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");if(Bi.default.existsSync(n))throw new Error("outputFilePath \u5DF2\u5B58\u5728\uFF1B\u4E3A\u907F\u514D\u8986\u76D6\uFF0C\u8BF7\u4F7F\u7528\u65B0\u7684\u6587\u4EF6\u540D\u3002");let i=Bi.default.lstatSync(Cr.default.dirname(n));if(!i.isDirectory()||i.isSymbolicLink())throw new Error("outputFilePath \u7684\u7236\u76EE\u5F55\u5FC5\u987B\u662F\u975E\u7B26\u53F7\u94FE\u63A5\u76EE\u5F55\u3002");return Bi.default.writeFileSync(n,e,{flag:"wx"}),n}var Rl={gutter:0,mask:!1,drag:!1,left:!1,hover:!1,shadow:!1,link:!0,watermark:!1,mobile:!1,dark:!1,themeMode:"system",density:"compact",autoRefresh:0,lastRefreshTime:"",watermarkStyle:{content:"Microi",font:{fontSize:16,color:"rgba(255, 0, 0, 0.15)"},rotate:-22},dynamicStyle:{padding:"10px",backgroundColor:"",opacity:1}};function fe(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}var NX=new Set(["true","false","axis","item","none","vertical","horizontal"]);function MX(t){if(typeof t!="string")return"";let e=t.trim();return e?NX.has(e.toLowerCase())?"":e:""}function ws(t){if(t==null||t==="")return{ok:!1,error:"JSON value is empty."};if(typeof t!="string")return{ok:!0,value:t};try{return{ok:!0,value:JSON.parse(t)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function Y4(t,e){return{...t,...fe(e)}}function Ef(){return Math.floor(Math.random()*8e4+1e4)}function DX(t){let e=Math.random().toString(36).slice(2,8);return`page_${t.replace(/[^\w\u4e00-\u9fa5]+/g,"_").replace(/^_+|_+$/g,"").slice(0,24)||"ai"}_${e}`}function D(t,e,r,n,i){let o={sort:t,label:e,type:r,value:n};return i&&(o.typeOptions=i),o}var FX=[{label:"\u672C\u65E5",value:"today"},{label:"\u672C\u5468",value:"week"},{label:"\u672C\u6708",value:"month"},{label:"\u672C\u5B63",value:"quarter"},{label:"\u672C\u5E74",value:"year"},{label:"\u53BB\u5E74",value:"lastYear"}];function zX(){return{prop:"period",label:"\u7EDF\u8BA1\u5468\u671F",type:"select",value:"month",defaultValue:"month",remote:!1,options:FX.map(t=>({...t}))}}function Xo(t){let e=Array.isArray(t)?t.map(n=>fe(n)).filter(n=>Object.keys(n).length):[];return e.some(n=>n.prop==="period"||n.prop==="_period")?e:[zX(),...e]}function t2(t){return{...t,searchData:Xo(t.searchData)}}function LX(t,e){let r={statistic:[18,19],progress:[26,27],bar:[1,16],line:[1,16],linebar:[1,18],pie:[1,19],funnel:[1,13],tabel:[1,13]};for(let n of r[t]??[]){let i=fe(e[n]);Object.keys(i).length&&(i.value=!0,e[n]=i)}}function z0(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let r=Number.parseFloat(t);if(Number.isFinite(r))return r}return e}function Q4(t,e,r){return z0(fe(t[e]).value,r)}function Sf(t,e){return fe(t[e]).value===!0}function jX(t){let e=Array.isArray(t.widgetParams)?t.widgetParams:[],r=fe(e[0]),n=fe(r.typeOptions).dataJson;if(Array.isArray(n))return n.length;let i=fe(n);return Array.isArray(i.data)?i.data.length:Array.isArray(i.bodyData)?i.bodyData.length:0}function BX(t){let e=qi(t,"type"),r=Array.isArray(t.widgetParams)?t.widgetParams:[],n=jX(t);if(e==="statistic"){let i=Math.min(24,Math.max(1,Q4(r,1,6))),o=Math.max(1,Math.floor(24/i)),a=Math.max(1,Math.ceil(Math.max(n,1)/o)),s=Sf(r,18)||Sf(r,19)?44:0;return Math.max(190,s+a*88+18)}if(e==="progress"){let i=Math.min(24,Math.max(1,Q4(r,1,12))),o=Math.max(1,Math.floor(24/i)),a=Math.max(1,Math.ceil(Math.max(n,1)/o)),s=Sf(r,26)||Sf(r,27)?44:0;return Math.max(180,s+a*108+24)}return 0}function qX(t,e,r){let n=BX(t);if(!n)return 0;let i=fe(t.widgetOption);return z0(i.height,0)<n&&(i.height=n,t.widgetOption=i,r.push(`${e}.widgetOption.height was raised to ${n} so content widgets do not clip when rendered.`)),n}function VX(t,e,r){return{number:Ef(),wrapperNumber:t,span:e,offset:0,push:0,pull:0,height:r,marginTop:0,dynamicStyle:{padding:"8px",backgroundColor:""}}}function UX(t,e){return[D(0,"Data source","textarea","",{rows:3,dataJson:{data:t,searchData:Xo([])}}),D(1,"Grid width","slider",6,{min:1,max:24,step:1}),D(2,"Background","color",""),D(3,"Gap","input","5px"),D(4,"Block colors","input","#2563eb,#16a34a,#f59e0b,#dc2626,#7c3aed,#0891b2"),D(5,"Padding","input","18px"),D(6,"Radius","input","8px"),D(7,"Title size","input","13px"),D(8,"Title weight","input","500"),D(9,"Title color","color",e?"#dbeafe":"#ffffff"),D(10,"Title margin","input","0 0 10px 0"),D(11,"Value size","input","22px"),D(12,"Value weight","input","700"),D(13,"Value color","color","#ffffff"),D(14,"Icon position","radio","suffix"),D(15,"Icon color","color","#ffffff"),D(16,"Icon size","input","18px"),D(17,"Background image","input",""),D(18,"Show search","switch",!0),D(19,"Date filter","switch",!0),D(20,"Precision","number",0),D(21,"Value padding","input","0"),D(22,"Value margin","input","0"),D(23,"Icon margin","input","0"),D(24,"Appearance","select","summary",{options:[{label:"\u6458\u8981",value:"summary"},{label:"\u660E\u7EC6\u6307\u6807",value:"detail"},{label:"\u5F69\u8272\u5361\u7247",value:"cards"}]})]}function F0(t,e,r,n=""){let i=t2(e);return t==="pie"?[D(0,"Data source","textarea","",{rows:3,dataJson:i}),D(1,"Show search","switch",!0),D(2,"Inner radius","number",36),D(3,"Outer radius","number",92),D(4,"Unit","input",n),D(5,"Title","input",r),D(6,"Subtitle","input",""),D(7,"Show legend","switch",!0),D(8,"Legend orient","select","vertical"),D(9,"Legend position","select","left"),D(10,"Tooltip","switch",!0),D(11,"Trigger","select","item"),D(12,"Toolbox","switch",!1),D(13,"Show label","switch",!0),D(14,"Label position","select","outside"),D(15,"Border radius","number",8),D(16,"Border width","number",2),D(17,"Pad angle","number",2),D(18,"Nightingale","switch",!1),D(19,"Date filter","switch",!0),D(20,"Label format","input","{d}%")]:[D(0,"Data source","textarea","",{rows:3,dataJson:i}),D(1,"Show search","switch",!0),D(2,"Boundary gap","switch",t==="bar"),t==="line"?D(3,"Smooth line","switch",!1):D(3,"Bar effect","select","shadow"),D(4,"Unit","input",n),D(5,"Title","input",r),D(6,"Subtitle","input",""),D(7,"Show legend","switch",!0),D(8,"Legend orient","select","horizontal"),D(9,"Legend position","select","center"),D(10,"Tooltip","switch",!0),D(11,"Trigger","select","axis"),D(12,"Toolbox","switch",!1),D(13,"Show label","switch",t==="bar"),D(14,"Label position","select","outside"),D(15,"Split line","switch",!0),D(16,"Date filter","switch",!0),D(17,"Rotate","switch",!1)]}function HX(t){return[D(0,"Data source","textarea","",{rows:3,dataJson:t2(t)}),D(1,"Show search","switch",!0),D(2,"Stripe","switch",!0),D(3,"Border","switch",!0),D(4,"Size","select","small"),D(5,"Progress width","number",16),D(6,"Merge column","input",""),D(7,"Page size","number",-1),D(8,"Summary","switch",!1),D(9,"Border color","color","var(--el-border-color-lighter)"),D(10,"Header background","color","var(--el-fill-color-light)"),D(11,"Header color","color","var(--el-table-header-text-color)"),D(12,"Text color","color","var(--el-table-text-color)"),D(13,"Date filter","switch",!0),D(14,"Pie width","number",30),D(15,"Pie background","color","#409eff50"),D(16,"Pie border","color","#409eff")]}function Ko(t,e,r,n,i,o){return{type:t,label:e,category:0,show:1,icon:"",img:"",widgetOption:VX(r,n,i),widgetParams:o}}function Wo(t,e,r,n,i){let o=Ef();return{type:"pannel",label:"Card",hidden:!1,icon:"",img:"",wrapperOption:{number:o,gutter:0,span:e,offset:0,push:0,pull:0,height:r,heightMode:"content",marginTop:0,margin:"0px 10px 10px 0px",pannelColor:"var(--el-bg-color)",dynamicStyle:{padding:"8px",backgroundColor:"var(--el-bg-color)"},titleOption:{hidden:!0,title:t,dynamicStyle:{textAlign:"left",padding:"0px",height:"22px",lineHeight:"22px",fontSize:"14px",color:"var(--el-text-color-primary)"},moreOption:{hidden:!1,icon:"More",iconShow:!1,text:"More",linkurl:"/",linktype:"router",refresh:"0",datetime:"0",autotime:!1,autotimeval:1,dynamicStyle:{color:i?"#93c5fd":"#2563eb",fontSize:"12px"}}}},widgetList:n(o)}}function L0(t,e){let r=`${t} ${e||""}`.toLowerCase();return/维保|维修|设备|工单|巡检|maintenance|service|ticket|asset/.test(r)?"maintenance":/商城|商品|库存|订单|门店|mall|shop|ecommerce|retail|sku/.test(r)?"mall":/财务|发票|收款|付款|finance|invoice|payment/.test(r)?"finance":/销售|客户|商机|营收|sales|customer|crm|revenue/.test(r)?"sales":"operations"}function r2(t){return t==="maintenance"?{title:"\u7EF4\u4FDD\u8FD0\u8425\u9A7E\u9A76\u8231",subtitle:"\u5DE5\u5355\u3001\u8BBE\u5907\u3001\u5DE1\u68C0\u4E0E\u5BA2\u6237\u670D\u52A1\u72B6\u6001\u603B\u89C8",stats:[{name:"\u4ECA\u65E5\u5DE5\u5355",value:86,icon:"Tickets",bgColor:"#2563eb",bgImage:"",linkUrl:"/"},{name:"\u5F85\u6D3E\u5355",value:14,icon:"Clock",bgColor:"#f59e0b",bgImage:"",linkUrl:"/"},{name:"\u6309\u65F6\u5B8C\u6210\u7387",value:96,icon:"Top",bgColor:"#16a34a",bgImage:"",linkUrl:"/"},{name:"\u9AD8\u98CE\u9669\u8BBE\u5907",value:7,icon:"Warning",bgColor:"#dc2626",bgImage:"",linkUrl:"/"}],xAxis:["\u5468\u4E00","\u5468\u4E8C","\u5468\u4E09","\u5468\u56DB","\u5468\u4E94","\u5468\u516D","\u5468\u65E5"],barSeries:[{name:"\u65B0\u589E\u5DE5\u5355",data:[18,22,16,28,31,20,14]},{name:"\u5B8C\u6210\u5DE5\u5355",data:[15,20,18,24,29,21,16]}],lineSeries:[{name:"\u54CD\u5E94\u65F6\u957F(\u5206\u949F)",data:[42,38,35,33,31,29,28]},{name:"\u6EE1\u610F\u5EA6",data:[92,93,94,94,95,96,96]}],pieData:[{name:"\u5F85\u63A5\u5355",value:14},{name:"\u5904\u7406\u4E2D",value:28},{name:"\u5F85\u9A8C\u6536",value:17},{name:"\u5DF2\u5B8C\u6210",value:63}],tableHeaders:[{prop:"WorkOrderNo",label:"\u5DE5\u5355\u53F7",align:"center"},{prop:"CustomerName",label:"\u5BA2\u6237",align:"center"},{prop:"DeviceName",label:"\u8BBE\u5907",align:"center"},{prop:"Status",label:"\u72B6\u6001",align:"center",status_ui:!0},{prop:"Owner",label:"\u8D1F\u8D23\u4EBA",align:"center"}],tableRows:[{WorkOrderNo:"WO-20260611-001",CustomerName:"\u5229\u8F69\u79D1\u6280\u56ED",DeviceName:"\u7A7A\u538B\u673A A01",Status:"\u5904\u7406\u4E2D",Owner:"\u5F20\u5DE5",status_ui:"warning"},{WorkOrderNo:"WO-20260611-002",CustomerName:"\u661F\u6CB3\u5DE5\u5382",DeviceName:"\u51B7\u5374\u5854 C03",Status:"\u5F85\u9A8C\u6536",Owner:"\u674E\u5DE5",status_ui:"primary"},{WorkOrderNo:"WO-20260611-003",CustomerName:"\u5317\u57CE\u4ED3\u50A8",DeviceName:"\u914D\u7535\u67DC P12",Status:"\u5DF2\u5B8C\u6210",Owner:"\u738B\u5DE5",status_ui:"success"}]}:t==="mall"?{title:"\u5546\u57CE\u7ECF\u8425\u770B\u677F",subtitle:"\u8BA2\u5355\u3001\u5546\u54C1\u3001\u5E93\u5B58\u4E0E\u4F1A\u5458\u589E\u957F\u6982\u89C8",stats:[{name:"\u4ECA\u65E5\u8BA2\u5355",value:328,icon:"ShoppingCart",bgColor:"#2563eb",bgImage:"",linkUrl:"/"},{name:"\u9500\u552E\u989D",value:128900,icon:"Money",bgColor:"#16a34a",bgImage:"",linkUrl:"/"},{name:"\u4F4E\u5E93\u5B58 SKU",value:23,icon:"Warning",bgColor:"#f59e0b",bgImage:"",linkUrl:"/"},{name:"\u65B0\u589E\u4F1A\u5458",value:78,icon:"User",bgColor:"#7c3aed",bgImage:"",linkUrl:"/"}],xAxis:["1\u6708","2\u6708","3\u6708","4\u6708","5\u6708","6\u6708"],barSeries:[{name:"\u8BA2\u5355\u6570",data:[1200,1420,1380,1680,1910,2250]},{name:"\u53D1\u8D27\u6570",data:[1160,1390,1350,1610,1880,2190]}],lineSeries:[{name:"\u9500\u552E\u989D",data:[82,96,91,116,132,158]},{name:"\u590D\u8D2D\u7387",data:[28,31,30,34,36,39]}],pieData:[{name:"\u98DF\u54C1\u996E\u6599",value:35},{name:"\u5BB6\u6E05\u65E5\u5316",value:24},{name:"\u6570\u7801\u5BB6\u7535",value:18},{name:"\u670D\u9970\u978B\u5305",value:23}],tableHeaders:[{prop:"SkuName",label:"\u5546\u54C1",align:"center"},{prop:"Stock",label:"\u5E93\u5B58",align:"center"},{prop:"Sales",label:"\u9500\u91CF",align:"center"},{prop:"Status",label:"\u72B6\u6001",align:"center",status_ui:!0}],tableRows:[{SkuName:"\u8F7B\u98DF\u71D5\u9EA6\u7EC4\u5408",Stock:128,Sales:486,Status:"\u70ED\u9500",status_ui:"success"},{SkuName:"\u65E0\u7EBF\u8033\u673A Pro",Stock:18,Sales:221,Status:"\u4F4E\u5E93\u5B58",status_ui:"warning"},{SkuName:"\u667A\u80FD\u6C34\u676F",Stock:76,Sales:164,Status:"\u6B63\u5E38",status_ui:"primary"}]}:{title:t==="sales"?"\u9500\u552E\u8FD0\u8425\u4EEA\u8868\u76D8":t==="finance"?"\u8D22\u52A1\u6536\u4ED8\u6B3E\u770B\u677F":"\u7EFC\u5408\u8FD0\u8425\u9A7E\u9A76\u8231",subtitle:"\u6838\u5FC3\u6307\u6807\u3001\u8D8B\u52BF\u5206\u6790\u3001\u7ED3\u6784\u5206\u5E03\u4E0E\u660E\u7EC6\u5217\u8868",stats:[{name:"\u672C\u6708\u76EE\u6807",value:128,icon:"Aim",bgColor:"#2563eb",bgImage:"",linkUrl:"/"},{name:"\u5DF2\u5B8C\u6210",value:96,icon:"Top",bgColor:"#16a34a",bgImage:"",linkUrl:"/"},{name:"\u5F85\u5904\u7406",value:18,icon:"Clock",bgColor:"#f59e0b",bgImage:"",linkUrl:"/"},{name:"\u98CE\u9669\u9879",value:6,icon:"Warning",bgColor:"#dc2626",bgImage:"",linkUrl:"/"}],xAxis:["1\u6708","2\u6708","3\u6708","4\u6708","5\u6708","6\u6708"],barSeries:[{name:"\u8BA1\u5212",data:[80,92,100,116,124,138]},{name:"\u5B9E\u9645",data:[76,88,96,110,129,146]}],lineSeries:[{name:"\u589E\u957F\u7387",data:[8,12,10,16,18,21]},{name:"\u8FBE\u6210\u7387",data:[88,91,93,94,96,98]}],pieData:[{name:"A \u7C7B",value:42},{name:"B \u7C7B",value:28},{name:"C \u7C7B",value:18},{name:"\u5176\u4ED6",value:12}],tableHeaders:[{prop:"Name",label:"\u540D\u79F0",align:"center"},{prop:"Owner",label:"\u8D1F\u8D23\u4EBA",align:"center"},{prop:"Progress",label:"\u8FDB\u5EA6",align:"center",progress_ui:!0},{prop:"Status",label:"\u72B6\u6001",align:"center",status_ui:!0}],tableRows:[{Name:"\u91CD\u70B9\u9879\u76EE A",Owner:"\u9648\u6668",Progress:92,Status:"\u8FDB\u884C\u4E2D",progress_ui:"success",status_ui:"success"},{Name:"\u5BA2\u6237\u8DDF\u8FDB B",Owner:"\u6797\u66E6",Progress:68,Status:"\u5F85\u63A8\u8FDB",progress_ui:"warning",status_ui:"warning"},{Name:"\u98CE\u9669\u6574\u6539 C",Owner:"\u8D75\u5B81",Progress:35,Status:"\u9884\u8B66",progress_ui:"exception",status_ui:"danger"}]}}function JX(t){let e=t.prompt||"";if(/平台首页|智能工作台|AI.*首页|首页.*AI|platform.*home/i.test(e)){let u=/dark|深色|黑色/.test(`${e} ${t.style||""}`),p=(f,m,h,g)=>Wo(f,h,360,y=>[Ko(m,f,y,24,320,g)],u);return{formConfig:{...Rl,title:t.title||"\u667A\u80FD\u5DE5\u4F5C\u9996\u9875",dark:u,themeMode:u?"dark":"system"},wrapperList:[p("AI \u521B\u4F5C\u4E2D\u5FC3","aiengine",14,[]),p("\u5DE5\u4F5C\u6982\u89C8","homeoverview",10,[D(0,"\u4E2A\u4EBA\u7EDF\u8BA1\u63A5\u53E3","input","platform-home-overview"),D(1,"\u5E03\u5C40\u5BC6\u5EA6","select","compact")]),p("\u6211\u7684\u5DE5\u4F5C","workcenter",16,[D(0,"\u89C6\u56FE","select","work"),D(1,"\u5DE5\u4F5C\u83DC\u5355","sysmenu",""),D(2,"\u6D41\u7A0B\u83DC\u5355","sysmenu",""),D(3,"\u516C\u544A\u83DC\u5355","sysmenu",""),D(4,"\u65E5\u5386\u83DC\u5355","sysmenu",""),D(5,"\u9996\u9875\u4EFB\u52A1\u5206\u9875\u6761\u6570","input",5)]),p("\u672C\u6708\u65E5\u7A0B","diycalendar",8,[D(0,"\u65E5\u5386\u83DC\u5355","sysmenu",""),D(1,"\u5E03\u5C40\u5BC6\u5EA6","input","compact")])]}}let r=L0(e,t.theme),n=`${e} ${t.style||""}`.toLowerCase(),i=/dark|深色|黑色/.test(n),o=i?"dark":/light|浅色|亮色/.test(n)?"light":"system",a=r2(r),s=t.title||a.title,c=t.desc||a.subtitle;return{formConfig:{...Rl,dark:i,themeMode:o,title:s,dynamicStyle:{padding:"12px 0 0 0",backgroundColor:"var(--el-bg-color-page)",opacity:1}},wrapperList:[Wo(s,24,76,u=>[Ko("workbench","Workbench",u,24,48,[D(0,"Data source","textarea","",{rows:3,dataJson:{icon:"",title:s,subTitle:c}})])],i),Wo("\u6838\u5FC3\u6307\u6807",24,112,u=>[Ko("statistic","Statistic",u,24,84,UX(a.stats,i))],i),Wo("\u8D8B\u52BF\u5206\u6790",12,340,u=>[Ko("bar","Bar Chart",u,24,300,F0("bar",{xAxis:a.xAxis,series:a.barSeries,searchData:[]},"\u4E1A\u52A1\u8D8B\u52BF",""))],i),Wo("\u7ED3\u6784\u5360\u6BD4",12,340,u=>[Ko("pie","Pie Chart",u,24,300,F0("pie",{data:a.pieData,searchData:[]},"\u5206\u7C7B\u5360\u6BD4",""))],i),Wo("\u6548\u7387\u8D70\u52BF",12,340,u=>[Ko("line","Line Chart",u,24,300,F0("line",{xAxis:a.xAxis,series:a.lineSeries,searchData:[]},"\u6548\u7387\u8D70\u52BF",""))],i),Wo("\u91CD\u70B9\u660E\u7EC6",12,340,u=>[Ko("tabel","Table",u,24,300,HX({headerData:a.tableHeaders,bodyData:a.tableRows,total:a.tableRows.length,searchData:[]}))],i)]}}function pt(t,e,r,n,i,o={}){return{options:{left:t,top:e,width:r,height:n,title:i,fontSize:9,lineHeight:n,...o},printElementType:{title:"Text",type:"text"}}}function e2(t,e,r){return{options:{left:t,top:e,width:r,height:1,borderStyle:"solid"},printElementType:{title:"Line",type:"hline"}}}function ZX(t,e,r,n){return{options:{left:t,top:e,width:r,height:n,borderWidth:1},printElementType:{title:"Rect",type:"rect"}}}function KX(t){return L0(t)}function WX(t){let e=KX(t.prompt||""),r=t.title||(e==="maintenance"?"\u7EF4\u4FDD\u5DE5\u5355\u6253\u5370\u6A21\u677F":e==="mall"?"\u5546\u57CE\u8BA2\u5355\u6253\u5370\u6A21\u677F":"\u4E1A\u52A1\u5355\u636E\u6253\u5370\u6A21\u677F"),n=e==="maintenance"?"Items":"Details",i=e==="maintenance"?[[{title:"\u9879\u76EE",field:"ItemName",width:120,checked:!0},{title:"\u5904\u7406\u7ED3\u679C",field:"Result",width:180,checked:!0},{title:"\u5DE5\u65F6",field:"Hours",width:80,checked:!0},{title:"\u5907\u6CE8",field:"Remark",width:150,checked:!0}]]:[[{title:"\u540D\u79F0",field:"Name",width:150,checked:!0},{title:"\u89C4\u683C",field:"Spec",width:120,checked:!0},{title:"\u6570\u91CF",field:"Qty",width:80,checked:!0},{title:"\u91D1\u989D",field:"Amount",width:100,checked:!0},{title:"\u5907\u6CE8",field:"Remark",width:120,checked:!0}]],o=e==="maintenance"?{WorkOrderNo:"WO-20260611-001",CustomerName:"\u5229\u8F69\u79D1\u6280\u56ED",ContactName:"\u738B\u7ECF\u7406",DeviceName:"\u7A7A\u538B\u673A A01",ServiceDate:"2026-06-11",EngineerName:"\u5F20\u5DE5",FaultDesc:"\u8BBE\u5907\u8FD0\u884C\u5F02\u54CD\uFF0C\u538B\u529B\u6CE2\u52A8\u5F02\u5E38\u3002",Solution:"\u5B8C\u6210\u8F74\u627F\u68C0\u67E5\u3001\u7BA1\u8DEF\u7D27\u56FA\u4E0E\u8FD0\u884C\u6D4B\u8BD5\u3002",Items:[{ItemName:"\u73B0\u573A\u68C0\u67E5",Result:"\u5DF2\u5B8C\u6210",Hours:1.5,Remark:"\u8FD0\u884C\u8BB0\u5F55\u6B63\u5E38"},{ItemName:"\u90E8\u4EF6\u7EF4\u62A4",Result:"\u5DF2\u5B8C\u6210",Hours:2,Remark:"\u66F4\u6362\u6613\u635F\u4EF6"}]}:{BillNo:"BILL-20260611-001",CustomerName:"\u793A\u4F8B\u5BA2\u6237",ContactName:"\u674E\u7ECF\u7406",BillDate:"2026-06-11",OwnerName:"\u9648\u6668",Summary:"\u4E1A\u52A1\u5355\u636E\u6458\u8981\u8BF4\u660E\u3002",Details:[{Name:"\u670D\u52A1\u9879\u76EE A",Spec:"\u6807\u51C6",Qty:2,Amount:1200,Remark:"\u542B\u7A0E"},{Name:"\u670D\u52A1\u9879\u76EE B",Spec:"\u9AD8\u7EA7",Qty:1,Amount:2800,Remark:"\u542B\u5B89\u88C5"}]},a=[pt(40,18,520,24,r,{fontSize:18,fontWeight:"700",textAlign:"center",lineHeight:24}),e2(36,50,535),pt(42,66,76,16,e==="maintenance"?"\u5DE5\u5355\u53F7":"\u5355\u636E\u53F7",{fontWeight:"600"}),pt(118,66,160,16,"",{field:e==="maintenance"?"WorkOrderNo":"BillNo",testData:e==="maintenance"?o.WorkOrderNo:o.BillNo}),pt(320,66,76,16,"\u65E5\u671F",{fontWeight:"600"}),pt(396,66,160,16,"",{field:e==="maintenance"?"ServiceDate":"BillDate",testData:e==="maintenance"?o.ServiceDate:o.BillDate}),pt(42,92,76,16,"\u5BA2\u6237",{fontWeight:"600"}),pt(118,92,160,16,"",{field:"CustomerName",testData:o.CustomerName}),pt(320,92,76,16,"\u8054\u7CFB\u4EBA",{fontWeight:"600"}),pt(396,92,160,16,"",{field:"ContactName",testData:o.ContactName}),pt(42,118,76,16,e==="maintenance"?"\u8BBE\u5907":"\u8D1F\u8D23\u4EBA",{fontWeight:"600"}),pt(118,118,160,16,"",{field:e==="maintenance"?"DeviceName":"OwnerName",testData:e==="maintenance"?o.DeviceName:o.OwnerName}),pt(320,118,76,16,e==="maintenance"?"\u5DE5\u7A0B\u5E08":"\u5236\u5355\u4EBA",{fontWeight:"600"}),pt(396,118,160,16,"",{field:e==="maintenance"?"EngineerName":"OwnerName",testData:e==="maintenance"?o.EngineerName:o.OwnerName}),ZX(38,150,535,70),pt(48,160,70,16,e==="maintenance"?"\u6545\u969C\u63CF\u8FF0":"\u6458\u8981",{fontWeight:"600"}),pt(118,160,430,46,"",{field:e==="maintenance"?"FaultDesc":"Summary",testData:e==="maintenance"?o.FaultDesc:o.Summary,lineHeight:18}),pt(42,242,160,16,"\u660E\u7EC6",{fontSize:12,fontWeight:"700"}),{options:{left:40,top:266,width:530,height:92,field:n,columns:i,fields:i[0].map(c=>({text:c.title,field:c.field}))},printElementType:{title:"Table",type:"table"}},pt(42,392,76,16,e==="maintenance"?"\u5904\u7406\u65B9\u6848":"\u5907\u6CE8",{fontWeight:"600"}),pt(118,392,430,38,"",{field:e==="maintenance"?"Solution":"Summary",testData:e==="maintenance"?o.Solution:o.Summary,lineHeight:18}),e2(36,468,535),pt(60,492,120,16,"\u5BA2\u6237\u7B7E\u5B57\uFF1A"),pt(330,492,120,16,"\u7ECF\u529E\u4EBA\u7B7E\u5B57\uFF1A")];return{pageObj:{panels:[{index:0,name:r,paperType:t.paperType||"A4",height:297,width:210,paperHeader:0,paperFooter:841.8897637795277,paperNumberContinue:!0,watermarkOptions:{},panelLayoutOptions:{},printElements:a}]},printObj:o}}function Go(t){let e=ws(t);if(!e.ok)return t;let r=e.value;if(typeof r=="string"){let o=ws(r);o.ok&&(r=o.value)}let n=fe(r);if(n.JsonObj!==void 0)return Go(n.JsonObj);if(n.jsonObj!==void 0)return Go(n.jsonObj);if(n.JsonStr!==void 0)return Go(n.JsonStr);if(n.jsonStr!==void 0)return Go(n.jsonStr);let i=fe(n.formData??n.FormData);if(Object.keys(i).length){if(i.JsonObj!==void 0)return Go(i.JsonObj);if(i.jsonObj!==void 0)return Go(i.jsonObj);if(i.formConfig!==void 0||i.wrapperList!==void 0)return i}return r}function GX(t,e,r){let n=qi(t,"type");if(!Array.isArray(t.widgetParams)||t.widgetParams.length===0)return;let i=t.widgetParams,o={bar:[5,6],line:[5,6],linebar:[5,6],pie:[5,6],funnel:[3,4]};for(let l of o[n]??[]){let u=fe(i[l]);if(!Object.keys(u).length||u.value===void 0||u.value==="")continue;let p=MX(u.value);u.value!==p&&(u.value=p,i[l]=u,r.push(`${e}.widgetParams[${l}].value was cleared because it looked like a chart option, not display text.`))}let a=fe(i[0]),s={rows:3,...fe(a.typeOptions)},c=s.dataJson;if(["statistic","pie","funnel","progress"].includes(n))if(Array.isArray(c))s.dataJson={data:c,searchData:Xo([])},r.push(`${e}.widgetParams[0].typeOptions.dataJson array was wrapped as {data, searchData}.`);else{let l=fe(c);s.dataJson={...l,data:Array.isArray(l.data)?l.data:[],searchData:Xo(l.searchData)}}if(["bar","line","linebar"].includes(n)){let l=fe(s.dataJson);s.dataJson={...l,xAxis:Array.isArray(l.xAxis)?l.xAxis:[],series:Array.isArray(l.series)?l.series:[],searchData:Xo(l.searchData)}}if(n==="tabel")if(Array.isArray(c))s.dataJson={headerData:[],bodyData:c,total:c.length,searchData:Xo([])},r.push(`${e}.widgetParams[0].typeOptions.dataJson array was wrapped as table bodyData.`);else{let l=fe(s.dataJson);s.dataJson={...l,headerData:Array.isArray(l.headerData)?l.headerData:[],bodyData:Array.isArray(l.bodyData)?l.bodyData:[],total:typeof l.total=="number"?l.total:Array.isArray(l.bodyData)?l.bodyData.length:0,searchData:Xo(l.searchData)}}LX(n,i),a.typeOptions=s,i[0]=a,t.widgetParams=i}function ti(t){let e=Go(t),r=ws(e);if(!r.ok)return{ok:!1,errors:[`JsonObj is not valid JSON: ${r.error}`],warnings:[]};let n=fe(r.value),i=[],o=[];Object.keys(n).length||i.push("JsonObj must be an object."),n.formConfig!==void 0&&Object.keys(fe(n.formConfig)).length===0&&o.push("formConfig is empty; defaults were applied."),n.wrapperList!==void 0&&!Array.isArray(n.wrapperList)&&i.push("JsonObj.wrapperList must be an array.");let a=Array.isArray(n.wrapperList)?n.wrapperList.map((c,l)=>{let u=fe(c);qi(u,"type")||(u.type="pannel"),qi(u,"label")||(u.label="Card"),u.hidden===void 0&&(u.hidden=!1),u.icon=u.icon??"",u.img=u.img??"",u.wrapperOption=Y4({number:Ef(),gutter:0,span:24,offset:0,push:0,pull:0,height:300,marginTop:0,margin:"0px 10px 10px 0px",pannelColor:"",dynamicStyle:{padding:"10px",backgroundColor:""},titleOption:{hidden:!0,title:`Section ${l+1}`,dynamicStyle:{textAlign:"left",padding:"0px",height:"20px",lineHeight:"20px",fontSize:"14px",color:""},moreOption:{hidden:!1,icon:"More",iconShow:!1,text:"More",linkurl:"/",linktype:"router",refresh:"0",datetime:"0",autotime:!1,autotimeval:1,dynamicStyle:{color:"",fontSize:"12px"}}}},u.wrapperOption);let p=0;if(Array.isArray(u.widgetList)?u.widgetList=u.widgetList.map((f,m)=>{let h=fe(f);qi(h,"type")||i.push(`wrapperList[${l}].widgetList[${m}].type is required.`),h.label=h.label??h.type??"Widget",h.category=h.category??0,h.show=h.show??1,h.icon=h.icon??"",h.img=h.img??"",h.widgetOption=Y4({number:Ef(),wrapperNumber:fe(u.wrapperOption).number,span:24,offset:0,push:0,pull:0,height:260,marginTop:0,dynamicStyle:{padding:"8px",backgroundColor:""}},h.widgetOption),Array.isArray(h.widgetParams)||(h.widgetParams=[D(0,"Data source","textarea","",{rows:3,dataJson:{}})],o.push(`wrapperList[${l}].widgetList[${m}].widgetParams was missing and a safe data param was added.`));let g=`wrapperList[${l}].widgetList[${m}]`;return GX(h,g,o),p=Math.max(p,qX(h,g,o)),h}):(u.widgetList=[],o.push(`wrapperList[${l}].widgetList was missing and was set to an empty array.`)),p>0){let f=fe(u.wrapperOption),m=p+16;z0(f.height,0)<m&&(f.height=m,u.wrapperOption=f,o.push(`wrapperList[${l}].wrapperOption.height was raised to ${m} to fit content widgets.`))}return u}):[];Array.isArray(n.wrapperList)||o.push("wrapperList was missing and was set to an empty array.");let s={formConfig:{...Rl,...fe(n.formConfig),dynamicStyle:{...fe(Rl.dynamicStyle),...fe(fe(n.formConfig).dynamicStyle)},watermarkStyle:{...fe(Rl.watermarkStyle),...fe(fe(n.formConfig).watermarkStyle)}},wrapperList:a};return{ok:i.length===0,value:s,json:JSON.stringify(s),errors:i,warnings:o}}function XX(t){let e=ws(t);if(!e.ok)return t;let r=e.value,n=fe(r);return n.PageObj!==void 0?r=n.PageObj:n.pageObj!==void 0&&(r=n.pageObj),r}function Yo(t){let e=XX(t),r=ws(e);if(!r.ok)return{ok:!1,errors:[`PageObj is not valid JSON: ${r.error}`],warnings:[]};let n=fe(r.value),i=[],o=[];Array.isArray(n.panels)||i.push("PageObj.panels must be an array.");let a=Array.isArray(n.panels)?n.panels.map((s,c)=>{let l=fe(s);return l.index=l.index??c,l.name=l.name??`Panel ${c+1}`,l.paperType=l.paperType??"A4",l.height=l.height??297,l.width=l.width??210,l.paperHeader=l.paperHeader??0,l.paperFooter=l.paperFooter??841.8897637795277,l.paperNumberContinue=l.paperNumberContinue??!0,l.watermarkOptions=l.watermarkOptions??{},l.panelLayoutOptions=l.panelLayoutOptions??{},Array.isArray(l.printElements)||(l.printElements=[],o.push(`panels[${c}].printElements was missing and was set to an empty array.`)),l.printElements=l.printElements.map((u,p)=>{let f=fe(u);return qi(fe(f.printElementType),"type")||i.push(`panels[${c}].printElements[${p}].printElementType.type is required.`),f.options=fe(f.options),f}),l}):[];return a.length===0&&i.push("PageObj.panels must contain at least one panel."),{ok:i.length===0,value:{...n,panels:a},json:JSON.stringify({...n,panels:a}),errors:i,warnings:o}}function Qo(t){if(t==null||t==="")return{ok:!0,value:{},json:"{}",errors:[],warnings:[]};let e=ws(t);return e.ok?{ok:!0,value:e.value,json:JSON.stringify(e.value),errors:[],warnings:[]}:{ok:!1,errors:[`PrintObj is not valid JSON: ${e.error}`],warnings:[]}}function qi(t,...e){for(let r of e){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim();if(typeof n=="number"||typeof n=="boolean")return String(n)}return""}function n2(t){let e=r2(L0(t.prompt||"",t.theme)),r=t.title||e.title,n=JX({...t,title:r});return{title:r,number:t.number||DX(r),desc:t.desc||e.subtitle||qi(fe(n.formConfig),"title")||"",jsonObj:n,jsonStr:JSON.stringify(n)}}function i2(t){let e=WX(t),r=Array.isArray(e.pageObj.panels)?e.pageObj.panels:[],n=t.title||qi(fe(r[0]),"name")||"AI print template",i=t.number||`print_${Math.random().toString(36).slice(2,8)}`;return{title:n,number:i,desc:t.desc||"",pageObj:e.pageObj,pageObjStr:JSON.stringify(e.pageObj),printObj:e.printObj,printObjStr:JSON.stringify(e.printObj),dataApi:t.dataApi||""}}var YX=["EnableRolePermission","HideUnauthorizedFiles","ShowUnauthorizedFileName","DisableRoleInheritance"];function o2(t){let e={...t};for(let n of YX){if(e[n]!==void 0&&typeof e[n]!="boolean")throw new Error(`FileUpload.${n} \u5FC5\u987B\u662F boolean`);e[n]??=!1}let r=e.ConfigurableRoleIds;if(r!==void 0&&(!Array.isArray(r)||r.length>100||r.some(n=>typeof n!="string"||!n.trim()||n.length>100)))throw new Error("FileUpload.ConfigurableRoleIds \u5FC5\u987B\u662F\u6700\u591A 100 \u4E2A\u771F\u5B9E\u89D2\u8272 Id \u7684\u5B57\u7B26\u4E32\u6570\u7EC4");return e.ConfigurableRoleIds=Array.isArray(r)?[...new Set(r)]:[],e.EnableRolePermission===!0&&(e.Limit=!0),{FileUpload:e}}var a2="/* MICROI_WF_LINE_CONDITION_JSON",QX="MICROI_WF_LINE_CONDITION_JSON */",tr=d.record(d.unknown());function W(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}function H(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ii(t){return Array.isArray(t)?t.map(H).filter(e=>Object.keys(e).length>0):[]}function ie(t,...e){for(let r of e){let n=t[r];if(Array.isArray(n))return ii(n)}return[]}function S(t,...e){for(let r of e){let n=t[r];if(typeof n=="string"&&n.trim())return n.trim();if(typeof n=="number"||typeof n=="boolean")return String(n)}return""}function oe(t,...e){for(let r of e){let n=t[r];if(typeof n=="number")return n;if(typeof n=="string"&&n.trim()&&!Number.isNaN(Number(n)))return Number(n)}}function Ss(t,...e){for(let r of e){let n=t[r];if(Array.isArray(n))return n.map(i=>typeof i=="string"?i:S(H(i),"name","Name","id","Id")).filter(Boolean);if(typeof n=="string"&&n.trim())return n.split(/[,,;;]/).map(i=>i.trim()).filter(Boolean)}return[]}function Le(t,...e){for(let r of e)if(Object.prototype.hasOwnProperty.call(t,r))return t[r]}function De(t){return t.trim().toLowerCase()}function E2(t,e){return`${De(t)}::${De(e)}`}function Pl(t){return["Id","CreateTime","UpdateTime","CreateUserId","CreateUserName","UpdateUserId","UpdateUserName","OsClient","IsDeleted"].some(e=>e.toLowerCase()===t.toLowerCase())}function k2(t){let e=t.trim();if(!e)return[];if(e.startsWith("["))try{let r=JSON.parse(e);if(Array.isArray(r))return r}catch{}return e.split(/[,;\n\uFF0C\uFF1B\u3001]+/).map(r=>r.trim()).filter(Boolean)}function Vr(t,...e){for(let r of e){let n=Le(t,r);if(n==null||n==="")continue;return(Array.isArray(n)?n:typeof n=="string"?k2(n):[n]).map(o=>{if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return{ref:String(o).trim()};let a=H(o);return{ref:S(a,"field","Field","fieldName","FieldName","name","Name","id","Id","fieldId","FieldId"),asName:S(a,"asName","AsName","alias","Alias")||void 0,type:S(a,"type","Type")||void 0,displayType:S(a,"displayType","DisplayType")||void 0,displaySelect:typeof a.displaySelect=="boolean"?a.displaySelect:typeof a.DisplaySelect=="boolean"?a.DisplaySelect:void 0,equal:typeof a.equal=="boolean"?a.equal:typeof a.Equal=="boolean"?a.Equal:void 0}}).filter(o=>o.ref)}return[]}function eY(){return{byTableAndRef:new Map,fieldsByTable:new Map}}function T2(t,e){let r=[e.tableId,e.tableName].filter(Boolean),n=[e.id,e.name,e.label].filter(Boolean);for(let i of r){for(let s of n)t.byTableAndRef.set(E2(i,s),e);let o=De(i),a=t.fieldsByTable.get(o)||[];a.some(s=>s.id===e.id||De(s.name)===De(e.name))||(a.push(e),t.fieldsByTable.set(o,a))}}function s2(t,e,r){if(!(!e||!r))return t.byTableAndRef.get(E2(e,r))}function Es(t,e){return t.fieldsByTable.get(De(e))||[]}function C2(t,e,r){return{id:r,name:r,label:r,tableId:t,tableName:e,tableDescription:e,component:"Text",type:"varchar(255)"}}function dn(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!=null&&e!==""))}function V0(){let t=Date.now().toString(36).toUpperCase().padStart(10,"0"),e=Math.random().toString(36).slice(2,18).toUpperCase().padEnd(16,"0");return`${t}${e}`.slice(0,26)}function I2(t){if(Array.isArray(t))return ii(t);let e=H(t);return Array.isArray(e.List)?ii(e.List):Array.isArray(e.Data)?ii(e.Data):[]}function ht(t,e){let r=[`## ${t}`,`- Code: ${e.Code}`,e.Msg?`- Message: ${e.Msg}`:"","","```json",JSON.stringify(e.Data??{},null,2),"```"].filter(Boolean);return W(r.join(`
133
- `),e.Code!==1)}function $l(t){if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function tY(t,e={}){let r=H(t),n=H(r.Workload??r.workload??r.BackgroundWorkload??r.backgroundWorkload),i=[],o=oe(n,"ExpectedSeconds","expectedSeconds")??0,a=oe(n,"ExpectedItems","expectedItems","EstimatedRows","estimatedRows")??0,s=oe(n,"FanOutOperations","fanOutOperations","FanOut","fanOut")??0,c=oe(n,"ExternalCalls","externalCalls")??0;o>=120&&i.push(`\u9884\u8BA1\u8017\u65F6 ${o}s >= 120s`),a>=500&&i.push(`\u9884\u8BA1\u5904\u7406 ${a} \u6761 >= 500 \u6761`),s>=1e3&&i.push(`\u9884\u8BA1\u6247\u51FA ${s} \u4E2A\u5B50\u64CD\u4F5C >= 1000`),c>=100&&i.push(`\u9884\u8BA1\u5916\u90E8\u8C03\u7528 ${c} \u6B21 >= 100 \u6B21`),Zr(n,"UnknownTotal","unknownTotal")===!0&&i.push("\u603B\u5DE5\u4F5C\u91CF\u672A\u77E5\u4E14\u53EF\u80FD\u957F\u65F6\u95F4\u8FD0\u884C");let l=S(r,"V8Code","v8Code"),u=[S(r,"Name","name"),S(r,"ApiEngineKey","apiEngineKey"),l].join(" "),p=/\bV8\.OpenAppDialog\s*\(/i.test(l)&&!/\bV8\.(?:ApiEngine\.RunBackground|Method\.QueueBackgroundTask)\s*\(/i.test(l);return e.inferActionSemantics!==!1&&!p&&/(批量.{0,4}(导入|生成|修复|处理)|安装|初始化|全量同步|数据迁移|数据库备份|批量任务)/i.test(u)&&i.push("\u52A8\u4F5C\u8BED\u4E49\u5C5E\u4E8E\u5178\u578B\u957F\u4EFB\u52A1"),{required:i.length>0,reasons:i}}function rY(t){let e=H(t),r=H(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=S(r,"ExecutionMode","executionMode").trim().toLowerCase(),i=Zr(r,"ClientChunked","clientChunked")===!0||n==="clientchunked"||n==="clientsequential",o=oe(r,"MaxItemsPerChunk","maxItemsPerChunk")??0,a=Zr(r,"Resumable","resumable")===!0;return{declared:i,valid:i&&o>0&&a,maxItemsPerChunk:o,resumable:a}}var kf="https://api.itdos.com",j0="iTdos";function nY(t){let e=String(t.storeId||"").trim(),r=String(t.storeVersionId||"").trim(),n=String(t.requestId||"").trim();if(!/^[A-Za-z0-9:._-]{1,100}$/u.test(e))throw new Error("storeId \u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u5192\u53F7\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\uFF0C\u957F\u5EA6 1-100\u3002");if(!/^[A-Za-z0-9:._-]{8,100}$/u.test(n))throw new Error("requestId \u5FC5\u987B\u662F\u8C03\u7528\u65B9\u4FDD\u5B58\u5E76\u5728\u91CD\u8BD5\u65F6\u590D\u7528\u7684\u7A33\u5B9A\u5E42\u7B49 Id\uFF0C\u957F\u5EA6 8-100\u3002");if(r&&!/^[A-Za-z0-9:._-]{1,100}$/u.test(r))throw new Error("storeVersionId \u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u5192\u53F7\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\uFF0C\u957F\u5EA6 1-100\u3002");let i=String(t.storeApiBase||kf).trim(),o;try{o=new URL(i)}catch{throw new Error("storeApiBase \u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP/HTTPS \u670D\u52A1\u6839\u5730\u5740\u3002")}if(o.protocol!=="https:"||o.username||o.password||o.pathname&&o.pathname!=="/"||o.search||o.hash||o.origin!==kf)throw new Error(`storeApiBase \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE ${kf}\uFF0C\u4E14\u4E0D\u80FD\u5305\u542B\u51ED\u636E\u3001\u8DEF\u5F84\u3001\u67E5\u8BE2\u3001\u7247\u6BB5\u6216\u81EA\u5B9A\u4E49\u7AEF\u53E3\u3002`);let a=kf,s=String(t.storeOsClient||j0).trim();if(s.toLowerCase()!==j0.toLowerCase())throw new Error(`storeOsClient \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE\u79DF\u6237 ${j0}\u3002`);return{ApiEngineKey:"import-microi-store-package",Title:`${t.operation==="update"?"\u66F4\u65B0":"\u5B89\u88C5"}\u5E94\u7528\uFF1A${String(t.appName||t.appId||e).trim()}`,Param:dn({StoreId:e,StoreVersionId:r||void 0,AppId:t.appId,AppName:t.appName,AppVersion:t.appVersion,StoreApiBase:a,StoreOsClient:s,InstallParentSysMenuId:t.installParentSysMenuId,ResumeInstall:t.resumeInstall!==!1,InstallAction:t.operation==="update"?"Update":"Install",InstallOperationId:n}),Options:{IdempotencyKey:`mcp:store:${t.operation}:${e}:${n}`,ConcurrencyKey:"import-microi-store-package",MaxAttempts:3,RetryOnFailure:!0}}}function iY(t,e){let r=[],n=[];if(e==null||e==="")return{ok:!0,value:void 0,errors:r,warnings:n};let i;try{i=typeof e=="string"?JSON.parse(e):e}catch(s){return{ok:!1,errors:[`${t} \u4E0D\u662F\u5408\u6CD5 JSON \u6570\u7EC4\uFF1A${s instanceof Error?s.message:String(s)}`],warnings:n}}if(!Array.isArray(i))return{ok:!1,errors:[`${t} \u5FC5\u987B\u662F JSON \u6570\u7EC4`],warnings:n};let o=new Set,a=i.map((s,c)=>{let l=H(s),u=S(l,"Name","name");u||r.push(`${t}[${c}].Name \u4E0D\u80FD\u4E3A\u7A7A`);let p=tY(l,{inferActionSemantics:t!=="PageTabs"}),f=rY(l),m=l.RunBackground??l.runBackground??l.BackgroundTask??l.backgroundTask??l.IsBackgroundTask??l.isBackgroundTask,h=S(l,"ApiEngineKey","apiEngineKey");p.required&&m!==!0&&(f.declared&&!f.valid?r.push(`${t}[${c}] \u58F0\u660E\u5BA2\u6237\u7AEF\u5206\u7247\u65F6\u5FC5\u987B\u8BBE\u7F6E Workload.MaxItemsPerChunk > 0 \u4E14 Workload.Resumable=true`):f.valid?n.push(`${t}[${c}] \u5DF2\u58F0\u660E\u5BA2\u6237\u7AEF\u53EF\u6062\u590D\u5206\u7247\uFF0C\u5355\u7247\u6700\u591A ${f.maxItemsPerChunk} \u6761\uFF1B\u4FDD\u7559\u524D\u7AEF\u5206\u7247\u6267\u884C\uFF1A${p.reasons.join("\uFF1B")}`):h?(m=!0,n.push(`${t}[${c}] \u5DF2\u8BC6\u522B\u4E3A\u957F\u4EFB\u52A1\u5E76\u81EA\u52A8\u542F\u7528 RunBackground\uFF1A${p.reasons.join("\uFF1B")}`)):r.push(`${t}[${c}] \u5DF2\u8BC6\u522B\u4E3A\u957F\u4EFB\u52A1\uFF0C\u4F46\u7F3A\u5C11 ApiEngineKey\uFF1A${p.reasons.join("\uFF1B")}`));let g=H(l.BackgroundTaskOptions??l.backgroundTaskOptions);m===!0&&(!S(g,"IdempotencyKey","idempotencyKey")&&!Ss(g,"IdempotencyKeyFields","idempotencyKeyFields").length&&n.push(`${t}[${c}] \u540E\u53F0\u4EFB\u52A1\u672A\u914D\u7F6E IdempotencyKey \u6216 IdempotencyKeyFields\uFF1B\u6D89\u53CA\u5199\u64CD\u4F5C\u65F6\u5FC5\u987B\u8865\u7A33\u5B9A\u4E1A\u52A1\u5E42\u7B49\u952E`),S(g,"BusinessTable","businessTable")&&(!S(g,"BusinessStatusField","businessStatusField")||!S(g,"BusinessTaskIdField","businessTaskIdField"))&&n.push(`${t}[${c}] \u5DF2\u5173\u8054\u4E1A\u52A1\u8868\uFF0C\u4F46\u7F3A\u5C11 BusinessStatusField/BusinessTaskIdField`));let y=S(l,"TargetSysMenuId","targetSysMenuId"),x=t==="PageTabs"&&!!y;!S(l,"V8Code","v8Code")&&!S(l,"Url","url")&&!(m&&h)&&!x&&r.push(`${t}[${c}] \u5FC5\u987B\u914D\u7F6E V8Code\u3001Url\u3001\u5173\u8054\u6A21\u5757 TargetSysMenuId\uFF0C\u6216\u540E\u53F0\u4EFB\u52A1 ApiEngineKey`);let b=S(l,"Id","id")||V0();S(l,"Id","id")||n.push(`${t}[${c}] \u672A\u4F20 Id\uFF0C\u5DF2\u81EA\u52A8\u751F\u6210 ${b}`),o.has(b)&&r.push(`${t} \u4E2D\u5B58\u5728\u91CD\u590D Id\uFF1A${b}`),o.add(b);let v=S(l,"V8CodeShow","v8CodeShow");return v&&!v.includes("V8.Result")&&n.push(`${t}[${c}].V8CodeShow \u5EFA\u8BAE\u663E\u5F0F\u8D4B\u503C V8.Result=true/false`),dn({...l,Id:b,Sort:oe(l,"Sort","sort")??c*10,Name:u,Icon:S(l,"Icon","icon")||void 0,BtnStyle:S(l,"BtnStyle","btnStyle")||void 0,IsVisible:l.IsVisible??l.isVisible??!0,ShowRow:t==="MoreBtns"?l.ShowRow??l.showRow??!0:l.ShowRow??l.showRow,V8CodeShow:v||void 0,V8Code:S(l,"V8Code","v8Code")||void 0,Url:S(l,"Url","url")||void 0,RunBackground:m===void 0?void 0:!!m,BackgroundTask:l.BackgroundTask??l.backgroundTask??void 0,IsBackgroundTask:l.IsBackgroundTask??l.isBackgroundTask??void 0,ApiEngineKey:h||void 0,Workload:Object.keys(H(l.Workload??l.workload)).length?H(l.Workload??l.workload):void 0,BackgroundTaskOptions:Object.keys(g).length?g:void 0,TargetSysMenuId:y||void 0})});return{ok:r.length===0,value:JSON.stringify(a),errors:r,warnings:n}}function A2(t,e=0){if(!t||typeof t!="object"||Array.isArray(t)||e>3)return!1;let r=t,n=String(r.Label??r.label??"").trim();if(!n||n.length>80)return!1;let i=r.Fields??r.fields,o=r.Children??r.children;return Array.isArray(i)&&i.length>0&&o===void 0?i.length<=64&&i.every(a=>typeof a=="string"&&a.trim().length>0&&a.length<=128):i===void 0&&Array.isArray(o)&&o.length>0&&o.length<=32&&o.every(a=>A2(a,e+1))}function ks(t){let e={...t},r=[],n=[];(t.DiyConfig!==void 0||t.diyConfig!==void 0)&&(r.push("DiyConfig \u5DF2\u5E9F\u5F03\uFF1B\u8BF7\u65B0\u589E\u4E13\u7528\u7269\u7406\u5B57\u6BB5\uFF0C\u5E76\u901A\u8FC7 diy_field \u5143\u6570\u636E\u66B4\u9732\u914D\u7F6E\u63A7\u4EF6\u3002\u8DE8\u7AEF\u89C6\u56FE\u8BF7\u4F7F\u7528 sys_menu.ViewSchema\u3002"),delete e.DiyConfig,delete e.diyConfig);let i={MoreBtns:["MoreBtns","moreBtns"],FormBtns:["FormBtns","formBtns"],BatchSelectMoreBtns:["BatchSelectMoreBtns","batchSelectMoreBtns"],PageTabs:["PageTabs","pageTabs"],ExportMoreBtns:["ExportMoreBtns","exportMoreBtns"],PageBtns:["PageBtns","pageBtns"]};for(let[l,u]of Object.entries(i)){let p=u.find(m=>t[m]!==void 0);if(!p)continue;let f=iY(l,t[p]);r.push(...f.errors),n.push(...f.warnings),f.ok&&f.value!==void 0&&(e[l]=f.value)}let o=[["MenuBadgeEnabled","menuBadgeEnabled"],["HideTableBanner","hideTableBanner"],["HideFormBanner","hideFormBanner"],["EnableViewSchema","enableViewSchema"],["ViewConfigVersion","viewConfigVersion"]];for(let[l,u]of o){if(t[l]===void 0&&t[u]===void 0)continue;let p=t[l]??t[u],f=(l==="HideTableBanner"||l==="HideFormBanner")&&typeof p=="boolean"?p?1:0:oe(t,l,u);f!==void 0&&(e[l]=l.endsWith("Enabled")||l.endsWith("Banner")?f===1?1:0:f),delete e[u]}let a=["TableHeaders","tableHeaders"].find(l=>t[l]!==void 0);if(a){try{let l=typeof t[a]=="string"?JSON.parse(t[a]):t[a];!Array.isArray(l)||l.length>32||l.some(u=>!A2(u))?r.push("TableHeaders \u5FC5\u987B\u4E3A\u6700\u591A 32 \u4E2A\u5206\u7EC4\u7684\u6570\u7EC4\uFF0C\u6BCF\u7EC4\u5305\u542B Label \u548C Fields \u6216 Children \u6570\u7EC4\u3002"):e.TableHeaders=JSON.stringify(l)}catch{r.push("TableHeaders \u5FC5\u987B\u662F\u5408\u6CD5 JSON \u6570\u7EC4\u3002")}delete e.tableHeaders}let s=[["MenuBadgeApiEngineKey","menuBadgeApiEngineKey"],["ViewSchemaVersion","viewSchemaVersion"]];for(let[l,u]of s)t[l]===void 0&&t[u]===void 0||(e[l]=S(t,l,u),delete e[u]);let c=["ViewSchema","viewSchema"].find(l=>t[l]!==void 0);if(c){let l=Of(t[c]);r.push(...l.errors),n.push(...l.warnings),delete e.viewSchema,l.value!==void 0&&(e.ViewSchema=l.value)}return{data:e,errors:r,warnings:n}}function Zr(t,...e){for(let r of e){let n=t[r];if(typeof n=="boolean")return n;if(typeof n=="number")return n!==0;if(typeof n=="string"&&n.trim()){let i=n.trim().toLowerCase();if(["true","1","yes"].includes(i))return!0;if(["false","0","no"].includes(i))return!1}}}function oY(t,e,r,n){let i=Le(t,"v8Limit","V8Limit"),o=Le(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(o==null||o===""))return;let a=i!=null&&i!=="",s=a?Zr(t,"v8Limit","V8Limit"):Ol(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(a&&o!==void 0){let c=Zr(t,"v8Unlimited","V8Unlimited");c!==void 0&&s!==!c&&r.push(`${e}.v8Limit \u4E0E\u517C\u5BB9\u5B57\u6BB5 v8Unlimited \u7684\u8BED\u4E49\u51B2\u7A81`)}else o!==void 0&&n.push(`${e}.v8Unlimited \u5DF2\u5F03\u7528\uFF1B\u8868\u5355\u5F15\u64CE\u8BF7\u6539\u7528\u6B63\u5411\u5B57\u6BB5 v8Limit\uFF08false=\u4E0D\u9650\uFF0Ctrue=\u542F\u7528\u9650\u5236\uFF09`);return s}function aY(t,e){return{ok:e.Code===1&&H(e.Data).Passed!==!1,results:t,validation:{Code:e.Code,Msg:e.Msg??null,Data:e.Data??null}}}function Ol(t){let e=Zr(t,"v8Limit","V8Limit");if(e!==void 0)return e;let r=Zr(t,"v8Unlimited","V8Unlimited");return r===void 0?void 0:!r}function sY(t,e,r,n){let i=Le(t,"v8Limit","V8Limit"),o=Le(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(o==null||o===""))return;let a=i!=null&&i!=="",s=a?Zr(t,"v8Limit","V8Limit"):Ol(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(a&&o!==void 0){let c=Zr(t,"v8Unlimited","V8Unlimited");c!==void 0&&s!==!c&&r.push(`${e}.v8Limit \u4E0E\u517C\u5BB9\u5B57\u6BB5 v8Unlimited \u7684\u8BED\u4E49\u51B2\u7A81`)}else o!==void 0&&n.push(`${e}.v8Unlimited \u5DF2\u5F03\u7528\uFF1B\u63A5\u53E3\u5F15\u64CE\u8BF7\u6539\u7528\u6B63\u5411\u5B57\u6BB5 v8Limit\uFF08false=\u4E0D\u9650\uFF0Ctrue=\u542F\u7528\u9650\u5236\uFF09`);return s}var cY=["Detail","Edit","List","Card"],lY=["PC","Mobile","All"],uY=["ApiEngine","OpenDetail","OpenList","OpenForm","Navigate","Dial","Scan","Map","Refresh","Back","Copy"],pY=new Set(["v8code","v8codeshow","script","javascript","eval","onclick","function"]);function U0(t,e){let r=String(t??"").trim().toLowerCase();return e.find(n=>n.toLowerCase()===r)||""}function ni(t,...e){let r=new Set(e.map(i=>i.toLowerCase()));return Object.entries(t).find(([i])=>r.has(i.toLowerCase()))?.[1]}function H0(t,e="ViewSchema"){if(Array.isArray(t)){for(let r=0;r<t.length;r+=1){let n=H0(t[r],`${e}[${r}]`);if(n)return n}return""}if(!t||typeof t!="object")return"";for(let[r,n]of Object.entries(t)){if(pY.has(r.toLowerCase()))return`${e}.${r}`;let i=H0(n,`${e}.${r}`);if(i)return i}return""}function J0(t,e,r=0){if(t==null)return[];if(r>4)return[`${e} \u7684 SuccessActions \u5D4C\u5957\u4E0D\u80FD\u8D85\u8FC7 4 \u5C42`];if(!Array.isArray(t))return[`${e} \u5FC5\u987B\u662F JSON \u6570\u7EC4`];if(t.length>50)return[`${e} \u6700\u591A\u5141\u8BB8 50 \u4E2A\u52A8\u4F5C`];let n=[];return t.forEach((i,o)=>{let a=H(i);if(!Object.keys(a).length){n.push(`${e}[${o}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}let s=U0(ni(a,"ActionType","Type"),uY);if(!s){n.push(`${e}[${o}].ActionType \u4E0D\u53D7\u652F\u6301`);return}s==="ApiEngine"&&!S(a,"ApiEngineKey","apiEngineKey")&&n.push(`${e}[${o}] \u4F7F\u7528 ApiEngine \u65F6\u5FC5\u987B\u914D\u7F6E ApiEngineKey`);let c=ni(a,"SuccessActions");n.push(...J0(c,`${e}[${o}].SuccessActions`,r+1))}),n}function Of(t){let e=[],r=[];if(t==null||t==="")return{ok:!0,value:void 0,errors:e,warnings:r};let n=t;try{typeof n=="string"&&(n=JSON.parse(n)),typeof n=="string"&&(n=JSON.parse(n))}catch(c){return{ok:!1,errors:[`ViewSchema \u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${c instanceof Error?c.message:String(c)}`],warnings:r}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,errors:["ViewSchema \u5FC5\u987B\u662F JSON \u5BF9\u8C61"],warnings:r};let i=H0(n);i&&e.push(`ViewSchema \u4E0D\u5141\u8BB8\u5305\u542B\u53EF\u6267\u884C\u524D\u7AEF\u811A\u672C\u5B57\u6BB5\uFF1A${i}`);let a=ni(n,"Views");a!==void 0&&!Array.isArray(a)?e.push("ViewSchema.Views \u5FC5\u987B\u662F JSON \u6570\u7EC4"):Array.isArray(a)?(a.length>100&&e.push("ViewSchema.Views \u6700\u591A\u5141\u8BB8 100 \u4E2A\u89C6\u56FE"),a.forEach((c,l)=>{let u=H(c);if(!Object.keys(u).length){e.push(`ViewSchema.Views[${l}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}U0(ni(u,"Scene"),cY)||e.push(`ViewSchema.Views[${l}].Scene \u4E0D\u53D7\u652F\u6301`);let p=ni(u,"Device");p!==void 0&&!U0(p,lY)&&e.push(`ViewSchema.Views[${l}].Device \u4E0D\u53D7\u652F\u6301`);let f=ni(u,"Layout","LayoutJson");if(typeof f=="string")try{f=JSON.parse(f)}catch{e.push(`ViewSchema.Views[${l}].Layout \u4E0D\u662F\u5408\u6CD5 JSON`);return}if(f==null)return;let m=H(f);if(!Object.keys(m).length&&(typeof f!="object"||Array.isArray(f))){e.push(`ViewSchema.Views[${l}].Layout \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}e.push(...J0(ni(m,"Actions","ActionSchema"),`ViewSchema.Views[${l}].Layout.Actions`));let h=ni(m,"Blocks","Sections");h!==void 0&&!Array.isArray(h)?e.push(`ViewSchema.Views[${l}].Layout.Blocks \u5FC5\u987B\u662F JSON \u6570\u7EC4`):Array.isArray(h)&&(h.length>100&&e.push(`ViewSchema.Views[${l}].Layout.Blocks \u6700\u591A\u5141\u8BB8 100 \u4E2A\u533A\u5757`),h.forEach((g,y)=>{let x=H(g);e.push(...J0(ni(x,"Actions"),`ViewSchema.Views[${l}].Layout.Blocks[${y}].Actions`))}))})):r.push("ViewSchema.Views \u4E3A\u7A7A\uFF0C\u5BA2\u6237\u7AEF\u5C06\u4F7F\u7528\u73B0\u6709\u6A21\u5757\u548C\u8868\u5355\u914D\u7F6E\u3002");let s=JSON.stringify(n);return Buffer.byteLength(s,"utf8")>512*1024&&e.push("ViewSchema \u4E0D\u80FD\u8D85\u8FC7 512KB"),{ok:e.length===0,value:s,errors:e,warnings:r}}function R2(t,e){let r=[],n=t.toLowerCase();if(n==="fileupload")return{config:o2(e),warnings:r};if(n==="keyvalue"){let i=S(e,"data","options"),o=i?i.split(/[,,;;\n]/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c]=a.split("|");return{Key:(s||"").trim(),Value:(c||s||"").trim()}}):ii(e.items).map(a=>({Key:S(a,"Key","key"),Value:S(a,"Value","label","name")}));return{data:JSON.stringify(o),config:{DataSource:"KeyValue",SelectLabel:"Value",SelectSaveField:"Key",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="data"){let i=S(e,"data","options"),o=i?i.split(/[,,;;\n]/).map(a=>a.trim()).filter(Boolean):Array.isArray(e.items)?e.items:[];return{data:JSON.stringify(o),config:{DataSource:"Data",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="sql"){let i=S(e,"sql","Sql");return i||r.push("SQL \u6570\u636E\u6E90\u7F3A\u5C11 sql"),{config:{DataSource:"Sql",Sql:i,SelectLabel:S(e,"selectLabel","SelectLabel")||"Name",SelectSaveField:S(e,"selectSaveField","SelectSaveField")||"Id",DataSourceSqlRemote:e.dataSourceSqlRemote??e.DataSourceSqlRemote??!0,EnableSearch:e.enableSearch??e.EnableSearch??!0},warnings:r}}if(n==="apiengine"){let i=S(e,"apiEngineKey","DataSourceApiEngineKey");return i||r.push("\u63A5\u53E3\u5F15\u64CE\u6570\u636E\u6E90\u7F3A\u5C11 apiEngineKey"),{config:{DataSource:"ApiEngine",DataSourceApiEngineKey:i,SelectLabel:S(e,"selectLabel")||"name",SelectSaveField:S(e,"selectSaveField")||"id"},warnings:r}}if(n==="datasource"){let i=S(e,"dataSourceId","DataSourceId");return i||r.push("\u6570\u636E\u6E90\u5F15\u64CE\u914D\u7F6E\u7F3A\u5C11 dataSourceId"),{config:{DataSource:"DataSource",DataSourceId:i,SelectLabel:S(e,"selectLabel")||"Name",SelectSaveField:S(e,"selectSaveField")||"Id"},warnings:r}}if(n==="autonumber")return{config:{AutoNumberFixed:S(e,"prefix","AutoNumberFixed"),AutoNumberLength:oe(e,"length","AutoNumberLength")??4},warnings:r};if(n==="datetime")return{config:{DateTimeType:S(e,"dateTimeType","DateTimeType")||"datetime"},warnings:r};if(n==="joinform"){let i=S(e,"tableId"),o=S(e,"tableName"),a=S(e,"joinFieldName");return!i&&!o&&r.push("JoinForm \u7F3A\u5C11 tableId/tableName\uFF0C\u7981\u6B62\u4FDD\u5B58\u672A\u89E3\u6790\u76EE\u6807\u8868\u7684\u914D\u7F6E"),a||r.push("JoinForm \u7F3A\u5C11 joinFieldName\uFF1B\u8BE5\u5B57\u6BB5\u5FC5\u987B\u662F\u5F53\u524D\u4E3B\u8868\u4E2D\u4FDD\u5B58\u76EE\u6807\u8BB0\u5F55 Id \u7684\u771F\u5B9E\u5B57\u6BB5\u540D"),{config:{JoinForm:dn({TableId:i,TableName:o,JoinFieldName:a})},warnings:r}}return r.push(`\u672A\u77E5 sourceType: ${t}\uFF0C\u5DF2\u8FD4\u56DE\u7A7A\u914D\u7F6E`),{config:{},warnings:r}}function B0(t,e){let r=Kr(t);return dn({Id:t.id,AsName:e?.asName||"",Name:t.name,Label:t.label||t.name,TableId:t.tableId,TableName:t.tableName,TableDescription:t.tableDescription||t.tableName,DisplayType:e?.displayType||(If.has(r)||Jr(t)||r==="numbertext"?"In":"Out"),DisplaySelect:e?.displaySelect??["opentable","joinform","department","selecttree"].includes(r),Equal:e?.equal??(If.has(r)||r==="numbertext"?!0:void 0),IsVisible:!0})}function _s(t,e,r,n,i){return n.map(o=>{let a=s2(t,e,o.ref)||s2(t,r,o.ref)||(Pl(o.ref)?C2(e,r,o.ref):void 0);if(!a)throw new Error(`${i}: unknown field "${o.ref}" on table "${r||e}"`);return{meta:a,ref:o}})}function dt(t,...e){for(let r of e){let n=Le(t,r);if(!(n==null||n===""))return typeof n=="string"?n:JSON.stringify(n)}return""}var dY=new Set(["id","osclient","isdeleted","createuserid","updateuserid","deleteuserid","tenantid","storeid","userid","userids","roleid","roleids","parentid","parentids","class","code","enname","endescription"]),Q0=new Set(["button","divider","collapsegroup","tabs","alert","statictext","html","devcomponent"]),fY=new Set(["textarea","richtext","codeeditor","jsontable","imgupload","fileupload","tablechild","map","maparea","jointable","opentable","treecheckbox","transfer"]),mY=new Set(["text","textarea","select","multipleselect","radio","checkbox","datetime","date","numbertext","autonumber","switch","department","address","cascader","selecttree","opentable","joinform","autocomplete","taginput"]),If=new Set(["select","multipleselect","radio","checkbox","switch","department","selecttree","opentable","joinform","cascader"]);function br(t){return(t||"").trim().toLowerCase()}function _t(t){return`${t.name||""} ${t.label||""} ${t.component||""} ${t.type||""}`.toLowerCase()}function be(t,e){return e.some(r=>t.includes(r.toLowerCase()))}function Kr(t){return br(t.component||"Text")}function hY(t){return Q0.has(Kr(t))}function gY(t){return fY.has(Kr(t))}function yY(t){let e=t.name||"",r=br(e).replace(/[_\-\s]+/g,"");return!!(dY.has(r)||/^(.*id|.*ids|.*idlist|.*guid)$/.test(r)&&!/idcard|identity|cardid/.test(r)||/Id$|ID$|Ids$|IDs$|Guid$/u.test(e)&&!/IdCard|IDCard|Identity|CardId/u.test(e))}function Nl(t){return Pl(t.name)&&!["CreateTime","UpdateTime","UserName"].some(e=>e.toLowerCase()===t.name.toLowerCase())||yY(t)||hY(t)||gY(t)?!0:Kr(t).includes("hidden")}function Vi(t){let e=new Set;return t.filter(r=>{let n=r.id||r.name;return!n||e.has(n)?!1:(e.add(n),!0)})}function Hr(t,e){return t.map((r,n)=>({field:r,index:n,score:e(r)})).sort((r,n)=>n.score-r.score||r.index-n.index).map(r=>r.field)}function Nf(t){let e=br(t.type);return Kr(t)==="numbertext"||e.startsWith("decimal")||e==="int"||e==="bigint"}function Jr(t){let e=_t(t);return Kr(t)==="datetime"||be(e,["time","date","\u65E5\u671F","\u65F6\u95F4"])}function bY(t){let e=Kr(t),r=If.has(e)||e==="numbertext"||e==="rate"||e==="progress";return{ref:t.name,displayType:r||Jr(t)?"In":"Out",displaySelect:["opentable","joinform","department","selecttree"].includes(e),equal:r?!0:void 0}}function c2(t){let e=_t(t),r=0;return be(e,["name","title","no","code","account","phone","mobile","email","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7","\u8D26\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])&&(r+=50),be(e,["status","state","type","category","level","class","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])&&(r+=45),be(e,["customer","member","user","owner","\u8D1F\u8D23\u4EBA","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8054\u7CFB\u4EBA"])&&(r+=35),Jr(t)&&(r+=25),Nf(t)&&!be(e,["phone","mobile","tel","\u7535\u8BDD","\u624B\u673A"])&&(r+=15),Kr(t)==="textarea"&&(r-=25),r}function Z0(t){let e=_t(t),r=0;return be(e,["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])&&(r+=70),be(e,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])&&(r+=45),be(e,["customer","member","user","owner","phone","mobile","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u7535\u8BDD","\u624B\u673A"])&&(r+=35),be(e,["amount","money","price","total","count","qty","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D"])&&(r+=30),Jr(t)&&(r+=15),Kr(t)==="autonumber"&&(r+=55),r}function vY(t){return Vi(t.filter(Nl))}function Ml(t){let e=t.filter(n=>!Nl(n)),r=e.length?e:t;return Vi(Hr(r,Z0)).slice(0,Math.min(12,r.length))}function xY(t){let e=t.filter(n=>!Nl(n)&&mY.has(Kr(n))),r=Hr(e,c2).filter(n=>c2(n)>0);return Vi(r.length?r:e).slice(0,Math.min(8,e.length))}function wY(t){let e=t.filter(r=>!Nl(r)&&(Jr(r)||Nf(r)||br(r.name)==="sort"));return Vi(Hr(e,r=>{let n=_t(r);return be(n,["update","\u4FEE\u6539"])?80:be(n,["create","\u521B\u5EFA"])?75:br(r.name)==="sort"?70:be(n,["amount","money","price","total","count","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?60:20})).slice(0,Math.min(8,e.length))}function P2(t){let e=["phone","mobile","tel","status","state","sort","rate","level","\u7535\u8BDD","\u624B\u673A","\u72B6\u6001","\u6392\u5E8F","\u7B49\u7EA7"],r=t.filter(n=>{let i=_t(n);return!Nl(n)&&Nf(n)&&!be(i,e)&&be(i,["amount","money","price","total","count","qty","score","point","balance","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D","\u9762\u79EF","\u91CD\u91CF"])});return Vi(Hr(r,n=>be(_t(n),["amount","money","price","total","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D"])?80:40)).slice(0,6)}function _Y(t){let e=Ml(t),r=Hr(e,o=>be(_t(o),["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])?100:0)[0],n=Hr(e.filter(o=>o!==r),o=>be(_t(o),["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?80:0),i=e.filter(o=>o!==r&&!n.slice(0,1).includes(o));return Vi([r,...n.slice(0,1),...i].filter(Boolean)).slice(0,4)}function SY(t){return Hr(Ml(t),e=>be(_t(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])?100:0).filter(e=>be(_t(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])).slice(0,2)}function EY(t){return Hr(Ml(t),e=>{let r=_t(e);return be(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?90:Jr(e)?60:0}).filter(e=>{let r=_t(e);return Jr(e)||be(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])}).slice(0,3)}function $2(t,e=0){let r=H(t),n=S(r,"name","Name");return n?{id:S(r,"id","Id")||n,name:n,label:S(r,"label","Label")||n,tableId:S(r,"tableId","TableId"),tableName:S(r,"tableName","TableName"),tableDescription:S(r,"tableDescription","TableDescription"),component:S(r,"component","Component")||"Text",type:S(r,"type","Type")||"varchar(500)"}:null}function Mf(t){let e=$2(t);if(!e)return 150;let r=_t(e),n=Kr(e);return["richtext","textarea","address","map","maparea","fileupload","imgupload"].includes(n)||be(r,["address","remark","description","content","\u5730\u5740","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247"])?240:be(r,["name","title","subject","customer","company","\u540D\u79F0","\u6807\u9898","\u4E3B\u9898","\u5BA2\u6237","\u4F01\u4E1A"])?200:Jr(e)?170:Nf(e)?140:n==="autonumber"||be(r,["phone","mobile","email","code","number","\u7F16\u53F7","\u5355\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])?160:If.has(n)||be(r,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?130:150}function ri(t,e={}){return{Name:t.name,Label:t.label||t.name,...e}}function ea(t,e,r){let n=[];for(let i of t)if(!(!i?.name||r.has(br(i.name)))&&(r.add(br(i.name)),n.push(i),n.length>=e))break;return n}function ew(t,e,r=""){let n=e.map($2).filter(Boolean),i=Ml(n),o=String(t||r||n[0]?.tableDescription||n[0]?.tableName||"\u4E1A\u52A1\u6A21\u5757").trim(),a=String(r||n[0]?.tableDescription||"").trim(),s=a&&a!==o?a:`${o}\u7684\u4E1A\u52A1\u6570\u636E\u3001\u8FDB\u5EA6\u4E0E\u5173\u952E\u6307\u6807`,c=Hr(i,R=>{let F=_t(R);return be(F,["title","subject","\u6807\u9898","\u4E3B\u9898"])?150:be(F,["name","\u540D\u79F0"])?130:Kr(R)==="autonumber"||be(F,["no","code","number","\u7F16\u53F7","\u5355\u53F7","\u7F16\u7801"])?110:Z0(R)})[0]||i[0],l=Hr(i.filter(R=>R!==c),R=>be(_t(R),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])?100:0).filter(R=>be(_t(R),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])),u=P2(n).filter(R=>R!==c),p=Hr(n.filter(Jr),R=>be(_t(R),["create","\u521B\u5EFA"])?100:50),f=Hr(i.filter(R=>R!==c&&!l.includes(R)&&!u.includes(R)),R=>{let F=_t(R);return be(F,["customer","member","user","owner","contact","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u8054\u7CFB\u4EBA"])?90:Jr(R)?70:Z0(R)}).slice(0,1),m=Vi([...l.slice(0,1),...u.slice(0,1)]),h=Vi([c,...f,...m].filter(Boolean)).map(R=>R.name),g=c?Math.min(520,Math.max(340,Mf(c)+f.length*28+m.length*70)):0,y=[{Icon:"fas fa-chart-column",Tone:"primary"},{Icon:"fas fa-calculator",Tone:"success"}],x=u.slice(0,2).map((R,F)=>({Key:`Aggregate:${R.name}`,Label:`${R.label||R.name}\u5408\u8BA1`,Source:"Field",Field:R.name,...y[F]}));x.push({Key:"DataCount",Label:"\u7B5B\u9009\u7ED3\u679C",Source:"DataCount",Icon:"fas fa-layer-group",Tone:"info"}),x.length<3&&x.push({Key:"PageCount",Label:"\u672C\u9875\u5C55\u793A",Source:"PageCount",Icon:"fas fa-list-check",Tone:"warning"});let b=new Set(c?[br(c.name)]:[]),v=ea(f,1,b),_=ea(l,1,b),w=ea(l,1,b),C=ea(u,1,b),E=ea(p,2,b),T=ea(i,2,b),A=ea([...u,...p],2,b),I={Title:o,Description:s,Metrics:x};return{Views:[{Key:"auto-list-pc",Scene:"List",Device:"PC",Priority:100,Layout:{Hero:I,List:{Density:"Compact",Columns:c?[{Key:`composite:${c.name}`,Field:c.name,Lines:f.map(R=>ri(R,{Icon:Jr(R)?"fas fa-clock":"fas fa-circle-info",Tone:"info"})),TrailingFields:m.map(R=>ri(R,{Icon:l.includes(R)?"fas fa-circle-check":"fas fa-coins",Tone:l.includes(R)?"success":"warning",DisplayStyle:l.includes(R)?"Tag":"Text"})),RequiredFields:h,Align:"Left",MinWidth:g}]:[]}}},{Key:"auto-card-mobile",Scene:"Card",Device:"Mobile",Priority:100,Layout:{Hero:{...I,Metrics:x.map(R=>({...R}))},Card:{Preset:"Business",AvatarTextField:c?.name||"",TitleField:c?.name||"",SubtitleFields:v.map(R=>ri(R,{Icon:"fas fa-circle-info",Tone:"info"})),StatusFields:_.map(R=>ri(R,{DisplayStyle:"Tag",Icon:"fas fa-circle-check",Tone:"success"})),TopFields:w.map(R=>ri(R,{DisplayStyle:"Tag",Icon:"fas fa-tag",Tone:"primary"})),RightFields:C.map(R=>ri(R,{Icon:"fas fa-coins",Tone:"danger",FontWeight:"700"})),Fields:T.map(R=>ri(R)),MetaFields:E.map(R=>ri(R,{Icon:"fas fa-clock",Tone:"info"})),BottomFields:A.map(R=>ri(R,{Icon:Jr(R)?"fas fa-calendar":"fas fa-chart-simple",Tone:"warning"})),HideIndex:!0,ShowCreateTime:E.length===0,ShowUpdateTime:!1}}}]}}function kY(t,e,r){let n=t.length?t:[C2(e,r,"CreateTime")],i=n.find(o=>br(o.name)==="createtime")||n.find(o=>br(o.name)==="updatetime")||n.find(o=>br(o.name)==="sort");if(i)return JSON.stringify([{Id:i.id,Name:i.name,Type:br(i.name)==="sort"?"ASC":"DESC",Sort:0}])}function TY(t,e,r,n){let i=Le(t,"DefaultOrderBy");if(i!=null&&i!=="")return typeof i=="string"?i:JSON.stringify(i);let o=Le(t,"defaultOrderBy");if(o!=null&&o!==""){let s=Array.isArray(o)||typeof o=="string"&&o.trim().startsWith("[")?Vr({value:o},"value"):[{ref:String(o).trim(),type:"DESC"}];return JSON.stringify(_s(e,r,n,s,"module.defaultOrderBy").map(({meta:c,ref:l},u)=>({Id:c.id,Name:c.name,Type:l.type||"DESC",Sort:u})))}let a=Vr(t,"orderBy","OrderBy","defaultSort","DefaultSort","sortBy","SortBy");if(a.length)return JSON.stringify(_s(e,r,n,a,"module.defaultOrderBy").map(({meta:s,ref:c},l)=>({Id:s.id,Name:s.name,Type:c.type||"DESC",Sort:l})))}function CY(t,e,r,n){if(!r&&!n)return{};let i=Es(e,r).length?Es(e,r):Es(e,n),o={},a=Vr(t,"searchFields","SearchFields","searchFieldNames","SearchFieldNames"),s=a.length?_s(e,r,n,a,"module.searchFields"):xY(i).map(m=>({meta:m,ref:bY(m)}));!dt(t,"searchFieldIds","SearchFieldIds")&&s.length&&(o.SearchFieldIds=JSON.stringify(s.map(({meta:m,ref:h})=>B0(m,h))));let c=Vr(t,"listFields","ListFields","tableFields","TableFields","columns","Columns"),l=c.length?_s(e,r,n,c,"module.listFields"):Ml(i).map(m=>({meta:m,ref:{ref:m.name}}));!dt(t,"tableDiyFieldIds","TableDiyFieldIds")&&l.length&&(o.TableDiyFieldIds=JSON.stringify(l.map(({meta:m})=>m.id))),!dt(t,"selectFields","SelectFields")&&l.length&&(o.SelectFields=JSON.stringify(l.map(({meta:m,ref:h})=>B0(m,h))));let u=[{canonical:"SortFieldIds",explicitKeys:["sortFieldIds","SortFieldIds"],refKeys:["sortFields","SortFields"]},{canonical:"NotShowFields",explicitKeys:["notShowFields","NotShowFields"],refKeys:["hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName"]},{canonical:"InTableEditFields",explicitKeys:["inTableEditFields","InTableEditFields"],refKeys:["editableFields","EditableFields","inTableEditFieldsByName","InTableEditFieldsByName"]},{canonical:"MobileListFields",explicitKeys:["mobileListFields","MobileListFields"],refKeys:["mobileFields","MobileFields"],objectArray:!0},{canonical:"CardTitleTagFields",explicitKeys:["cardTitleTagFields","CardTitleTagFields"],refKeys:["cardTitleFields","CardTitleFields"],objectArray:!0},{canonical:"CardBottomTagFields",explicitKeys:["cardBottomTagFields","CardBottomTagFields"],refKeys:["cardBottomFields","CardBottomFields"],objectArray:!0}];for(let m of u){if(dt(t,...m.explicitKeys))continue;let h=Vr(t,...m.refKeys),g={SortFieldIds:wY(i),NotShowFields:vY(i),MobileListFields:_Y(i),CardTitleTagFields:SY(i),CardBottomTagFields:EY(i),InTableEditFields:[]};if(!h.length&&!g[m.canonical]?.length)continue;let y=h.length?_s(e,r,n,h,`module.${m.canonical}`):g[m.canonical].map(x=>({meta:x,ref:{ref:x.name}}));o[m.canonical]=JSON.stringify(m.objectArray?y.map(({meta:x,ref:b})=>B0(x,b)):y.map(({meta:x})=>x.id))}let p=Vr(t,"statisticsFieldNames","StatisticsFieldNames","statFields","StatFields");if(!dt(t,"statisticsFields","StatisticsFields")){let m=p.length?_s(e,r,n,p,"module.statisticsFields"):P2(i).map(h=>({meta:h,ref:{ref:h.name,type:"Sum"}}));m.length&&(o.StatisticsFields=JSON.stringify(m.map(({meta:h,ref:g})=>({Id:h.id,Type:g.type||"Sum"}))))}let f=TY(t,e,r,n)||(dt(t,"DefaultOrderBy","defaultOrderBy")?void 0:kY(i,r,n));return f&&(o.DefaultOrderBy=f),o}function l2(t,e,r){let n=ii(H(e).Tables);for(let i of n){let o=S(i,"Id","id"),a=S(i,"Name","name");if(!o||!a)continue;r?.set(a.toLowerCase(),o);let s=Le(i,"_Fields","Fields","fields"),c=Array.isArray(s)?ii(s):[];for(let l of c){let u=S(l,"Id","id"),p=S(l,"Name","name");!u||!p||T2(t,{id:u,name:p,label:S(l,"Label","label")||p,tableId:o,tableName:a,tableDescription:S(i,"Description","description")||a,component:S(l,"Component","component")||"Text",type:S(l,"Type","type")||"varchar(255)"})}}}function Ot(t){return br(S(t,"component","Component")||"Text")}function IY(t){return`${S(t,"name","Name")} ${S(t,"label","Label")} ${S(t,"component","Component")}`.toLowerCase()}function AY(t,e){let r=IY(t),n=Ot(t);return["imgupload","fileupload","richtext","codeeditor","jsontable","tablechild","map","maparea","textarea"].includes(n)||be(r,["remark","note","content","file","image","attach","map","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247","\u5730\u56FE"])?"attachment":be(r,["phone","mobile","email","address","city","contact","\u8054\u7CFB\u4EBA","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1","\u5730\u5740","\u57CE\u5E02"])?"contact":be(r,["status","state","type","category","amount","money","price","count","date","time","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF","\u65F6\u95F4","\u65E5\u671F"])?"business":e<8?"basic":"extra"}function K0(t){let e=ie(t,"fields","Fields"),r=Le(t,"tabs","Tabs"),n=new Map,i=oe(t,"column","Column")??(e.length>6?2:void 0);if(r!=null&&r!=="")return{fieldTabs:n,column:i};let o=e.filter(l=>!Q0.has(Ot(l)));if(o.length<=12)return{fieldTabs:n,column:i};let a={basic:{Name:"\u57FA\u7840\u4FE1\u606F",Icon:"fas fa-id-card",Sort:10},contact:{Name:"\u8054\u7CFB\u4FE1\u606F",Icon:"fas fa-address-book",Sort:20},business:{Name:"\u4E1A\u52A1\u4FE1\u606F",Icon:"fas fa-briefcase",Sort:30},attachment:{Name:"\u9644\u4EF6\u5907\u6CE8",Icon:"fas fa-paperclip",Sort:40},extra:{Name:"\u6269\u5C55\u4FE1\u606F",Icon:"fas fa-layer-group",Sort:50}},s=new Set;return o.forEach((l,u)=>{let p=S(l,"name","Name");if(!p||S(l,"tab","Tab"))return;let f=AY(l,u);n.set(p,f),s.add(f)}),{tabs:["basic","contact","business","attachment","extra"].filter(l=>s.has(l)).map(l=>({Id:l,Name:a[l].Name,Icon:a[l].Icon,Sort:a[l].Sort})),fieldTabs:n,column:i}}function q0(t){let e=[],r=[],n=[],i=ie(t,"roles","Roles"),o=ie(t,"tables","Tables"),a=ie(t,"engines","Engines"),s=ie(t,"modules","Modules"),c=ie(t,"events","Events"),l=ie(t,"dataSources","DataSources"),u=ie(t,"pages","Pages"),p=ie(t,"printTemplates","PrintTemplates"),f=ie(t,"workflows","Workflows"),m=ie(t,"jobs","Jobs"),h=ie(t,"permissions","Permissions"),g=new Map,y=new Set(a.map(b=>S(b,"apiEngineKey","ApiEngineKey").toLowerCase()).filter(Boolean));!o.length&&!a.length&&!s.length&&!u.length&&r.push("Manifest \u672A\u58F0\u660E tables/engines/modules/pages\uFF0C\u53EF\u80FD\u4E0D\u662F\u5B8C\u6574\u7CFB\u7EDF\u8BA1\u5212");let x=UY(t);return e.push(...x.errors),r.push(...x.warnings),i.forEach(b=>n.push(`save_role ${S(b,"name","Name")}`)),o.forEach((b,v)=>{let _=S(b,"name","Name");_||e.push(`tables[${v}].name \u4E0D\u80FD\u4E3A\u7A7A`),oY(b,`tables[${v}]`,e,r);let w=Le(b,"readPrimary","ReadPrimary");w!=null&&w!==0&&w!==1&&e.push(`tables[${v}].readPrimary \u5FC5\u987B\u662F null\u30010 \u6216 1`),Object.hasOwn(b,"readPrimary")&&Object.hasOwn(b,"ReadPrimary")&&b.readPrimary!==b.ReadPrimary&&e.push(`tables[${v}].readPrimary \u4E0E ReadPrimary \u4E0D\u4E00\u81F4`),n.push(`create_table ${_||`(index ${v})`}`),K0(b).tabs?.length&&r.push(`table ${_||`(index ${v})`} has many fields; generator will create diy_table.Tabs and assign empty field Tab values automatically`),_&&g.set(_.toLowerCase(),new Set),ie(b,"fields","Fields").forEach((z,j)=>{let K=S(z,"name","Name"),ee=S(z,"label","Label");K||e.push(`tables[${v}].fields[${j}].name \u4E0D\u80FD\u4E3A\u7A7A`),ee||e.push(`tables[${v}].fields[${j}].label \u4E0D\u80FD\u4E3A\u7A7A`),_&&K&&g.get(_.toLowerCase())?.add(K.toLowerCase()),_&&ee&&g.get(_.toLowerCase())?.add(ee.toLowerCase()),n.push(`add_field ${_}.${K}`)});let E=Dl(b);n.push(`configure_form_banner ${_||`(index ${v})`}`);let T=g.get(_.toLowerCase())||new Set,A=(z,j)=>{z&&!T.has(z.toLowerCase())&&!Pl(z)&&e.push(`${j} references unknown field "${z}" on table "${_}"`)};A(S(E,"FormBannerTitleField"),`tables[${v}].formBanner.titleField`),A(S(E,"FormBannerSubtitleField"),`tables[${v}].formBanner.subtitleField`),A(S(E,"FormBannerImageField"),`tables[${v}].formBanner.imageField`),A(S(E,"FormBannerBackgroundField"),`tables[${v}].formBanner.backgroundField`),$f(JSON.parse(S(E,"FormBannerTagFields")||"[]")).forEach((z,j)=>{let K=typeof z=="string"?z:S(H(z),"Field","field","Name","name");A(K,`tables[${v}].formBanner.tagFields[${j}]`)}),$f(JSON.parse(S(E,"FormBannerMetrics")||"[]")).forEach((z,j)=>{let K=H(z),ee=typeof z=="string"?z:S(K,"Field","field","Name","name");A(ee,`tables[${v}].formBanner.metrics[${j}]`);let _e=S(K,"ApiEngineKey","apiEngineKey");_e&&!y.has(_e.toLowerCase())&&r.push(`tables[${v}].formBanner.metrics[${j}] references ApiEngineKey "${_e}" not declared in this manifest; it must already exist in the target tenant`)});let F=new Set(ie(b,"fields","Fields").filter(z=>{let j=Ot(z);return!["opentable","phonesms","tablechild","button","divider","collapsegroup","tabs","alert","statictext","html"].includes(j)&&(j!=="devcomponent"||!!S(z,"type","Type"))}).map(z=>S(z,"name","Name").toLowerCase()).filter(Boolean));["id","createtime","updatetime","userid","username","isdeleted"].forEach(z=>F.add(z)),ie(b,"indexes","Indexes").forEach((z,j)=>{let K=Ss(z,"columns","Columns");K.length||e.push(`tables[${v}].indexes[${j}].columns \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5`);for(let ee of K)F.has(ee.toLowerCase())||e.push(`tables[${v}].indexes[${j}] references unknown physical field "${ee}" on table "${_}"`);K.some((ee,_e)=>K.findIndex(me=>me.toLowerCase()===ee.toLowerCase())!==_e)&&e.push(`tables[${v}].indexes[${j}] \u5305\u542B\u91CD\u590D\u5B57\u6BB5`),n.push(`create_index ${_}.${S(z,"name","Name")||K.join("_")}`)})}),l.forEach(b=>n.push(`save_data_source ${S(b,"dataSourceKey","DataSourceKey")}`)),a.forEach((b,v)=>{let _=S(b,"apiEngineKey","ApiEngineKey");_||e.push(`engines[${v}].apiEngineKey \u4E0D\u80FD\u4E3A\u7A7A`),sY(b,`engines[${v}]`,e,r),n.push(`upsert_engine ${_}`)}),c.forEach(b=>n.push(`save_event ${S(b,"formEngineKey","FormEngineKey")}/${S(b,"eventType","EventType")}`)),s.forEach(b=>{let v=ks(b);e.push(...v.errors),r.push(...v.warnings);let _=S(b,"table","tableName","diyTableName","DiyTableName"),w=S(b,"name","Name"),C=S(b,"openType","OpenType");if(C.toLowerCase()==="workflow"){let I=S(b,"flowName","FlowName"),R=S(b,"flowDesignId","FlowDesignId");!I&&!R&&e.push(`modules.${w||"(unnamed)"}.flowName \u6216 flowDesignId \u5FC5\u987B\u6307\u5411\u5DF2\u542F\u7528\u6D41\u7A0B`),I&&!f.some(z=>S(H(z.FlowDesign??z.flowDesign),"FlowName","flowName")===I)&&e.push(`modules.${w||"(unnamed)"}.flowName ${I} \u672A\u5728\u672C\u6B21 workflows \u4E2D\u58F0\u660E\uFF1B\u73B0\u6709\u6D41\u7A0B\u8BF7\u4F7F\u7528 flowDesignId`);let F=f.find(z=>S(H(z.FlowDesign??z.flowDesign),"FlowName","flowName")===I);if(F){let z=H(F.FlowDesign??F.flowDesign);(oe(z,"IsEnable","isEnable")===0||Le(z,"IsEnable","isEnable")===!1)&&e.push(`modules.${w||"(unnamed)"}.flowName ${I} \u6307\u5411\u7981\u7528\u6D41\u7A0B`);let j=S(b,"table","tableName","diyTableName","DiyTableName"),K=S(z,"table","tableName","diyTableName","DiyTableName");j&&K&&j.toLowerCase()!==K.toLowerCase()&&e.push(`modules.${w||"(unnamed)"} \u7684 table \u4E0E\u6D41\u7A0B ${I} \u7684\u4E1A\u52A1\u8868\u4E0D\u4E00\u81F4`)}S(b,"diyTableId","DiyTableId","table","tableName","diyTableName","DiyTableName")||e.push(`modules.${w||"(unnamed)"} \u5FC5\u987B\u7ED1\u5B9A\u4E0E\u6D41\u7A0B\u76F8\u540C\u7684 diy_table`)}let E=S(b,"microServiceKey","MicroServiceKey"),T=S(b,"microServiceRoutePath","MicroServiceRoutePath");if(["microservice","codeform"].includes(C.toLowerCase())||!!(oe(b,"isMicroiService","IsMicroiService")===1||E||T||S(b,"microServiceId","MicroServiceId")||S(b,"microServicePageId","MicroServicePageId"))){if(E||e.push(`modules.${w||"(unnamed)"}.microServiceKey \u4E0D\u80FD\u4E3A\u7A7A`),T||e.push(`modules.${w||"(unnamed)"}.microServiceRoutePath \u4E0D\u80FD\u4E3A\u7A7A`),T)try{Y0(T)}catch(I){e.push(`modules.${w||"(unnamed)"}.microServiceRoutePath ${I instanceof Error?I.message:String(I)}`)}n.push(`resolve_microservice_binding ${E||"(missing)"}${T||"/(missing)"}`)}if(_&&g.has(_.toLowerCase())){let I=g.get(_.toLowerCase())||new Set,R=[["listFields",Vr(b,"listFields","ListFields","tableFields","TableFields","columns","Columns")],["searchFields",Vr(b,"searchFields","SearchFields","searchFieldNames","SearchFieldNames")],["sortFields",Vr(b,"sortFields","SortFields")],["hiddenFields",Vr(b,"hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName")],["mobileFields",Vr(b,"mobileFields","MobileFields")]];for(let[F,z]of R)for(let j of z)!I.has(j.ref.toLowerCase())&&!Pl(j.ref)&&e.push(`modules.${w||_}.${F} references unknown field "${j.ref}" on table "${_}"`)}_&&!Vr(b,"listFields","ListFields","tableFields","TableFields","columns","Columns").length&&!dt(b,"TableDiyFieldIds","SelectFields")&&r.push(`module ${w||_} has no listFields; generator will use the first business fields from ${_}`),n.push(`create_or_update_module ${S(b,"name","Name")}`)}),h.forEach(b=>n.push(`set_permission ${S(b,"roleId","RoleId")||"admin"}`)),u.forEach((b,v)=>{let _=ti(b.json??b.JsonObj??b.JsonStr??b);e.push(..._.errors.map(w=>`pages[${v}]: ${w}`)),r.push(..._.warnings.map(w=>`pages[${v}]: ${w}`)),n.push(`save_page ${S(b,"title","Title")}`)}),p.forEach((b,v)=>{let _=Yo(b.PageObj??b.pageObj),w=Qo(b.PrintObj??b.printObj);e.push(..._.errors.map(C=>`printTemplates[${v}].PageObj: ${C}`)),r.push(..._.warnings.map(C=>`printTemplates[${v}].PageObj: ${C}`)),e.push(...w.errors.map(C=>`printTemplates[${v}].PrintObj: ${C}`)),r.push(...w.warnings.map(C=>`printTemplates[${v}].PrintObj: ${C}`)),n.push(`save_print_template ${S(b,"title","Title")}`)}),f.forEach((b,v)=>{let _=W0(b);e.push(..._.errors.map(w=>`workflows[${v}]: ${w}`)),r.push(..._.warnings.map(w=>`workflows[${v}]: ${w}`)),n.push(`save_workflow ${S(H(b.FlowDesign??b.flowDesign??b),"FlowName","flowName","name")}`)}),m.forEach(b=>n.push(`save_job ${S(b,"jobName","JobName")}`)),{plan:n,errors:e,warnings:r}}function tw(t){return{flow:H(t.FlowDesign??t.flowDesign??t),nodes:ie(t,"Nodes","nodes"),lines:ie(t,"Lines","lines")}}function gt(t){return S(t,"Id","id","NodeId","nodeId")}function Ur(t){return S(t,"NodeName","nodeName","Name","name")}function Af(t){return S(t,"NodeType","nodeType","Type","type")}function Rf(t){return Af(t)==="Start"}function u2(t){return["End","AutoEnd"].includes(Af(t))}var RY=new Set(["Start","Auto","Business","End","AutoEnd","Countersign","Approve"]),PY=new Set(["Approve","Countersign","End"]),O2=["Users","Roles","Depts","BindJobs"],$Y=[...O2,"CopyUsers"];function Pf(t,e,r){let n=Le(t,e,e[0].toLowerCase()+e.slice(1));if(n==null||n==="")return[];let i=n;if(typeof n=="string")try{i=JSON.parse(n)}catch{i=null}return!Array.isArray(i)||i.some(o=>!S(H(o),"Id")||!S(H(o),"Name","JobName"))?(r.push(`\u8282\u70B9 ${Ur(t)||gt(t)}.${e} \u5FC5\u987B\u662F [{Id,Name}] \u6570\u7EC4\uFF1B\u4E0D\u80FD\u4F7F\u7528\u89D2\u8272\u540D\u6216 Id \u5B57\u7B26\u4E32`),[]):i.map(o=>({Id:S(o,"Id"),Name:S(o,"Name","JobName")}))}function OY(t,e,r){let n=Le(t,"BackNodes","backNodes");if(n==null||n==="")return"[]";let i=n;if(typeof n=="string")try{i=JSON.parse(n)}catch{i=null}if(!Array.isArray(i))return r.push(`\u8282\u70B9 ${Ur(t)||gt(t)}.BackNodes \u5FC5\u987B\u662F\u8282\u70B9 Id \u6216 {Id,NodeName} \u6570\u7EC4`),"[]";let o=i.map(a=>{let s=typeof a=="string"?a:S(H(a),"Id");e.has(s)||r.push(`\u8282\u70B9 ${Ur(t)||gt(t)}.BackNodes \u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684\u8282\u70B9 ${s}`);let c=e.get(s);return{Id:s,NodeName:c?Ur(c):S(H(a),"NodeName")}});return JSON.stringify(o)}function p2(t,e,r){let n=Le(t,e,e[0].toLowerCase()+e.slice(1));if(n==null||n==="")return;let i=/^(\d+(?:\.\d+)?)(?:px)?$/.exec(String(n).trim());if(!i||Number(i[1])>1e5){r.push(`\u8282\u70B9 ${Ur(t)||gt(t)}.${e} \u5FC5\u987B\u662F\u975E\u8D1F\u50CF\u7D20\u5750\u6807`);return}return Number(i[1])}function N2(t,e,r){let n=new Map(t.map(c=>[gt(c),c])),i=new Map,o=t.filter(Rf).map(gt);for(o.forEach(c=>i.set(c,0));o.length;){let c=o.shift();for(let l of e.filter(u=>S(u,"FromNodeId","fromNodeId")===c)){let u=S(l,"ToNodeId","toNodeId");!n.has(u)||i.has(u)||(i.set(u,(i.get(c)||0)+1),o.push(u))}}let a=new Map,s=new Set;return t.map((c,l)=>{let u=i.get(gt(c))??l,p=a.get(u)||0;a.set(u,p+1);let f=p2(c,"PositionLeft",r)??80+u*260,m=p2(c,"PositionTop",r)??120+p*150,h=`${f}:${m}`;s.has(h)&&r.push(`\u8282\u70B9 ${Ur(c)||gt(c)} \u4E0E\u5176\u5B83\u8282\u70B9\u5750\u6807\u91CD\u53E0`),s.add(h);let g={...c,PositionLeft:`${f}px`,PositionTop:`${m}px`};for(let y of $Y)g[y]=JSON.stringify(Pf(c,y,r));return g.BackNodes=OY(c,n,r),g})}function W0(t){let e=[],r=[],{flow:n,nodes:i,lines:o}=tw(t),a=S(n,"FlowName","flowName","Name","name"),s=S(n,"TableId","tableId"),c=S(n,"table","tableName","TableName","diyTableName","DiyTableName"),l=Object.prototype.hasOwnProperty.call(n,"IsEnable")&&(n.IsEnable===0||n.IsEnable==="0"),u=new Map,p=new Map,f=new Map;a||e.push("FlowDesign.FlowName \u4E0D\u80FD\u4E3A\u7A7A"),Pf(n,"Roles",e),i.length||e.push("Nodes \u81F3\u5C11\u9700\u8981\u5305\u542B\u5F00\u59CB\u3001\u5BA1\u6279/\u4E1A\u52A1\u3001\u7ED3\u675F\u8282\u70B9"),o.length||e.push("Lines \u81F3\u5C11\u9700\u8981\u8FDE\u63A5\u5F00\u59CB\u5230\u4E0B\u4E00\u8282\u70B9"),!s&&!c&&r.push("\u6D41\u7A0B\u672A\u7ED1\u5B9A\u4E1A\u52A1 diy_table\uFF1B\u82E5\u8981\u901A\u8FC7\u6A21\u5757\u5F15\u64CE\u6253\u5F00\u6D41\u7A0B\uFF0C\u5FC5\u987B\u7ED1\u5B9A\u540C\u4E00\u4E1A\u52A1\u8868"),i.forEach((b,v)=>{let _=gt(b),w=Ur(b);_||e.push(`Nodes[${v}].Id/NodeId \u4E0D\u80FD\u4E3A\u7A7A`),w||e.push(`Nodes[${v}].NodeName \u4E0D\u80FD\u4E3A\u7A7A`),RY.has(Af(b))||e.push(`Nodes[${v}].NodeType \u5FC5\u987B\u662F Start/Auto/Business/End/AutoEnd/Countersign/Approve`),_&&(u.has(_)&&e.push(`\u8282\u70B9 Id \u91CD\u590D\uFF1A${_}`),u.set(_,b))}),o.forEach((b,v)=>{let _=S(b,"Id","id","LineId","lineId")||`(index ${v})`,w=S(b,"FromNodeId","fromNodeId"),C=S(b,"ToNodeId","toNodeId");w||e.push(`Lines[${v}].FromNodeId \u4E0D\u80FD\u4E3A\u7A7A`),C||e.push(`Lines[${v}].ToNodeId \u4E0D\u80FD\u4E3A\u7A7A`),w&&!u.has(w)&&e.push(`\u8FDE\u7EBF ${_} \u7684 FromNodeId \u4E0D\u5B58\u5728\uFF1A${w}`),C&&!u.has(C)&&e.push(`\u8FDE\u7EBF ${_} \u7684 ToNodeId \u4E0D\u5B58\u5728\uFF1A${C}`),w===C&&w&&r.push(`\u8FDE\u7EBF ${_} \u6307\u5411\u81EA\u8EAB\uFF0C\u8BF7\u786E\u8BA4\u662F\u5426\u4E3A\u6709\u610F\u5FAA\u73AF`),w&&p.set(w,[...p.get(w)||[],b]),C&&f.set(C,[...f.get(C)||[],b])});let m=i.filter(Rf),h=i.filter(u2);m.length!==1&&e.push(`\u9700\u8981\u4E14\u4EC5\u9700\u8981 1 \u4E2A\u5F00\u59CB\u8282\u70B9\uFF0C\u5F53\u524D ${m.length} \u4E2A`),h.length<1&&e.push("\u81F3\u5C11\u9700\u8981 1 \u4E2A\u7ED3\u675F\u8282\u70B9");let g=N2(i,o,e);i.forEach(b=>{let v=gt(b),_=Ur(b)||v;if(!v)return;let w=p.get(v)||[],C=f.get(v)||[];if(!Rf(b)&&C.length===0&&r.push(`\u8282\u70B9 ${_} \u6CA1\u6709\u5165\u7EBF`),!u2(b)&&w.length===0&&r.push(`\u8282\u70B9 ${_} \u6CA1\u6709\u51FA\u7EBF`),PY.has(Af(b))){let E=O2.flatMap(A=>Pf(b,A,[])),T=C.some(A=>{let I=u.get(S(A,"FromNodeId","fromNodeId"))||{};return oe(I,"AllowSelectUsers","allowSelectUsers")===1||Le(I,"AllowSelectUsers","allowSelectUsers")===!0});!E.length&&!T&&!l&&e.push(`\u4EBA\u5DE5\u8282\u70B9 ${_} \u672A\u7ED1\u5B9A Users/Roles/Depts/BindJobs\uFF0C\u4E14\u4E0A\u6E38\u8282\u70B9\u6CA1\u6709\u624B\u52A8\u9009\u4EBA\u7B56\u7565\uFF1BSameDeptApprove \u4EC5\u7B5B\u9009\u5019\u9009\u4EBA\uFF0C\u4E0D\u80FD\u72EC\u7ACB\u6307\u5B9A\u5BA1\u6279\u4EBA`)}w.length>1&&(S(b,"LineValueV8","lineValueV8","V8Code","v8Code")||r.push(`\u8282\u70B9 ${_} \u6709 ${w.length} \u6761\u51FA\u7EBF\uFF0C\u5EFA\u8BAE\u914D\u7F6E LineValueV8\uFF0C\u5E76\u4F18\u5148\u7528 V8.NextNodeId \u6307\u5B9A\u4E0B\u4E00\u8282\u70B9`))});let y=new Set(m.map(gt)),x=[...y];for(;x.length;){let b=x.shift();for(let v of p.get(b)||[]){let _=S(v,"ToNodeId","toNodeId");!y.has(_)&&u.has(_)&&(y.add(_),x.push(_))}}for(let b of i)gt(b)&&!y.has(gt(b))&&e.push(`\u8282\u70B9 ${Ur(b)} \u4ECE\u5F00\u59CB\u8282\u70B9\u4E0D\u53EF\u8FBE`);return h.length&&!h.some(b=>y.has(gt(b)))&&e.push("\u7ED3\u675F\u8282\u70B9\u4ECE\u5F00\u59CB\u8282\u70B9\u4E0D\u53EF\u8FBE"),{ok:e.length===0,errors:e,warnings:r,summary:{flowName:a,tableId:s,table:c,nodeCount:i.length,lineCount:o.length,positions:g.map(b=>({id:gt(b),left:b.PositionLeft,top:b.PositionTop})),startNodes:m.map(b=>({id:gt(b),name:Ur(b)})),endNodes:h.map(b=>({id:gt(b),name:Ur(b)}))}}}function NY(t){let e=t.indexOf(a2);if(e<0)return null;let r=e+a2.length,n=t.indexOf(QX,r);if(n<0)return null;try{return H(JSON.parse(t.slice(r,n).trim()))}catch{return null}}function d2(t){return t==null||String(t).trim()===""}function f2(t,e){let r=S(t,"field","Field"),n=S(t,"operator","Operator")||"eq",i=Le(t,"value","Value"),o=r?e[r]:void 0,a=o==null?"":String(o),s=i==null?"":String(i);if(n==="empty")return d2(o);if(n==="notEmpty")return!d2(o);if(n==="contains")return a.includes(s);if(n==="notContains")return!a.includes(s);if(n==="startsWith")return a.startsWith(s);if(n==="endsWith")return s===""||a.endsWith(s);if(["gt","gte","lt","lte"].includes(n)){let c=Number(o),l=Number(i);return Number.isNaN(c)||Number.isNaN(l)?!1:n==="gt"?c>l:n==="gte"?c>=l:n==="lt"?c<l:c<=l}return n==="ne"?a!==s:a===s}function MY(t){let e=H(t.workflow),r=H(t.formData),n=S(t,"lineValueV8Code","LineValueV8","code");if(!n&&Object.keys(e).length>0){let{nodes:s}=tw(e),c=S(t,"nodeId","NodeId"),l=(c?s.find(u=>gt(u)===c):s.find(Rf)||s[0])||{};n=S(l,"LineValueV8","lineValueV8","V8Code","v8Code")}let i=NY(n),o=ie(i||{},"routes","Routes");if(!i||o.length===0)return{ok:!1,selectedRoute:null,warnings:["\u672A\u627E\u5230\u56FE\u5F62\u6761\u4EF6\u6807\u8BB0\uFF0CMCP \u4E0D\u6267\u884C\u4EFB\u610F\u624B\u5199 V8\uFF1B\u8BF7\u7528\u56FE\u5F62\u6761\u4EF6\u751F\u6210 LineValueV8 \u540E\u518D\u6D4B\u8BD5\u3002"]};let a=o.find(s=>!!Le(s,"isDefault","IsDefault"))||null;for(let s of o){if(s===a)continue;let c=ie(s,"rules","Rules").filter(u=>S(u,"field","Field"));if(c.length===0)continue;if(S(s,"match","Match")==="any"?c.some(u=>f2(u,r)):c.every(u=>f2(u,r)))return{ok:!0,selectedRoute:s,assignment:m2(s),source:"matched"}}return{ok:!!a,selectedRoute:a,assignment:a?m2(a):null,source:a?"default":"none"}}function m2(t){let e=S(t,"lineValue","LineValue"),r=S(t,"toNodeId","ToNodeId");return e?{LineValue:e}:{NextNodeId:r}}function h2(t,e){let{flow:r,nodes:n,lines:i}=tw(t),o={...r},a=[];if(o.Roles=JSON.stringify(Pf(r,"Roles",a)),a.length)throw new Error(a.join("\uFF1B"));let s=S(r,"table","tableName","TableName","diyTableName","DiyTableName");if(!S(o,"TableId","tableId")&&s){let m=e.get(s.toLowerCase());if(!m)throw new Error(`\u6D41\u7A0B\u4E1A\u52A1\u8868 ${s} \u5728\u5F53\u524D\u79DF\u6237\u4E0D\u5B58\u5728`);o.TableId=m}let c=new Map,l=n.map((m,h)=>{let g=gt(m)||`wf_node_${h+1}_${V0().slice(0,8)}`,y={...m,Id:g},x=Ur(y);return x&&c.set(g,x),y}),u=i.map((m,h)=>{let g=S(m,"FromNodeId","fromNodeId"),y=S(m,"ToNodeId","toNodeId"),x=S(m,"LineName","lineName")||`${c.get(g)||g||"\u5F53\u524D\u8282\u70B9"} \u5230 ${c.get(y)||y||"\u4E0B\u4E00\u8282\u70B9"}`;return{...m,Id:S(m,"Id","id","LineId","lineId")||`wf_line_${h+1}_${V0().slice(0,8)}`,LineName:x}}),p=[],f=N2(l,u,p);if(p.length)throw new Error(p.join("\uFF1B"));return{FlowDesign:o,Nodes:f,Lines:u}}async function g2(t,e){let r=[{table:"sys_user",field:"Users",owners:ie(e,"Nodes")},{table:"sys_user",field:"CopyUsers",owners:ie(e,"Nodes")},{table:"sys_role",field:"Roles",owners:[H(e.FlowDesign),...ie(e,"Nodes")]},{table:"sys_dept",field:"Depts",owners:ie(e,"Nodes")},{table:"diy_job",field:"BindJobs",owners:ie(e,"Nodes")}],n=[];for(let i of r){let o=[...new Set(i.owners.flatMap(a=>{try{return ii(JSON.parse(S(a,i.field)||"[]")).map(s=>S(s,"Id")).filter(Boolean)}catch{return n.push(`${i.field} \u4E0D\u662F\u6709\u6548 JSON`),[]}}))];for(let a=0;a<o.length;a+=100){let s=o.slice(a,a+100);try{let c=await t.getTableData(i.table,{_Where:[["Id","In",s]],_SelectFields:["Id"],_PageIndex:1,_PageSize:s.length+1});if(c.Code!==1)throw new Error(c.Msg||`Code=${c.Code}`);let l=new Set(I2(c.Data).map(u=>S(u,"Id")));for(let u of s)l.has(u)||n.push(`${i.field} \u5F15\u7528\u4E86\u5F53\u524D\u79DF\u6237\u4E0D\u5B58\u5728\u7684 ${i.table}.Id=${u}`)}catch(c){n.push(`${i.field} \u65E0\u6CD5\u6838\u5BF9\u5F53\u524D\u79DF\u6237 ${i.table}\uFF1A${c instanceof Error?c.message:String(c)}`)}}}return n}async function qr(t,e,r,n){try{await t.writeAuditLog(e,r,JSON.stringify(n).slice(0,6e3))}catch(i){console.error("[microi-mcp] audit log failed:",i instanceof Error?i.message:String(i))}}async function y2(t,e){let r=S(e,"apiEngineKey","ApiEngineKey"),n=S(e,"apiName","ApiName","name","Name")||r,i=S(e,"category","Category")||"AI\u751F\u6210",o=Le(e,"code","Code","ApiV8Code"),a=typeof o=="string",s=a?String(o):"",c=Ol(e),l=await t.getEngineCode(r);return l.Code===1?!a&&c!==void 0?t.updateEngineRuntimeLimit(r,c):a?t.saveEngineCode(r,s,{functionDescription:S(e,"functionDescription","FunctionDescription")||void 0,changeSummary:S(e,"changeSummary","ChangeSummary")||void 0,v8Limit:c}):{Code:1,Data:{ApiEngineKey:r,V8Limit:Number(l.Data?.V8Limit||0),Skipped:!0},Msg:"\u63A5\u53E3\u5F15\u64CE\u5DF2\u5B58\u5728\uFF0CManifest \u672A\u63D0\u4F9B code \u6216 V8Limit\uFF0C\u4FDD\u6301\u539F\u914D\u7F6E"}:t.createEngine({ApiEngineKey:r,ApiName:n,Category:i,Code:s,V8Limit:c===void 0?void 0:c?1:0,functionDescription:S(e,"functionDescription","FunctionDescription")||void 0,changeSummary:S(e,"changeSummary","ChangeSummary")||void 0})}function DY(t,e,r,n){let i=S(t,"table","tableName","diyTableName","DiyTableName"),o=ks(t);if(o.errors.length)throw new Error(o.errors.join(`
133
+ `),e.Code!==1)}function $l(t){if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function tY(t,e={}){let r=H(t),n=H(r.Workload??r.workload??r.BackgroundWorkload??r.backgroundWorkload),i=[],o=oe(n,"ExpectedSeconds","expectedSeconds")??0,a=oe(n,"ExpectedItems","expectedItems","EstimatedRows","estimatedRows")??0,s=oe(n,"FanOutOperations","fanOutOperations","FanOut","fanOut")??0,c=oe(n,"ExternalCalls","externalCalls")??0;o>=120&&i.push(`\u9884\u8BA1\u8017\u65F6 ${o}s >= 120s`),a>=500&&i.push(`\u9884\u8BA1\u5904\u7406 ${a} \u6761 >= 500 \u6761`),s>=1e3&&i.push(`\u9884\u8BA1\u6247\u51FA ${s} \u4E2A\u5B50\u64CD\u4F5C >= 1000`),c>=100&&i.push(`\u9884\u8BA1\u5916\u90E8\u8C03\u7528 ${c} \u6B21 >= 100 \u6B21`),Zr(n,"UnknownTotal","unknownTotal")===!0&&i.push("\u603B\u5DE5\u4F5C\u91CF\u672A\u77E5\u4E14\u53EF\u80FD\u957F\u65F6\u95F4\u8FD0\u884C");let l=S(r,"V8Code","v8Code"),u=[S(r,"Name","name"),S(r,"ApiEngineKey","apiEngineKey"),l].join(" "),p=/\bV8\.OpenAppDialog\s*\(/i.test(l)&&!/\bV8\.(?:ApiEngine\.RunBackground|Method\.QueueBackgroundTask)\s*\(/i.test(l);return e.inferActionSemantics!==!1&&!p&&/(批量.{0,4}(导入|生成|修复|处理)|安装|初始化|全量同步|数据迁移|数据库备份|批量任务)/i.test(u)&&i.push("\u52A8\u4F5C\u8BED\u4E49\u5C5E\u4E8E\u5178\u578B\u957F\u4EFB\u52A1"),{required:i.length>0,reasons:i}}function rY(t){let e=H(t),r=H(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=S(r,"ExecutionMode","executionMode").trim().toLowerCase(),i=Zr(r,"ClientChunked","clientChunked")===!0||n==="clientchunked"||n==="clientsequential",o=oe(r,"MaxItemsPerChunk","maxItemsPerChunk")??0,a=Zr(r,"Resumable","resumable")===!0;return{declared:i,valid:i&&o>0&&a,maxItemsPerChunk:o,resumable:a}}var kf="https://api.itdos.com",j0="iTdos";function nY(t){let e=String(t.storeId||"").trim(),r=String(t.storeVersionId||"").trim(),n=String(t.requestId||"").trim();if(!/^[A-Za-z0-9:._-]{1,100}$/u.test(e))throw new Error("storeId \u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u5192\u53F7\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\uFF0C\u957F\u5EA6 1-100\u3002");if(!/^[A-Za-z0-9:._-]{8,100}$/u.test(n))throw new Error("requestId \u5FC5\u987B\u662F\u8C03\u7528\u65B9\u4FDD\u5B58\u5E76\u5728\u91CD\u8BD5\u65F6\u590D\u7528\u7684\u7A33\u5B9A\u5E42\u7B49 Id\uFF0C\u957F\u5EA6 8-100\u3002");if(r&&!/^[A-Za-z0-9:._-]{1,100}$/u.test(r))throw new Error("storeVersionId \u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u5192\u53F7\u3001\u70B9\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26\uFF0C\u957F\u5EA6 1-100\u3002");let i=String(t.storeApiBase||kf).trim(),o;try{o=new URL(i)}catch{throw new Error("storeApiBase \u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP/HTTPS \u670D\u52A1\u6839\u5730\u5740\u3002")}if(o.protocol!=="https:"||o.username||o.password||o.pathname&&o.pathname!=="/"||o.search||o.hash||o.origin!==kf)throw new Error(`storeApiBase \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE ${kf}\uFF0C\u4E14\u4E0D\u80FD\u5305\u542B\u51ED\u636E\u3001\u8DEF\u5F84\u3001\u67E5\u8BE2\u3001\u7247\u6BB5\u6216\u81EA\u5B9A\u4E49\u7AEF\u53E3\u3002`);let a=kf,s=String(t.storeOsClient||j0).trim();if(s.toLowerCase()!==j0.toLowerCase())throw new Error(`storeOsClient \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE\u79DF\u6237 ${j0}\u3002`);return{ApiEngineKey:"import-microi-store-package",Title:`${t.operation==="update"?"\u66F4\u65B0":"\u5B89\u88C5"}\u5E94\u7528\uFF1A${String(t.appName||t.appId||e).trim()}`,Param:dn({StoreId:e,StoreVersionId:r||void 0,AppId:t.appId,AppName:t.appName,AppVersion:t.appVersion,StoreApiBase:a,StoreOsClient:s,InstallParentSysMenuId:t.installParentSysMenuId,ResumeInstall:t.resumeInstall!==!1,InstallAction:t.operation==="update"?"Update":"Install",InstallOperationId:n}),Options:{IdempotencyKey:`mcp:store:${t.operation}:${e}:${n}`,ConcurrencyKey:"import-microi-store-package",MaxAttempts:3,RetryOnFailure:!0}}}function iY(t,e){let r=[],n=[];if(e==null||e==="")return{ok:!0,value:void 0,errors:r,warnings:n};let i;try{i=typeof e=="string"?JSON.parse(e):e}catch(s){return{ok:!1,errors:[`${t} \u4E0D\u662F\u5408\u6CD5 JSON \u6570\u7EC4\uFF1A${s instanceof Error?s.message:String(s)}`],warnings:n}}if(!Array.isArray(i))return{ok:!1,errors:[`${t} \u5FC5\u987B\u662F JSON \u6570\u7EC4`],warnings:n};let o=new Set,a=i.map((s,c)=>{let l=H(s),u=S(l,"Name","name");u||r.push(`${t}[${c}].Name \u4E0D\u80FD\u4E3A\u7A7A`);let p=tY(l,{inferActionSemantics:t!=="PageTabs"}),f=rY(l),m=l.RunBackground??l.runBackground??l.BackgroundTask??l.backgroundTask??l.IsBackgroundTask??l.isBackgroundTask,h=S(l,"ApiEngineKey","apiEngineKey");p.required&&m!==!0&&(f.declared&&!f.valid?r.push(`${t}[${c}] \u58F0\u660E\u5BA2\u6237\u7AEF\u5206\u7247\u65F6\u5FC5\u987B\u8BBE\u7F6E Workload.MaxItemsPerChunk > 0 \u4E14 Workload.Resumable=true`):f.valid?n.push(`${t}[${c}] \u5DF2\u58F0\u660E\u5BA2\u6237\u7AEF\u53EF\u6062\u590D\u5206\u7247\uFF0C\u5355\u7247\u6700\u591A ${f.maxItemsPerChunk} \u6761\uFF1B\u4FDD\u7559\u524D\u7AEF\u5206\u7247\u6267\u884C\uFF1A${p.reasons.join("\uFF1B")}`):h?(m=!0,n.push(`${t}[${c}] \u5DF2\u8BC6\u522B\u4E3A\u957F\u4EFB\u52A1\u5E76\u81EA\u52A8\u542F\u7528 RunBackground\uFF1A${p.reasons.join("\uFF1B")}`)):r.push(`${t}[${c}] \u5DF2\u8BC6\u522B\u4E3A\u957F\u4EFB\u52A1\uFF0C\u4F46\u7F3A\u5C11 ApiEngineKey\uFF1A${p.reasons.join("\uFF1B")}`));let g=H(l.BackgroundTaskOptions??l.backgroundTaskOptions);m===!0&&(!S(g,"IdempotencyKey","idempotencyKey")&&!Ss(g,"IdempotencyKeyFields","idempotencyKeyFields").length&&n.push(`${t}[${c}] \u540E\u53F0\u4EFB\u52A1\u672A\u914D\u7F6E IdempotencyKey \u6216 IdempotencyKeyFields\uFF1B\u6D89\u53CA\u5199\u64CD\u4F5C\u65F6\u5FC5\u987B\u8865\u7A33\u5B9A\u4E1A\u52A1\u5E42\u7B49\u952E`),S(g,"BusinessTable","businessTable")&&(!S(g,"BusinessStatusField","businessStatusField")||!S(g,"BusinessTaskIdField","businessTaskIdField"))&&n.push(`${t}[${c}] \u5DF2\u5173\u8054\u4E1A\u52A1\u8868\uFF0C\u4F46\u7F3A\u5C11 BusinessStatusField/BusinessTaskIdField`));let y=S(l,"TargetSysMenuId","targetSysMenuId"),x=t==="PageTabs"&&!!y;!S(l,"V8Code","v8Code")&&!S(l,"Url","url")&&!(m&&h)&&!x&&r.push(`${t}[${c}] \u5FC5\u987B\u914D\u7F6E V8Code\u3001Url\u3001\u5173\u8054\u6A21\u5757 TargetSysMenuId\uFF0C\u6216\u540E\u53F0\u4EFB\u52A1 ApiEngineKey`);let b=S(l,"Id","id")||V0();S(l,"Id","id")||n.push(`${t}[${c}] \u672A\u4F20 Id\uFF0C\u5DF2\u81EA\u52A8\u751F\u6210 ${b}`),o.has(b)&&r.push(`${t} \u4E2D\u5B58\u5728\u91CD\u590D Id\uFF1A${b}`),o.add(b);let v=S(l,"V8CodeShow","v8CodeShow");return v&&!v.includes("V8.Result")&&n.push(`${t}[${c}].V8CodeShow \u5EFA\u8BAE\u663E\u5F0F\u8D4B\u503C V8.Result=true/false`),dn({...l,Id:b,Sort:oe(l,"Sort","sort")??c*10,Name:u,Icon:S(l,"Icon","icon")||void 0,BtnStyle:S(l,"BtnStyle","btnStyle")||void 0,IsVisible:l.IsVisible??l.isVisible??!0,ShowRow:t==="MoreBtns"?l.ShowRow??l.showRow??!0:l.ShowRow??l.showRow,V8CodeShow:v||void 0,V8Code:S(l,"V8Code","v8Code")||void 0,Url:S(l,"Url","url")||void 0,RunBackground:m===void 0?void 0:!!m,BackgroundTask:l.BackgroundTask??l.backgroundTask??void 0,IsBackgroundTask:l.IsBackgroundTask??l.isBackgroundTask??void 0,ApiEngineKey:h||void 0,Workload:Object.keys(H(l.Workload??l.workload)).length?H(l.Workload??l.workload):void 0,BackgroundTaskOptions:Object.keys(g).length?g:void 0,TargetSysMenuId:y||void 0})});return{ok:r.length===0,value:JSON.stringify(a),errors:r,warnings:n}}function A2(t,e=0){if(!t||typeof t!="object"||Array.isArray(t)||e>3)return!1;let r=t,n=String(r.Label??r.label??"").trim();if(!n||n.length>80)return!1;let i=r.Fields??r.fields,o=r.Children??r.children;return Array.isArray(i)&&i.length>0&&o===void 0?i.length<=64&&i.every(a=>typeof a=="string"&&a.trim().length>0&&a.length<=128):i===void 0&&Array.isArray(o)&&o.length>0&&o.length<=32&&o.every(a=>A2(a,e+1))}function ks(t){let e={...t},r=[],n=[];(t.DiyConfig!==void 0||t.diyConfig!==void 0)&&(r.push("DiyConfig \u5DF2\u5E9F\u5F03\uFF1B\u8BF7\u65B0\u589E\u4E13\u7528\u7269\u7406\u5B57\u6BB5\uFF0C\u5E76\u901A\u8FC7 diy_field \u5143\u6570\u636E\u66B4\u9732\u914D\u7F6E\u63A7\u4EF6\u3002\u8DE8\u7AEF\u89C6\u56FE\u8BF7\u4F7F\u7528 sys_menu.ViewSchema\u3002"),delete e.DiyConfig,delete e.diyConfig);let i={MoreBtns:["MoreBtns","moreBtns"],FormBtns:["FormBtns","formBtns"],BatchSelectMoreBtns:["BatchSelectMoreBtns","batchSelectMoreBtns"],PageTabs:["PageTabs","pageTabs"],ExportMoreBtns:["ExportMoreBtns","exportMoreBtns"],PageBtns:["PageBtns","pageBtns"]};for(let[u,p]of Object.entries(i)){let f=p.find(h=>t[h]!==void 0);if(!f)continue;let m=iY(u,t[f]);r.push(...m.errors),n.push(...m.warnings),m.ok&&m.value!==void 0&&(e[u]=m.value)}let o=[["TreeDragSortEnabled","treeDragSortEnabled"],["MenuBadgeEnabled","menuBadgeEnabled"],["HideTableBanner","hideTableBanner"],["HideFormBanner","hideFormBanner"],["EnableViewSchema","enableViewSchema"],["ViewConfigVersion","viewConfigVersion"]];for(let[u,p]of o){if(t[u]===void 0&&t[p]===void 0)continue;let f=t[u]??t[p],m=u!=="ViewConfigVersion"&&typeof f=="boolean"?f?1:0:oe(t,u,p);m!==void 0&&(e[u]=u.endsWith("Enabled")||u.endsWith("Banner")?m===1?1:0:m),delete e[p]}let a=["TableHeaders","tableHeaders"].find(u=>t[u]!==void 0);if(a){try{let u=typeof t[a]=="string"?JSON.parse(t[a]):t[a];!Array.isArray(u)||u.length>32||u.some(p=>!A2(p))?r.push("TableHeaders \u5FC5\u987B\u4E3A\u6700\u591A 32 \u4E2A\u5206\u7EC4\u7684\u6570\u7EC4\uFF0C\u6BCF\u7EC4\u5305\u542B Label \u548C Fields \u6216 Children \u6570\u7EC4\u3002"):e.TableHeaders=JSON.stringify(u)}catch{r.push("TableHeaders \u5FC5\u987B\u662F\u5408\u6CD5 JSON \u6570\u7EC4\u3002")}delete e.tableHeaders}let s=[["TreeDragSortField","treeDragSortField"],["MenuBadgeApiEngineKey","menuBadgeApiEngineKey"],["ViewSchemaVersion","viewSchemaVersion"]];for(let[u,p]of s)t[u]===void 0&&t[p]===void 0||(e[u]=S(t,u,p),delete e[p]);let c=["FieldPermissions","fieldPermissions"].find(u=>t[u]!==void 0);if(c){try{let u=typeof t[c]=="string"?JSON.parse(t[c]):t[c];!u||typeof u!="object"||Array.isArray(u)||u.Enabled&&(u.Version!==1||!Array.isArray(u.Rules)||u.Rules.length>200)?r.push("FieldPermissions \u5FC5\u987B\u4E3A\u5B57\u6BB5\u6743\u9650 v1 \u914D\u7F6E\u5BF9\u8C61\u3002"):e.FieldPermissions=JSON.stringify(u)}catch{r.push("FieldPermissions \u5FC5\u987B\u662F\u5408\u6CD5 JSON \u5BF9\u8C61\u3002")}delete e.fieldPermissions}let l=["ViewSchema","viewSchema"].find(u=>t[u]!==void 0);if(l){let u=Of(t[l]);r.push(...u.errors),n.push(...u.warnings),delete e.viewSchema,u.value!==void 0&&(e.ViewSchema=u.value)}return{data:e,errors:r,warnings:n}}function Zr(t,...e){for(let r of e){let n=t[r];if(typeof n=="boolean")return n;if(typeof n=="number")return n!==0;if(typeof n=="string"&&n.trim()){let i=n.trim().toLowerCase();if(["true","1","yes"].includes(i))return!0;if(["false","0","no"].includes(i))return!1}}}function oY(t,e,r,n){let i=Le(t,"v8Limit","V8Limit"),o=Le(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(o==null||o===""))return;let a=i!=null&&i!=="",s=a?Zr(t,"v8Limit","V8Limit"):Ol(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(a&&o!==void 0){let c=Zr(t,"v8Unlimited","V8Unlimited");c!==void 0&&s!==!c&&r.push(`${e}.v8Limit \u4E0E\u517C\u5BB9\u5B57\u6BB5 v8Unlimited \u7684\u8BED\u4E49\u51B2\u7A81`)}else o!==void 0&&n.push(`${e}.v8Unlimited \u5DF2\u5F03\u7528\uFF1B\u8868\u5355\u5F15\u64CE\u8BF7\u6539\u7528\u6B63\u5411\u5B57\u6BB5 v8Limit\uFF08false=\u4E0D\u9650\uFF0Ctrue=\u542F\u7528\u9650\u5236\uFF09`);return s}function aY(t,e){return{ok:e.Code===1&&H(e.Data).Passed!==!1,results:t,validation:{Code:e.Code,Msg:e.Msg??null,Data:e.Data??null}}}function Ol(t){let e=Zr(t,"v8Limit","V8Limit");if(e!==void 0)return e;let r=Zr(t,"v8Unlimited","V8Unlimited");return r===void 0?void 0:!r}function sY(t,e,r,n){let i=Le(t,"v8Limit","V8Limit"),o=Le(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(o==null||o===""))return;let a=i!=null&&i!=="",s=a?Zr(t,"v8Limit","V8Limit"):Ol(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(a&&o!==void 0){let c=Zr(t,"v8Unlimited","V8Unlimited");c!==void 0&&s!==!c&&r.push(`${e}.v8Limit \u4E0E\u517C\u5BB9\u5B57\u6BB5 v8Unlimited \u7684\u8BED\u4E49\u51B2\u7A81`)}else o!==void 0&&n.push(`${e}.v8Unlimited \u5DF2\u5F03\u7528\uFF1B\u63A5\u53E3\u5F15\u64CE\u8BF7\u6539\u7528\u6B63\u5411\u5B57\u6BB5 v8Limit\uFF08false=\u4E0D\u9650\uFF0Ctrue=\u542F\u7528\u9650\u5236\uFF09`);return s}var cY=["Detail","Edit","List","Card"],lY=["PC","Mobile","All"],uY=["ApiEngine","OpenDetail","OpenList","OpenForm","Navigate","Dial","Scan","Map","Refresh","Back","Copy"],pY=new Set(["v8code","v8codeshow","script","javascript","eval","onclick","function"]);function U0(t,e){let r=String(t??"").trim().toLowerCase();return e.find(n=>n.toLowerCase()===r)||""}function ni(t,...e){let r=new Set(e.map(i=>i.toLowerCase()));return Object.entries(t).find(([i])=>r.has(i.toLowerCase()))?.[1]}function H0(t,e="ViewSchema"){if(Array.isArray(t)){for(let r=0;r<t.length;r+=1){let n=H0(t[r],`${e}[${r}]`);if(n)return n}return""}if(!t||typeof t!="object")return"";for(let[r,n]of Object.entries(t)){if(pY.has(r.toLowerCase()))return`${e}.${r}`;let i=H0(n,`${e}.${r}`);if(i)return i}return""}function J0(t,e,r=0){if(t==null)return[];if(r>4)return[`${e} \u7684 SuccessActions \u5D4C\u5957\u4E0D\u80FD\u8D85\u8FC7 4 \u5C42`];if(!Array.isArray(t))return[`${e} \u5FC5\u987B\u662F JSON \u6570\u7EC4`];if(t.length>50)return[`${e} \u6700\u591A\u5141\u8BB8 50 \u4E2A\u52A8\u4F5C`];let n=[];return t.forEach((i,o)=>{let a=H(i);if(!Object.keys(a).length){n.push(`${e}[${o}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}let s=U0(ni(a,"ActionType","Type"),uY);if(!s){n.push(`${e}[${o}].ActionType \u4E0D\u53D7\u652F\u6301`);return}s==="ApiEngine"&&!S(a,"ApiEngineKey","apiEngineKey")&&n.push(`${e}[${o}] \u4F7F\u7528 ApiEngine \u65F6\u5FC5\u987B\u914D\u7F6E ApiEngineKey`);let c=ni(a,"SuccessActions");n.push(...J0(c,`${e}[${o}].SuccessActions`,r+1))}),n}function Of(t){let e=[],r=[];if(t==null||t==="")return{ok:!0,value:void 0,errors:e,warnings:r};let n=t;try{typeof n=="string"&&(n=JSON.parse(n)),typeof n=="string"&&(n=JSON.parse(n))}catch(c){return{ok:!1,errors:[`ViewSchema \u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${c instanceof Error?c.message:String(c)}`],warnings:r}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1,errors:["ViewSchema \u5FC5\u987B\u662F JSON \u5BF9\u8C61"],warnings:r};let i=H0(n);i&&e.push(`ViewSchema \u4E0D\u5141\u8BB8\u5305\u542B\u53EF\u6267\u884C\u524D\u7AEF\u811A\u672C\u5B57\u6BB5\uFF1A${i}`);let a=ni(n,"Views");a!==void 0&&!Array.isArray(a)?e.push("ViewSchema.Views \u5FC5\u987B\u662F JSON \u6570\u7EC4"):Array.isArray(a)?(a.length>100&&e.push("ViewSchema.Views \u6700\u591A\u5141\u8BB8 100 \u4E2A\u89C6\u56FE"),a.forEach((c,l)=>{let u=H(c);if(!Object.keys(u).length){e.push(`ViewSchema.Views[${l}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}U0(ni(u,"Scene"),cY)||e.push(`ViewSchema.Views[${l}].Scene \u4E0D\u53D7\u652F\u6301`);let p=ni(u,"Device");p!==void 0&&!U0(p,lY)&&e.push(`ViewSchema.Views[${l}].Device \u4E0D\u53D7\u652F\u6301`);let f=ni(u,"Layout","LayoutJson");if(typeof f=="string")try{f=JSON.parse(f)}catch{e.push(`ViewSchema.Views[${l}].Layout \u4E0D\u662F\u5408\u6CD5 JSON`);return}if(f==null)return;let m=H(f);if(!Object.keys(m).length&&(typeof f!="object"||Array.isArray(f))){e.push(`ViewSchema.Views[${l}].Layout \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}e.push(...J0(ni(m,"Actions","ActionSchema"),`ViewSchema.Views[${l}].Layout.Actions`));let h=ni(m,"Blocks","Sections");h!==void 0&&!Array.isArray(h)?e.push(`ViewSchema.Views[${l}].Layout.Blocks \u5FC5\u987B\u662F JSON \u6570\u7EC4`):Array.isArray(h)&&(h.length>100&&e.push(`ViewSchema.Views[${l}].Layout.Blocks \u6700\u591A\u5141\u8BB8 100 \u4E2A\u533A\u5757`),h.forEach((g,y)=>{let x=H(g);e.push(...J0(ni(x,"Actions"),`ViewSchema.Views[${l}].Layout.Blocks[${y}].Actions`))}))})):r.push("ViewSchema.Views \u4E3A\u7A7A\uFF0C\u5BA2\u6237\u7AEF\u5C06\u4F7F\u7528\u73B0\u6709\u6A21\u5757\u548C\u8868\u5355\u914D\u7F6E\u3002");let s=JSON.stringify(n);return Buffer.byteLength(s,"utf8")>512*1024&&e.push("ViewSchema \u4E0D\u80FD\u8D85\u8FC7 512KB"),{ok:e.length===0,value:s,errors:e,warnings:r}}function R2(t,e){let r=[],n=t.toLowerCase();if(n==="fileupload")return{config:o2(e),warnings:r};if(n==="keyvalue"){let i=S(e,"data","options"),o=i?i.split(/[,,;;\n]/).map(a=>a.trim()).filter(Boolean).map(a=>{let[s,c]=a.split("|");return{Key:(s||"").trim(),Value:(c||s||"").trim()}}):ii(e.items).map(a=>({Key:S(a,"Key","key"),Value:S(a,"Value","label","name")}));return{data:JSON.stringify(o),config:{DataSource:"KeyValue",SelectLabel:"Value",SelectSaveField:"Key",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="data"){let i=S(e,"data","options"),o=i?i.split(/[,,;;\n]/).map(a=>a.trim()).filter(Boolean):Array.isArray(e.items)?e.items:[];return{data:JSON.stringify(o),config:{DataSource:"Data",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="sql"){let i=S(e,"sql","Sql");return i||r.push("SQL \u6570\u636E\u6E90\u7F3A\u5C11 sql"),{config:{DataSource:"Sql",Sql:i,SelectLabel:S(e,"selectLabel","SelectLabel")||"Name",SelectSaveField:S(e,"selectSaveField","SelectSaveField")||"Id",DataSourceSqlRemote:e.dataSourceSqlRemote??e.DataSourceSqlRemote??!0,EnableSearch:e.enableSearch??e.EnableSearch??!0},warnings:r}}if(n==="apiengine"){let i=S(e,"apiEngineKey","DataSourceApiEngineKey");return i||r.push("\u63A5\u53E3\u5F15\u64CE\u6570\u636E\u6E90\u7F3A\u5C11 apiEngineKey"),{config:{DataSource:"ApiEngine",DataSourceApiEngineKey:i,SelectLabel:S(e,"selectLabel")||"name",SelectSaveField:S(e,"selectSaveField")||"id"},warnings:r}}if(n==="datasource"){let i=S(e,"dataSourceId","DataSourceId");return i||r.push("\u6570\u636E\u6E90\u5F15\u64CE\u914D\u7F6E\u7F3A\u5C11 dataSourceId"),{config:{DataSource:"DataSource",DataSourceId:i,SelectLabel:S(e,"selectLabel")||"Name",SelectSaveField:S(e,"selectSaveField")||"Id"},warnings:r}}if(n==="autonumber")return{config:{AutoNumberFixed:S(e,"prefix","AutoNumberFixed"),AutoNumberLength:oe(e,"length","AutoNumberLength")??4},warnings:r};if(n==="datetime")return{config:{DateTimeType:S(e,"dateTimeType","DateTimeType")||"datetime"},warnings:r};if(n==="joinform"){let i=S(e,"tableId"),o=S(e,"tableName"),a=S(e,"joinFieldName");return!i&&!o&&r.push("JoinForm \u7F3A\u5C11 tableId/tableName\uFF0C\u7981\u6B62\u4FDD\u5B58\u672A\u89E3\u6790\u76EE\u6807\u8868\u7684\u914D\u7F6E"),a||r.push("JoinForm \u7F3A\u5C11 joinFieldName\uFF1B\u8BE5\u5B57\u6BB5\u5FC5\u987B\u662F\u5F53\u524D\u4E3B\u8868\u4E2D\u4FDD\u5B58\u76EE\u6807\u8BB0\u5F55 Id \u7684\u771F\u5B9E\u5B57\u6BB5\u540D"),{config:{JoinForm:dn({TableId:i,TableName:o,JoinFieldName:a})},warnings:r}}return r.push(`\u672A\u77E5 sourceType: ${t}\uFF0C\u5DF2\u8FD4\u56DE\u7A7A\u914D\u7F6E`),{config:{},warnings:r}}function B0(t,e){let r=Kr(t);return dn({Id:t.id,AsName:e?.asName||"",Name:t.name,Label:t.label||t.name,TableId:t.tableId,TableName:t.tableName,TableDescription:t.tableDescription||t.tableName,DisplayType:e?.displayType||(If.has(r)||Jr(t)||r==="numbertext"?"In":"Out"),DisplaySelect:e?.displaySelect??["opentable","joinform","department","selecttree"].includes(r),Equal:e?.equal??(If.has(r)||r==="numbertext"?!0:void 0),IsVisible:!0})}function _s(t,e,r,n,i){return n.map(o=>{let a=s2(t,e,o.ref)||s2(t,r,o.ref)||(Pl(o.ref)?C2(e,r,o.ref):void 0);if(!a)throw new Error(`${i}: unknown field "${o.ref}" on table "${r||e}"`);return{meta:a,ref:o}})}function dt(t,...e){for(let r of e){let n=Le(t,r);if(!(n==null||n===""))return typeof n=="string"?n:JSON.stringify(n)}return""}var dY=new Set(["id","osclient","isdeleted","createuserid","updateuserid","deleteuserid","tenantid","storeid","userid","userids","roleid","roleids","parentid","parentids","class","code","enname","endescription"]),Q0=new Set(["button","divider","collapsegroup","tabs","alert","statictext","html","devcomponent"]),fY=new Set(["textarea","richtext","codeeditor","jsontable","imgupload","fileupload","tablechild","map","maparea","jointable","opentable","treecheckbox","transfer"]),mY=new Set(["text","textarea","select","multipleselect","radio","checkbox","datetime","date","numbertext","autonumber","switch","department","address","cascader","selecttree","opentable","joinform","autocomplete","taginput"]),If=new Set(["select","multipleselect","radio","checkbox","switch","department","selecttree","opentable","joinform","cascader"]);function br(t){return(t||"").trim().toLowerCase()}function _t(t){return`${t.name||""} ${t.label||""} ${t.component||""} ${t.type||""}`.toLowerCase()}function be(t,e){return e.some(r=>t.includes(r.toLowerCase()))}function Kr(t){return br(t.component||"Text")}function hY(t){return Q0.has(Kr(t))}function gY(t){return fY.has(Kr(t))}function yY(t){let e=t.name||"",r=br(e).replace(/[_\-\s]+/g,"");return!!(dY.has(r)||/^(.*id|.*ids|.*idlist|.*guid)$/.test(r)&&!/idcard|identity|cardid/.test(r)||/Id$|ID$|Ids$|IDs$|Guid$/u.test(e)&&!/IdCard|IDCard|Identity|CardId/u.test(e))}function Nl(t){return Pl(t.name)&&!["CreateTime","UpdateTime","UserName"].some(e=>e.toLowerCase()===t.name.toLowerCase())||yY(t)||hY(t)||gY(t)?!0:Kr(t).includes("hidden")}function Vi(t){let e=new Set;return t.filter(r=>{let n=r.id||r.name;return!n||e.has(n)?!1:(e.add(n),!0)})}function Hr(t,e){return t.map((r,n)=>({field:r,index:n,score:e(r)})).sort((r,n)=>n.score-r.score||r.index-n.index).map(r=>r.field)}function Nf(t){let e=br(t.type);return Kr(t)==="numbertext"||e.startsWith("decimal")||e==="int"||e==="bigint"}function Jr(t){let e=_t(t);return Kr(t)==="datetime"||be(e,["time","date","\u65E5\u671F","\u65F6\u95F4"])}function bY(t){let e=Kr(t),r=If.has(e)||e==="numbertext"||e==="rate"||e==="progress";return{ref:t.name,displayType:r||Jr(t)?"In":"Out",displaySelect:["opentable","joinform","department","selecttree"].includes(e),equal:r?!0:void 0}}function c2(t){let e=_t(t),r=0;return be(e,["name","title","no","code","account","phone","mobile","email","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7","\u8D26\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])&&(r+=50),be(e,["status","state","type","category","level","class","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])&&(r+=45),be(e,["customer","member","user","owner","\u8D1F\u8D23\u4EBA","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8054\u7CFB\u4EBA"])&&(r+=35),Jr(t)&&(r+=25),Nf(t)&&!be(e,["phone","mobile","tel","\u7535\u8BDD","\u624B\u673A"])&&(r+=15),Kr(t)==="textarea"&&(r-=25),r}function Z0(t){let e=_t(t),r=0;return be(e,["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])&&(r+=70),be(e,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])&&(r+=45),be(e,["customer","member","user","owner","phone","mobile","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u7535\u8BDD","\u624B\u673A"])&&(r+=35),be(e,["amount","money","price","total","count","qty","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D"])&&(r+=30),Jr(t)&&(r+=15),Kr(t)==="autonumber"&&(r+=55),r}function vY(t){return Vi(t.filter(Nl))}function Ml(t){let e=t.filter(n=>!Nl(n)),r=e.length?e:t;return Vi(Hr(r,Z0)).slice(0,Math.min(12,r.length))}function xY(t){let e=t.filter(n=>!Nl(n)&&mY.has(Kr(n))),r=Hr(e,c2).filter(n=>c2(n)>0);return Vi(r.length?r:e).slice(0,Math.min(8,e.length))}function wY(t){let e=t.filter(r=>!Nl(r)&&(Jr(r)||Nf(r)||br(r.name)==="sort"));return Vi(Hr(e,r=>{let n=_t(r);return be(n,["update","\u4FEE\u6539"])?80:be(n,["create","\u521B\u5EFA"])?75:br(r.name)==="sort"?70:be(n,["amount","money","price","total","count","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?60:20})).slice(0,Math.min(8,e.length))}function P2(t){let e=["phone","mobile","tel","status","state","sort","rate","level","\u7535\u8BDD","\u624B\u673A","\u72B6\u6001","\u6392\u5E8F","\u7B49\u7EA7"],r=t.filter(n=>{let i=_t(n);return!Nl(n)&&Nf(n)&&!be(i,e)&&be(i,["amount","money","price","total","count","qty","score","point","balance","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D","\u9762\u79EF","\u91CD\u91CF"])});return Vi(Hr(r,n=>be(_t(n),["amount","money","price","total","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D"])?80:40)).slice(0,6)}function _Y(t){let e=Ml(t),r=Hr(e,o=>be(_t(o),["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])?100:0)[0],n=Hr(e.filter(o=>o!==r),o=>be(_t(o),["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?80:0),i=e.filter(o=>o!==r&&!n.slice(0,1).includes(o));return Vi([r,...n.slice(0,1),...i].filter(Boolean)).slice(0,4)}function SY(t){return Hr(Ml(t),e=>be(_t(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])?100:0).filter(e=>be(_t(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])).slice(0,2)}function EY(t){return Hr(Ml(t),e=>{let r=_t(e);return be(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?90:Jr(e)?60:0}).filter(e=>{let r=_t(e);return Jr(e)||be(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])}).slice(0,3)}function $2(t,e=0){let r=H(t),n=S(r,"name","Name");return n?{id:S(r,"id","Id")||n,name:n,label:S(r,"label","Label")||n,tableId:S(r,"tableId","TableId"),tableName:S(r,"tableName","TableName"),tableDescription:S(r,"tableDescription","TableDescription"),component:S(r,"component","Component")||"Text",type:S(r,"type","Type")||"varchar(500)"}:null}function Mf(t){let e=$2(t);if(!e)return 150;let r=_t(e),n=Kr(e);return["richtext","textarea","address","map","maparea","fileupload","imgupload"].includes(n)||be(r,["address","remark","description","content","\u5730\u5740","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247"])?240:be(r,["name","title","subject","customer","company","\u540D\u79F0","\u6807\u9898","\u4E3B\u9898","\u5BA2\u6237","\u4F01\u4E1A"])?200:Jr(e)?170:Nf(e)?140:n==="autonumber"||be(r,["phone","mobile","email","code","number","\u7F16\u53F7","\u5355\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])?160:If.has(n)||be(r,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?130:150}function ri(t,e={}){return{Name:t.name,Label:t.label||t.name,...e}}function ea(t,e,r){let n=[];for(let i of t)if(!(!i?.name||r.has(br(i.name)))&&(r.add(br(i.name)),n.push(i),n.length>=e))break;return n}function ew(t,e,r=""){let n=e.map($2).filter(Boolean),i=Ml(n),o=String(t||r||n[0]?.tableDescription||n[0]?.tableName||"\u4E1A\u52A1\u6A21\u5757").trim(),a=String(r||n[0]?.tableDescription||"").trim(),s=a&&a!==o?a:`${o}\u7684\u4E1A\u52A1\u6570\u636E\u3001\u8FDB\u5EA6\u4E0E\u5173\u952E\u6307\u6807`,c=Hr(i,R=>{let F=_t(R);return be(F,["title","subject","\u6807\u9898","\u4E3B\u9898"])?150:be(F,["name","\u540D\u79F0"])?130:Kr(R)==="autonumber"||be(F,["no","code","number","\u7F16\u53F7","\u5355\u53F7","\u7F16\u7801"])?110:Z0(R)})[0]||i[0],l=Hr(i.filter(R=>R!==c),R=>be(_t(R),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])?100:0).filter(R=>be(_t(R),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])),u=P2(n).filter(R=>R!==c),p=Hr(n.filter(Jr),R=>be(_t(R),["create","\u521B\u5EFA"])?100:50),f=Hr(i.filter(R=>R!==c&&!l.includes(R)&&!u.includes(R)),R=>{let F=_t(R);return be(F,["customer","member","user","owner","contact","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u8054\u7CFB\u4EBA"])?90:Jr(R)?70:Z0(R)}).slice(0,1),m=Vi([...l.slice(0,1),...u.slice(0,1)]),h=Vi([c,...f,...m].filter(Boolean)).map(R=>R.name),g=c?Math.min(520,Math.max(340,Mf(c)+f.length*28+m.length*70)):0,y=[{Icon:"fas fa-chart-column",Tone:"primary"},{Icon:"fas fa-calculator",Tone:"success"}],x=u.slice(0,2).map((R,F)=>({Key:`Aggregate:${R.name}`,Label:`${R.label||R.name}\u5408\u8BA1`,Source:"Field",Field:R.name,...y[F]}));x.push({Key:"DataCount",Label:"\u7B5B\u9009\u7ED3\u679C",Source:"DataCount",Icon:"fas fa-layer-group",Tone:"info"}),x.length<3&&x.push({Key:"PageCount",Label:"\u672C\u9875\u5C55\u793A",Source:"PageCount",Icon:"fas fa-list-check",Tone:"warning"});let b=new Set(c?[br(c.name)]:[]),v=ea(f,1,b),_=ea(l,1,b),w=ea(l,1,b),C=ea(u,1,b),E=ea(p,2,b),T=ea(i,2,b),A=ea([...u,...p],2,b),I={Title:o,Description:s,Metrics:x};return{Views:[{Key:"auto-list-pc",Scene:"List",Device:"PC",Priority:100,Layout:{Hero:I,List:{Density:"Compact",Columns:c?[{Key:`composite:${c.name}`,Field:c.name,Lines:f.map(R=>ri(R,{Icon:Jr(R)?"fas fa-clock":"fas fa-circle-info",Tone:"info"})),TrailingFields:m.map(R=>ri(R,{Icon:l.includes(R)?"fas fa-circle-check":"fas fa-coins",Tone:l.includes(R)?"success":"warning",DisplayStyle:l.includes(R)?"Tag":"Text"})),RequiredFields:h,Align:"Left",MinWidth:g}]:[]}}},{Key:"auto-card-mobile",Scene:"Card",Device:"Mobile",Priority:100,Layout:{Hero:{...I,Metrics:x.map(R=>({...R}))},Card:{Preset:"Business",AvatarTextField:c?.name||"",TitleField:c?.name||"",SubtitleFields:v.map(R=>ri(R,{Icon:"fas fa-circle-info",Tone:"info"})),StatusFields:_.map(R=>ri(R,{DisplayStyle:"Tag",Icon:"fas fa-circle-check",Tone:"success"})),TopFields:w.map(R=>ri(R,{DisplayStyle:"Tag",Icon:"fas fa-tag",Tone:"primary"})),RightFields:C.map(R=>ri(R,{Icon:"fas fa-coins",Tone:"danger",FontWeight:"700"})),Fields:T.map(R=>ri(R)),MetaFields:E.map(R=>ri(R,{Icon:"fas fa-clock",Tone:"info"})),BottomFields:A.map(R=>ri(R,{Icon:Jr(R)?"fas fa-calendar":"fas fa-chart-simple",Tone:"warning"})),HideIndex:!0,ShowCreateTime:E.length===0,ShowUpdateTime:!1}}}]}}function kY(t,e,r){let n=t.length?t:[C2(e,r,"CreateTime")],i=n.find(o=>br(o.name)==="createtime")||n.find(o=>br(o.name)==="updatetime")||n.find(o=>br(o.name)==="sort");if(i)return JSON.stringify([{Id:i.id,Name:i.name,Type:br(i.name)==="sort"?"ASC":"DESC",Sort:0}])}function TY(t,e,r,n){let i=Le(t,"DefaultOrderBy");if(i!=null&&i!=="")return typeof i=="string"?i:JSON.stringify(i);let o=Le(t,"defaultOrderBy");if(o!=null&&o!==""){let s=Array.isArray(o)||typeof o=="string"&&o.trim().startsWith("[")?Vr({value:o},"value"):[{ref:String(o).trim(),type:"DESC"}];return JSON.stringify(_s(e,r,n,s,"module.defaultOrderBy").map(({meta:c,ref:l},u)=>({Id:c.id,Name:c.name,Type:l.type||"DESC",Sort:u})))}let a=Vr(t,"orderBy","OrderBy","defaultSort","DefaultSort","sortBy","SortBy");if(a.length)return JSON.stringify(_s(e,r,n,a,"module.defaultOrderBy").map(({meta:s,ref:c},l)=>({Id:s.id,Name:s.name,Type:c.type||"DESC",Sort:l})))}function CY(t,e,r,n){if(!r&&!n)return{};let i=Es(e,r).length?Es(e,r):Es(e,n),o={},a=Vr(t,"searchFields","SearchFields","searchFieldNames","SearchFieldNames"),s=a.length?_s(e,r,n,a,"module.searchFields"):xY(i).map(m=>({meta:m,ref:bY(m)}));!dt(t,"searchFieldIds","SearchFieldIds")&&s.length&&(o.SearchFieldIds=JSON.stringify(s.map(({meta:m,ref:h})=>B0(m,h))));let c=Vr(t,"listFields","ListFields","tableFields","TableFields","columns","Columns"),l=c.length?_s(e,r,n,c,"module.listFields"):Ml(i).map(m=>({meta:m,ref:{ref:m.name}}));!dt(t,"tableDiyFieldIds","TableDiyFieldIds")&&l.length&&(o.TableDiyFieldIds=JSON.stringify(l.map(({meta:m})=>m.id))),!dt(t,"selectFields","SelectFields")&&l.length&&(o.SelectFields=JSON.stringify(l.map(({meta:m,ref:h})=>B0(m,h))));let u=[{canonical:"SortFieldIds",explicitKeys:["sortFieldIds","SortFieldIds"],refKeys:["sortFields","SortFields"]},{canonical:"NotShowFields",explicitKeys:["notShowFields","NotShowFields"],refKeys:["hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName"]},{canonical:"InTableEditFields",explicitKeys:["inTableEditFields","InTableEditFields"],refKeys:["editableFields","EditableFields","inTableEditFieldsByName","InTableEditFieldsByName"]},{canonical:"MobileListFields",explicitKeys:["mobileListFields","MobileListFields"],refKeys:["mobileFields","MobileFields"],objectArray:!0},{canonical:"CardTitleTagFields",explicitKeys:["cardTitleTagFields","CardTitleTagFields"],refKeys:["cardTitleFields","CardTitleFields"],objectArray:!0},{canonical:"CardBottomTagFields",explicitKeys:["cardBottomTagFields","CardBottomTagFields"],refKeys:["cardBottomFields","CardBottomFields"],objectArray:!0}];for(let m of u){if(dt(t,...m.explicitKeys))continue;let h=Vr(t,...m.refKeys),g={SortFieldIds:wY(i),NotShowFields:vY(i),MobileListFields:_Y(i),CardTitleTagFields:SY(i),CardBottomTagFields:EY(i),InTableEditFields:[]};if(!h.length&&!g[m.canonical]?.length)continue;let y=h.length?_s(e,r,n,h,`module.${m.canonical}`):g[m.canonical].map(x=>({meta:x,ref:{ref:x.name}}));o[m.canonical]=JSON.stringify(m.objectArray?y.map(({meta:x,ref:b})=>B0(x,b)):y.map(({meta:x})=>x.id))}let p=Vr(t,"statisticsFieldNames","StatisticsFieldNames","statFields","StatFields");if(!dt(t,"statisticsFields","StatisticsFields")){let m=p.length?_s(e,r,n,p,"module.statisticsFields"):P2(i).map(h=>({meta:h,ref:{ref:h.name,type:"Sum"}}));m.length&&(o.StatisticsFields=JSON.stringify(m.map(({meta:h,ref:g})=>({Id:h.id,Type:g.type||"Sum"}))))}let f=TY(t,e,r,n)||(dt(t,"DefaultOrderBy","defaultOrderBy")?void 0:kY(i,r,n));return f&&(o.DefaultOrderBy=f),o}function l2(t,e,r){let n=ii(H(e).Tables);for(let i of n){let o=S(i,"Id","id"),a=S(i,"Name","name");if(!o||!a)continue;r?.set(a.toLowerCase(),o);let s=Le(i,"_Fields","Fields","fields"),c=Array.isArray(s)?ii(s):[];for(let l of c){let u=S(l,"Id","id"),p=S(l,"Name","name");!u||!p||T2(t,{id:u,name:p,label:S(l,"Label","label")||p,tableId:o,tableName:a,tableDescription:S(i,"Description","description")||a,component:S(l,"Component","component")||"Text",type:S(l,"Type","type")||"varchar(255)"})}}}function Ot(t){return br(S(t,"component","Component")||"Text")}function IY(t){return`${S(t,"name","Name")} ${S(t,"label","Label")} ${S(t,"component","Component")}`.toLowerCase()}function AY(t,e){let r=IY(t),n=Ot(t);return["imgupload","fileupload","richtext","codeeditor","jsontable","tablechild","map","maparea","textarea"].includes(n)||be(r,["remark","note","content","file","image","attach","map","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247","\u5730\u56FE"])?"attachment":be(r,["phone","mobile","email","address","city","contact","\u8054\u7CFB\u4EBA","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1","\u5730\u5740","\u57CE\u5E02"])?"contact":be(r,["status","state","type","category","amount","money","price","count","date","time","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF","\u65F6\u95F4","\u65E5\u671F"])?"business":e<8?"basic":"extra"}function K0(t){let e=ie(t,"fields","Fields"),r=Le(t,"tabs","Tabs"),n=new Map,i=oe(t,"column","Column")??(e.length>6?2:void 0);if(r!=null&&r!=="")return{fieldTabs:n,column:i};let o=e.filter(l=>!Q0.has(Ot(l)));if(o.length<=12)return{fieldTabs:n,column:i};let a={basic:{Name:"\u57FA\u7840\u4FE1\u606F",Icon:"fas fa-id-card",Sort:10},contact:{Name:"\u8054\u7CFB\u4FE1\u606F",Icon:"fas fa-address-book",Sort:20},business:{Name:"\u4E1A\u52A1\u4FE1\u606F",Icon:"fas fa-briefcase",Sort:30},attachment:{Name:"\u9644\u4EF6\u5907\u6CE8",Icon:"fas fa-paperclip",Sort:40},extra:{Name:"\u6269\u5C55\u4FE1\u606F",Icon:"fas fa-layer-group",Sort:50}},s=new Set;return o.forEach((l,u)=>{let p=S(l,"name","Name");if(!p||S(l,"tab","Tab"))return;let f=AY(l,u);n.set(p,f),s.add(f)}),{tabs:["basic","contact","business","attachment","extra"].filter(l=>s.has(l)).map(l=>({Id:l,Name:a[l].Name,Icon:a[l].Icon,Sort:a[l].Sort})),fieldTabs:n,column:i}}function q0(t){let e=[],r=[],n=[],i=ie(t,"roles","Roles"),o=ie(t,"tables","Tables"),a=ie(t,"engines","Engines"),s=ie(t,"modules","Modules"),c=ie(t,"events","Events"),l=ie(t,"dataSources","DataSources"),u=ie(t,"pages","Pages"),p=ie(t,"printTemplates","PrintTemplates"),f=ie(t,"workflows","Workflows"),m=ie(t,"jobs","Jobs"),h=ie(t,"permissions","Permissions"),g=new Map,y=new Set(a.map(b=>S(b,"apiEngineKey","ApiEngineKey").toLowerCase()).filter(Boolean));!o.length&&!a.length&&!s.length&&!u.length&&r.push("Manifest \u672A\u58F0\u660E tables/engines/modules/pages\uFF0C\u53EF\u80FD\u4E0D\u662F\u5B8C\u6574\u7CFB\u7EDF\u8BA1\u5212");let x=UY(t);return e.push(...x.errors),r.push(...x.warnings),i.forEach(b=>n.push(`save_role ${S(b,"name","Name")}`)),o.forEach((b,v)=>{let _=S(b,"name","Name");_||e.push(`tables[${v}].name \u4E0D\u80FD\u4E3A\u7A7A`),oY(b,`tables[${v}]`,e,r);let w=Le(b,"readPrimary","ReadPrimary");w!=null&&w!==0&&w!==1&&e.push(`tables[${v}].readPrimary \u5FC5\u987B\u662F null\u30010 \u6216 1`),Object.hasOwn(b,"readPrimary")&&Object.hasOwn(b,"ReadPrimary")&&b.readPrimary!==b.ReadPrimary&&e.push(`tables[${v}].readPrimary \u4E0E ReadPrimary \u4E0D\u4E00\u81F4`),n.push(`create_table ${_||`(index ${v})`}`),K0(b).tabs?.length&&r.push(`table ${_||`(index ${v})`} has many fields; generator will create diy_table.Tabs and assign empty field Tab values automatically`),_&&g.set(_.toLowerCase(),new Set),ie(b,"fields","Fields").forEach((z,j)=>{let K=S(z,"name","Name"),ee=S(z,"label","Label");K||e.push(`tables[${v}].fields[${j}].name \u4E0D\u80FD\u4E3A\u7A7A`),ee||e.push(`tables[${v}].fields[${j}].label \u4E0D\u80FD\u4E3A\u7A7A`),_&&K&&g.get(_.toLowerCase())?.add(K.toLowerCase()),_&&ee&&g.get(_.toLowerCase())?.add(ee.toLowerCase()),n.push(`add_field ${_}.${K}`)});let E=Dl(b);n.push(`configure_form_banner ${_||`(index ${v})`}`);let T=g.get(_.toLowerCase())||new Set,A=(z,j)=>{z&&!T.has(z.toLowerCase())&&!Pl(z)&&e.push(`${j} references unknown field "${z}" on table "${_}"`)};A(S(E,"FormBannerTitleField"),`tables[${v}].formBanner.titleField`),A(S(E,"FormBannerSubtitleField"),`tables[${v}].formBanner.subtitleField`),A(S(E,"FormBannerImageField"),`tables[${v}].formBanner.imageField`),A(S(E,"FormBannerBackgroundField"),`tables[${v}].formBanner.backgroundField`),$f(JSON.parse(S(E,"FormBannerTagFields")||"[]")).forEach((z,j)=>{let K=typeof z=="string"?z:S(H(z),"Field","field","Name","name");A(K,`tables[${v}].formBanner.tagFields[${j}]`)}),$f(JSON.parse(S(E,"FormBannerMetrics")||"[]")).forEach((z,j)=>{let K=H(z),ee=typeof z=="string"?z:S(K,"Field","field","Name","name");A(ee,`tables[${v}].formBanner.metrics[${j}]`);let _e=S(K,"ApiEngineKey","apiEngineKey");_e&&!y.has(_e.toLowerCase())&&r.push(`tables[${v}].formBanner.metrics[${j}] references ApiEngineKey "${_e}" not declared in this manifest; it must already exist in the target tenant`)});let F=new Set(ie(b,"fields","Fields").filter(z=>{let j=Ot(z);return!["opentable","phonesms","tablechild","button","divider","collapsegroup","tabs","alert","statictext","html"].includes(j)&&(j!=="devcomponent"||!!S(z,"type","Type"))}).map(z=>S(z,"name","Name").toLowerCase()).filter(Boolean));["id","createtime","updatetime","userid","username","isdeleted"].forEach(z=>F.add(z)),ie(b,"indexes","Indexes").forEach((z,j)=>{let K=Ss(z,"columns","Columns");K.length||e.push(`tables[${v}].indexes[${j}].columns \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5`);for(let ee of K)F.has(ee.toLowerCase())||e.push(`tables[${v}].indexes[${j}] references unknown physical field "${ee}" on table "${_}"`);K.some((ee,_e)=>K.findIndex(me=>me.toLowerCase()===ee.toLowerCase())!==_e)&&e.push(`tables[${v}].indexes[${j}] \u5305\u542B\u91CD\u590D\u5B57\u6BB5`),n.push(`create_index ${_}.${S(z,"name","Name")||K.join("_")}`)})}),l.forEach(b=>n.push(`save_data_source ${S(b,"dataSourceKey","DataSourceKey")}`)),a.forEach((b,v)=>{let _=S(b,"apiEngineKey","ApiEngineKey");_||e.push(`engines[${v}].apiEngineKey \u4E0D\u80FD\u4E3A\u7A7A`),sY(b,`engines[${v}]`,e,r),n.push(`upsert_engine ${_}`)}),c.forEach(b=>n.push(`save_event ${S(b,"formEngineKey","FormEngineKey")}/${S(b,"eventType","EventType")}`)),s.forEach(b=>{let v=ks(b);e.push(...v.errors),r.push(...v.warnings);let _=S(b,"table","tableName","diyTableName","DiyTableName"),w=S(b,"name","Name"),C=S(b,"openType","OpenType");if(C.toLowerCase()==="workflow"){let I=S(b,"flowName","FlowName"),R=S(b,"flowDesignId","FlowDesignId");!I&&!R&&e.push(`modules.${w||"(unnamed)"}.flowName \u6216 flowDesignId \u5FC5\u987B\u6307\u5411\u5DF2\u542F\u7528\u6D41\u7A0B`),I&&!f.some(z=>S(H(z.FlowDesign??z.flowDesign),"FlowName","flowName")===I)&&e.push(`modules.${w||"(unnamed)"}.flowName ${I} \u672A\u5728\u672C\u6B21 workflows \u4E2D\u58F0\u660E\uFF1B\u73B0\u6709\u6D41\u7A0B\u8BF7\u4F7F\u7528 flowDesignId`);let F=f.find(z=>S(H(z.FlowDesign??z.flowDesign),"FlowName","flowName")===I);if(F){let z=H(F.FlowDesign??F.flowDesign);(oe(z,"IsEnable","isEnable")===0||Le(z,"IsEnable","isEnable")===!1)&&e.push(`modules.${w||"(unnamed)"}.flowName ${I} \u6307\u5411\u7981\u7528\u6D41\u7A0B`);let j=S(b,"table","tableName","diyTableName","DiyTableName"),K=S(z,"table","tableName","diyTableName","DiyTableName");j&&K&&j.toLowerCase()!==K.toLowerCase()&&e.push(`modules.${w||"(unnamed)"} \u7684 table \u4E0E\u6D41\u7A0B ${I} \u7684\u4E1A\u52A1\u8868\u4E0D\u4E00\u81F4`)}S(b,"diyTableId","DiyTableId","table","tableName","diyTableName","DiyTableName")||e.push(`modules.${w||"(unnamed)"} \u5FC5\u987B\u7ED1\u5B9A\u4E0E\u6D41\u7A0B\u76F8\u540C\u7684 diy_table`)}let E=S(b,"microServiceKey","MicroServiceKey"),T=S(b,"microServiceRoutePath","MicroServiceRoutePath");if(["microservice","codeform"].includes(C.toLowerCase())||!!(oe(b,"isMicroiService","IsMicroiService")===1||E||T||S(b,"microServiceId","MicroServiceId")||S(b,"microServicePageId","MicroServicePageId"))){if(E||e.push(`modules.${w||"(unnamed)"}.microServiceKey \u4E0D\u80FD\u4E3A\u7A7A`),T||e.push(`modules.${w||"(unnamed)"}.microServiceRoutePath \u4E0D\u80FD\u4E3A\u7A7A`),T)try{Y0(T)}catch(I){e.push(`modules.${w||"(unnamed)"}.microServiceRoutePath ${I instanceof Error?I.message:String(I)}`)}n.push(`resolve_microservice_binding ${E||"(missing)"}${T||"/(missing)"}`)}if(_&&g.has(_.toLowerCase())){let I=g.get(_.toLowerCase())||new Set,R=[["listFields",Vr(b,"listFields","ListFields","tableFields","TableFields","columns","Columns")],["searchFields",Vr(b,"searchFields","SearchFields","searchFieldNames","SearchFieldNames")],["sortFields",Vr(b,"sortFields","SortFields")],["hiddenFields",Vr(b,"hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName")],["mobileFields",Vr(b,"mobileFields","MobileFields")]];for(let[F,z]of R)for(let j of z)!I.has(j.ref.toLowerCase())&&!Pl(j.ref)&&e.push(`modules.${w||_}.${F} references unknown field "${j.ref}" on table "${_}"`)}_&&!Vr(b,"listFields","ListFields","tableFields","TableFields","columns","Columns").length&&!dt(b,"TableDiyFieldIds","SelectFields")&&r.push(`module ${w||_} has no listFields; generator will use the first business fields from ${_}`),n.push(`create_or_update_module ${S(b,"name","Name")}`)}),h.forEach(b=>n.push(`set_permission ${S(b,"roleId","RoleId")||"admin"}`)),u.forEach((b,v)=>{let _=ti(b.json??b.JsonObj??b.JsonStr??b);e.push(..._.errors.map(w=>`pages[${v}]: ${w}`)),r.push(..._.warnings.map(w=>`pages[${v}]: ${w}`)),n.push(`save_page ${S(b,"title","Title")}`)}),p.forEach((b,v)=>{let _=Yo(b.PageObj??b.pageObj),w=Qo(b.PrintObj??b.printObj);e.push(..._.errors.map(C=>`printTemplates[${v}].PageObj: ${C}`)),r.push(..._.warnings.map(C=>`printTemplates[${v}].PageObj: ${C}`)),e.push(...w.errors.map(C=>`printTemplates[${v}].PrintObj: ${C}`)),r.push(...w.warnings.map(C=>`printTemplates[${v}].PrintObj: ${C}`)),n.push(`save_print_template ${S(b,"title","Title")}`)}),f.forEach((b,v)=>{let _=W0(b);e.push(..._.errors.map(w=>`workflows[${v}]: ${w}`)),r.push(..._.warnings.map(w=>`workflows[${v}]: ${w}`)),n.push(`save_workflow ${S(H(b.FlowDesign??b.flowDesign??b),"FlowName","flowName","name")}`)}),m.forEach(b=>n.push(`save_job ${S(b,"jobName","JobName")}`)),{plan:n,errors:e,warnings:r}}function tw(t){return{flow:H(t.FlowDesign??t.flowDesign??t),nodes:ie(t,"Nodes","nodes"),lines:ie(t,"Lines","lines")}}function gt(t){return S(t,"Id","id","NodeId","nodeId")}function Ur(t){return S(t,"NodeName","nodeName","Name","name")}function Af(t){return S(t,"NodeType","nodeType","Type","type")}function Rf(t){return Af(t)==="Start"}function u2(t){return["End","AutoEnd"].includes(Af(t))}var RY=new Set(["Start","Auto","Business","End","AutoEnd","Countersign","Approve"]),PY=new Set(["Approve","Countersign","End"]),O2=["Users","Roles","Depts","BindJobs"],$Y=[...O2,"CopyUsers"];function Pf(t,e,r){let n=Le(t,e,e[0].toLowerCase()+e.slice(1));if(n==null||n==="")return[];let i=n;if(typeof n=="string")try{i=JSON.parse(n)}catch{i=null}return!Array.isArray(i)||i.some(o=>!S(H(o),"Id")||!S(H(o),"Name","JobName"))?(r.push(`\u8282\u70B9 ${Ur(t)||gt(t)}.${e} \u5FC5\u987B\u662F [{Id,Name}] \u6570\u7EC4\uFF1B\u4E0D\u80FD\u4F7F\u7528\u89D2\u8272\u540D\u6216 Id \u5B57\u7B26\u4E32`),[]):i.map(o=>({Id:S(o,"Id"),Name:S(o,"Name","JobName")}))}function OY(t,e,r){let n=Le(t,"BackNodes","backNodes");if(n==null||n==="")return"[]";let i=n;if(typeof n=="string")try{i=JSON.parse(n)}catch{i=null}if(!Array.isArray(i))return r.push(`\u8282\u70B9 ${Ur(t)||gt(t)}.BackNodes \u5FC5\u987B\u662F\u8282\u70B9 Id \u6216 {Id,NodeName} \u6570\u7EC4`),"[]";let o=i.map(a=>{let s=typeof a=="string"?a:S(H(a),"Id");e.has(s)||r.push(`\u8282\u70B9 ${Ur(t)||gt(t)}.BackNodes \u5F15\u7528\u4E86\u4E0D\u5B58\u5728\u7684\u8282\u70B9 ${s}`);let c=e.get(s);return{Id:s,NodeName:c?Ur(c):S(H(a),"NodeName")}});return JSON.stringify(o)}function p2(t,e,r){let n=Le(t,e,e[0].toLowerCase()+e.slice(1));if(n==null||n==="")return;let i=/^(\d+(?:\.\d+)?)(?:px)?$/.exec(String(n).trim());if(!i||Number(i[1])>1e5){r.push(`\u8282\u70B9 ${Ur(t)||gt(t)}.${e} \u5FC5\u987B\u662F\u975E\u8D1F\u50CF\u7D20\u5750\u6807`);return}return Number(i[1])}function N2(t,e,r){let n=new Map(t.map(c=>[gt(c),c])),i=new Map,o=t.filter(Rf).map(gt);for(o.forEach(c=>i.set(c,0));o.length;){let c=o.shift();for(let l of e.filter(u=>S(u,"FromNodeId","fromNodeId")===c)){let u=S(l,"ToNodeId","toNodeId");!n.has(u)||i.has(u)||(i.set(u,(i.get(c)||0)+1),o.push(u))}}let a=new Map,s=new Set;return t.map((c,l)=>{let u=i.get(gt(c))??l,p=a.get(u)||0;a.set(u,p+1);let f=p2(c,"PositionLeft",r)??80+u*260,m=p2(c,"PositionTop",r)??120+p*150,h=`${f}:${m}`;s.has(h)&&r.push(`\u8282\u70B9 ${Ur(c)||gt(c)} \u4E0E\u5176\u5B83\u8282\u70B9\u5750\u6807\u91CD\u53E0`),s.add(h);let g={...c,PositionLeft:`${f}px`,PositionTop:`${m}px`};for(let y of $Y)g[y]=JSON.stringify(Pf(c,y,r));return g.BackNodes=OY(c,n,r),g})}function W0(t){let e=[],r=[],{flow:n,nodes:i,lines:o}=tw(t),a=S(n,"FlowName","flowName","Name","name"),s=S(n,"TableId","tableId"),c=S(n,"table","tableName","TableName","diyTableName","DiyTableName"),l=Object.prototype.hasOwnProperty.call(n,"IsEnable")&&(n.IsEnable===0||n.IsEnable==="0"),u=new Map,p=new Map,f=new Map;a||e.push("FlowDesign.FlowName \u4E0D\u80FD\u4E3A\u7A7A"),Pf(n,"Roles",e),i.length||e.push("Nodes \u81F3\u5C11\u9700\u8981\u5305\u542B\u5F00\u59CB\u3001\u5BA1\u6279/\u4E1A\u52A1\u3001\u7ED3\u675F\u8282\u70B9"),o.length||e.push("Lines \u81F3\u5C11\u9700\u8981\u8FDE\u63A5\u5F00\u59CB\u5230\u4E0B\u4E00\u8282\u70B9"),!s&&!c&&r.push("\u6D41\u7A0B\u672A\u7ED1\u5B9A\u4E1A\u52A1 diy_table\uFF1B\u82E5\u8981\u901A\u8FC7\u6A21\u5757\u5F15\u64CE\u6253\u5F00\u6D41\u7A0B\uFF0C\u5FC5\u987B\u7ED1\u5B9A\u540C\u4E00\u4E1A\u52A1\u8868"),i.forEach((b,v)=>{let _=gt(b),w=Ur(b);_||e.push(`Nodes[${v}].Id/NodeId \u4E0D\u80FD\u4E3A\u7A7A`),w||e.push(`Nodes[${v}].NodeName \u4E0D\u80FD\u4E3A\u7A7A`),RY.has(Af(b))||e.push(`Nodes[${v}].NodeType \u5FC5\u987B\u662F Start/Auto/Business/End/AutoEnd/Countersign/Approve`),_&&(u.has(_)&&e.push(`\u8282\u70B9 Id \u91CD\u590D\uFF1A${_}`),u.set(_,b))}),o.forEach((b,v)=>{let _=S(b,"Id","id","LineId","lineId")||`(index ${v})`,w=S(b,"FromNodeId","fromNodeId"),C=S(b,"ToNodeId","toNodeId");w||e.push(`Lines[${v}].FromNodeId \u4E0D\u80FD\u4E3A\u7A7A`),C||e.push(`Lines[${v}].ToNodeId \u4E0D\u80FD\u4E3A\u7A7A`),w&&!u.has(w)&&e.push(`\u8FDE\u7EBF ${_} \u7684 FromNodeId \u4E0D\u5B58\u5728\uFF1A${w}`),C&&!u.has(C)&&e.push(`\u8FDE\u7EBF ${_} \u7684 ToNodeId \u4E0D\u5B58\u5728\uFF1A${C}`),w===C&&w&&r.push(`\u8FDE\u7EBF ${_} \u6307\u5411\u81EA\u8EAB\uFF0C\u8BF7\u786E\u8BA4\u662F\u5426\u4E3A\u6709\u610F\u5FAA\u73AF`),w&&p.set(w,[...p.get(w)||[],b]),C&&f.set(C,[...f.get(C)||[],b])});let m=i.filter(Rf),h=i.filter(u2);m.length!==1&&e.push(`\u9700\u8981\u4E14\u4EC5\u9700\u8981 1 \u4E2A\u5F00\u59CB\u8282\u70B9\uFF0C\u5F53\u524D ${m.length} \u4E2A`),h.length<1&&e.push("\u81F3\u5C11\u9700\u8981 1 \u4E2A\u7ED3\u675F\u8282\u70B9");let g=N2(i,o,e);i.forEach(b=>{let v=gt(b),_=Ur(b)||v;if(!v)return;let w=p.get(v)||[],C=f.get(v)||[];if(!Rf(b)&&C.length===0&&r.push(`\u8282\u70B9 ${_} \u6CA1\u6709\u5165\u7EBF`),!u2(b)&&w.length===0&&r.push(`\u8282\u70B9 ${_} \u6CA1\u6709\u51FA\u7EBF`),PY.has(Af(b))){let E=O2.flatMap(A=>Pf(b,A,[])),T=C.some(A=>{let I=u.get(S(A,"FromNodeId","fromNodeId"))||{};return oe(I,"AllowSelectUsers","allowSelectUsers")===1||Le(I,"AllowSelectUsers","allowSelectUsers")===!0});!E.length&&!T&&!l&&e.push(`\u4EBA\u5DE5\u8282\u70B9 ${_} \u672A\u7ED1\u5B9A Users/Roles/Depts/BindJobs\uFF0C\u4E14\u4E0A\u6E38\u8282\u70B9\u6CA1\u6709\u624B\u52A8\u9009\u4EBA\u7B56\u7565\uFF1BSameDeptApprove \u4EC5\u7B5B\u9009\u5019\u9009\u4EBA\uFF0C\u4E0D\u80FD\u72EC\u7ACB\u6307\u5B9A\u5BA1\u6279\u4EBA`)}w.length>1&&(S(b,"LineValueV8","lineValueV8","V8Code","v8Code")||r.push(`\u8282\u70B9 ${_} \u6709 ${w.length} \u6761\u51FA\u7EBF\uFF0C\u5EFA\u8BAE\u914D\u7F6E LineValueV8\uFF0C\u5E76\u4F18\u5148\u7528 V8.NextNodeId \u6307\u5B9A\u4E0B\u4E00\u8282\u70B9`))});let y=new Set(m.map(gt)),x=[...y];for(;x.length;){let b=x.shift();for(let v of p.get(b)||[]){let _=S(v,"ToNodeId","toNodeId");!y.has(_)&&u.has(_)&&(y.add(_),x.push(_))}}for(let b of i)gt(b)&&!y.has(gt(b))&&e.push(`\u8282\u70B9 ${Ur(b)} \u4ECE\u5F00\u59CB\u8282\u70B9\u4E0D\u53EF\u8FBE`);return h.length&&!h.some(b=>y.has(gt(b)))&&e.push("\u7ED3\u675F\u8282\u70B9\u4ECE\u5F00\u59CB\u8282\u70B9\u4E0D\u53EF\u8FBE"),{ok:e.length===0,errors:e,warnings:r,summary:{flowName:a,tableId:s,table:c,nodeCount:i.length,lineCount:o.length,positions:g.map(b=>({id:gt(b),left:b.PositionLeft,top:b.PositionTop})),startNodes:m.map(b=>({id:gt(b),name:Ur(b)})),endNodes:h.map(b=>({id:gt(b),name:Ur(b)}))}}}function NY(t){let e=t.indexOf(a2);if(e<0)return null;let r=e+a2.length,n=t.indexOf(QX,r);if(n<0)return null;try{return H(JSON.parse(t.slice(r,n).trim()))}catch{return null}}function d2(t){return t==null||String(t).trim()===""}function f2(t,e){let r=S(t,"field","Field"),n=S(t,"operator","Operator")||"eq",i=Le(t,"value","Value"),o=r?e[r]:void 0,a=o==null?"":String(o),s=i==null?"":String(i);if(n==="empty")return d2(o);if(n==="notEmpty")return!d2(o);if(n==="contains")return a.includes(s);if(n==="notContains")return!a.includes(s);if(n==="startsWith")return a.startsWith(s);if(n==="endsWith")return s===""||a.endsWith(s);if(["gt","gte","lt","lte"].includes(n)){let c=Number(o),l=Number(i);return Number.isNaN(c)||Number.isNaN(l)?!1:n==="gt"?c>l:n==="gte"?c>=l:n==="lt"?c<l:c<=l}return n==="ne"?a!==s:a===s}function MY(t){let e=H(t.workflow),r=H(t.formData),n=S(t,"lineValueV8Code","LineValueV8","code");if(!n&&Object.keys(e).length>0){let{nodes:s}=tw(e),c=S(t,"nodeId","NodeId"),l=(c?s.find(u=>gt(u)===c):s.find(Rf)||s[0])||{};n=S(l,"LineValueV8","lineValueV8","V8Code","v8Code")}let i=NY(n),o=ie(i||{},"routes","Routes");if(!i||o.length===0)return{ok:!1,selectedRoute:null,warnings:["\u672A\u627E\u5230\u56FE\u5F62\u6761\u4EF6\u6807\u8BB0\uFF0CMCP \u4E0D\u6267\u884C\u4EFB\u610F\u624B\u5199 V8\uFF1B\u8BF7\u7528\u56FE\u5F62\u6761\u4EF6\u751F\u6210 LineValueV8 \u540E\u518D\u6D4B\u8BD5\u3002"]};let a=o.find(s=>!!Le(s,"isDefault","IsDefault"))||null;for(let s of o){if(s===a)continue;let c=ie(s,"rules","Rules").filter(u=>S(u,"field","Field"));if(c.length===0)continue;if(S(s,"match","Match")==="any"?c.some(u=>f2(u,r)):c.every(u=>f2(u,r)))return{ok:!0,selectedRoute:s,assignment:m2(s),source:"matched"}}return{ok:!!a,selectedRoute:a,assignment:a?m2(a):null,source:a?"default":"none"}}function m2(t){let e=S(t,"lineValue","LineValue"),r=S(t,"toNodeId","ToNodeId");return e?{LineValue:e}:{NextNodeId:r}}function h2(t,e){let{flow:r,nodes:n,lines:i}=tw(t),o={...r},a=[];if(o.Roles=JSON.stringify(Pf(r,"Roles",a)),a.length)throw new Error(a.join("\uFF1B"));let s=S(r,"table","tableName","TableName","diyTableName","DiyTableName");if(!S(o,"TableId","tableId")&&s){let m=e.get(s.toLowerCase());if(!m)throw new Error(`\u6D41\u7A0B\u4E1A\u52A1\u8868 ${s} \u5728\u5F53\u524D\u79DF\u6237\u4E0D\u5B58\u5728`);o.TableId=m}let c=new Map,l=n.map((m,h)=>{let g=gt(m)||`wf_node_${h+1}_${V0().slice(0,8)}`,y={...m,Id:g},x=Ur(y);return x&&c.set(g,x),y}),u=i.map((m,h)=>{let g=S(m,"FromNodeId","fromNodeId"),y=S(m,"ToNodeId","toNodeId"),x=S(m,"LineName","lineName")||`${c.get(g)||g||"\u5F53\u524D\u8282\u70B9"} \u5230 ${c.get(y)||y||"\u4E0B\u4E00\u8282\u70B9"}`;return{...m,Id:S(m,"Id","id","LineId","lineId")||`wf_line_${h+1}_${V0().slice(0,8)}`,LineName:x}}),p=[],f=N2(l,u,p);if(p.length)throw new Error(p.join("\uFF1B"));return{FlowDesign:o,Nodes:f,Lines:u}}async function g2(t,e){let r=[{table:"sys_user",field:"Users",owners:ie(e,"Nodes")},{table:"sys_user",field:"CopyUsers",owners:ie(e,"Nodes")},{table:"sys_role",field:"Roles",owners:[H(e.FlowDesign),...ie(e,"Nodes")]},{table:"sys_dept",field:"Depts",owners:ie(e,"Nodes")},{table:"diy_job",field:"BindJobs",owners:ie(e,"Nodes")}],n=[];for(let i of r){let o=[...new Set(i.owners.flatMap(a=>{try{return ii(JSON.parse(S(a,i.field)||"[]")).map(s=>S(s,"Id")).filter(Boolean)}catch{return n.push(`${i.field} \u4E0D\u662F\u6709\u6548 JSON`),[]}}))];for(let a=0;a<o.length;a+=100){let s=o.slice(a,a+100);try{let c=await t.getTableData(i.table,{_Where:[["Id","In",s]],_SelectFields:["Id"],_PageIndex:1,_PageSize:s.length+1});if(c.Code!==1)throw new Error(c.Msg||`Code=${c.Code}`);let l=new Set(I2(c.Data).map(u=>S(u,"Id")));for(let u of s)l.has(u)||n.push(`${i.field} \u5F15\u7528\u4E86\u5F53\u524D\u79DF\u6237\u4E0D\u5B58\u5728\u7684 ${i.table}.Id=${u}`)}catch(c){n.push(`${i.field} \u65E0\u6CD5\u6838\u5BF9\u5F53\u524D\u79DF\u6237 ${i.table}\uFF1A${c instanceof Error?c.message:String(c)}`)}}}return n}async function qr(t,e,r,n){try{await t.writeAuditLog(e,r,JSON.stringify(n).slice(0,6e3))}catch(i){console.error("[microi-mcp] audit log failed:",i instanceof Error?i.message:String(i))}}async function y2(t,e){let r=S(e,"apiEngineKey","ApiEngineKey"),n=S(e,"apiName","ApiName","name","Name")||r,i=S(e,"category","Category")||"AI\u751F\u6210",o=Le(e,"code","Code","ApiV8Code"),a=typeof o=="string",s=a?String(o):"",c=Ol(e),l=await t.getEngineCode(r);return l.Code===1?!a&&c!==void 0?t.updateEngineRuntimeLimit(r,c):a?t.saveEngineCode(r,s,{functionDescription:S(e,"functionDescription","FunctionDescription")||void 0,changeSummary:S(e,"changeSummary","ChangeSummary")||void 0,v8Limit:c}):{Code:1,Data:{ApiEngineKey:r,V8Limit:Number(l.Data?.V8Limit||0),Skipped:!0},Msg:"\u63A5\u53E3\u5F15\u64CE\u5DF2\u5B58\u5728\uFF0CManifest \u672A\u63D0\u4F9B code \u6216 V8Limit\uFF0C\u4FDD\u6301\u539F\u914D\u7F6E"}:t.createEngine({ApiEngineKey:r,ApiName:n,Category:i,Code:s,V8Limit:c===void 0?void 0:c?1:0,functionDescription:S(e,"functionDescription","FunctionDescription")||void 0,changeSummary:S(e,"changeSummary","ChangeSummary")||void 0})}function DY(t,e,r,n){let i=S(t,"table","tableName","diyTableName","DiyTableName"),o=ks(t);if(o.errors.length)throw new Error(o.errors.join(`
134
134
  `));let a=S(t,"diyTableId","DiyTableId")||(i?e.get(i.toLowerCase()):""),s=i||S(t,"DiyTableName","diyTableName"),c=n?CY(t,n,a||"",s):{},l=oe(t,"display","Display")??1,u=oe(t,"appDisplay","AppDisplay")??1,p=S(t,"openType","OpenType")||"Diy",f=o.data.ViewSchema;if(!f&&n&&a&&(l===1||u===1)&&br(p)==="diy"){let h=Es(n,a).length?Es(n,a):Es(n,s);if(h.length){let g=ew(S(t,"name","Name"),h,h[0]?.tableDescription||s),y=Of(g);if(!y.ok)throw new Error(y.errors.join(`
135
135
  `));f=y.value}}return dn({...o.data,...c,Name:S(t,"name","Name"),DiyTableId:a,ParentId:S(t,"parentId","ParentId")||(r?r.get(S(t,"parentName","ParentName").toLowerCase()):void 0),ComponentName:S(t,"componentName","ComponentName"),ComponentPath:S(t,"componentPath","ComponentPath"),Display:l,AppDisplay:u,HasChild:oe(t,"hasChild","HasChild"),OpenType:p,FlowDesignId:S(t,"flowDesignId","FlowDesignId"),Url:S(t,"url","Url"),Sort:oe(t,"sort","Sort"),Icon:S(t,"icon","Icon"),SearchFieldIds:dt(t,"searchFieldIds","SearchFieldIds")||c.SearchFieldIds,TableDiyFieldIds:dt(t,"tableDiyFieldIds","TableDiyFieldIds")||c.TableDiyFieldIds,SelectFields:dt(t,"selectFields","SelectFields")||c.SelectFields,TableHeaders:dt(t,"tableHeaders","TableHeaders"),HideTableBanner:typeof(t.hideTableBanner??t.HideTableBanner)=="boolean"?t.hideTableBanner??t.HideTableBanner?1:0:oe(t,"hideTableBanner","HideTableBanner"),HideFormBanner:typeof(t.hideFormBanner??t.HideFormBanner)=="boolean"?t.hideFormBanner??t.HideFormBanner?1:0:oe(t,"hideFormBanner","HideFormBanner"),DefaultOrderBy:dt(t,"DefaultOrderBy")||c.DefaultOrderBy,SqlWhere:S(t,"sqlWhere","SqlWhere"),SqlJoin:S(t,"sqlJoin","SqlJoin"),JoinTables:dt(t,"joinTables","JoinTables"),SortFieldIds:dt(t,"sortFieldIds","SortFieldIds")||c.SortFieldIds,NotShowFields:dt(t,"notShowFields","NotShowFields")||c.NotShowFields,StatisticsFields:dt(t,"statisticsFields","StatisticsFields")||c.StatisticsFields,InTableEdit:oe(t,"inTableEdit","InTableEdit"),InTableEditFields:dt(t,"inTableEditFields","InTableEditFields")||c.InTableEditFields,MobileListFields:dt(t,"mobileListFields","MobileListFields")||c.MobileListFields,CardTitleTagFields:dt(t,"cardTitleTagFields","CardTitleTagFields")||c.CardTitleTagFields,CardBottomTagFields:dt(t,"cardBottomTagFields","CardBottomTagFields")||c.CardBottomTagFields,MenuBadgeEnabled:oe(t,"menuBadgeEnabled","MenuBadgeEnabled"),MenuBadgeApiEngineKey:S(t,"menuBadgeApiEngineKey","MenuBadgeApiEngineKey"),EnableViewSchema:oe(t,"enableViewSchema","EnableViewSchema")??0,ViewSchemaVersion:S(t,"viewSchemaVersion","ViewSchemaVersion")||(f?"1.0":void 0),ViewConfigVersion:oe(t,"viewConfigVersion","ViewConfigVersion")??(f?1:void 0),ViewSchema:f,IsMicroiService:oe(t,"isMicroiService","IsMicroiService"),MicroServiceId:S(t,"microServiceId","MicroServiceId"),MicroServicePageId:S(t,"microServicePageId","MicroServicePageId"),MicroServiceRoutePath:S(t,"microServiceRoutePath","MicroServiceRoutePath"),MicroServiceKey:S(t,"microServiceKey","MicroServiceKey")})}function FY(t){let e=S(t,"formOpenType","FormOpenType"),r=S(t,"formOpenWidth","FormOpenWidth");if(e)return{type:e,width:r||"80%"};let i=ie(t,"fields","Fields").filter(c=>!Q0.has(Ot(c))),o=i.filter(c=>Ot(c)==="tablechild").length,a=i.filter(c=>["tablechild","richtext","codeeditor","jsontable","imgupload","fileupload","map","maparea","devcomponent"].includes(Ot(c))).length;return{type:i.length>=36||o>=2||i.length>=28&&o>=1||a>=7?"Drawer":"Dialog",width:r||"80%"}}function zY(t){let e=t.trim().toLowerCase().replace(/\s+/gu,"").replace(/[×**]/gu,":");return["1:1","one:one","one-to-one","onetoone"].includes(e)?"1:1":["n:1","many:one","many-to-one","manytoone"].includes(e)?"N:1":["1:n","one:many","one-to-many","onetomany"].includes(e)?"1:N":""}function rw(t){let e=Le(t,"relation","Relation");if(!e||typeof e!="object"||Array.isArray(e))return;let r=H(e);return{cardinality:zY(S(r,"cardinality","Cardinality")),targetTable:S(r,"targetTable","TargetTable","table","Table"),joinFieldName:S(r,"joinFieldName","JoinFieldName","foreignKey","ForeignKey"),childForeignKey:S(r,"childForeignKey","ChildForeignKey","foreignKey","ForeignKey"),childModule:S(r,"childModule","ChildModule","module","Module"),primaryTableFieldName:S(r,"primaryTableFieldName","PrimaryTableFieldName")||"Id"}}var LY=new Set(["collapsegroup","tabs","divider","empty","alert","statictext","html","button"]),G0=new Set(["select","multipleselect","radio","checkbox","switch","cascader","selecttree","department"]),jY=new Set(["numbertext","slider","rate","progress"]);function M2(t){return`${S(t,"name","Name")} ${S(t,"label","Label")} ${S(t,"description","Description")}`.toLowerCase()}function Tf(t,e,r){let n=M2(t),i=e.findIndex(o=>n.includes(o));return i>=0?100-i:r}function X0(t){return G0.has(Ot(t))?!1:jY.has(Ot(t))?!0:/^(tinyint|smallint|mediumint|int|bigint|decimal|numeric|float|double|real)(\b|\()/iu.test(S(t,"type","Type"))}function BY(t){if(!X0(t))return!1;let e=M2(t);return/(^|\s|_)(id|ids)(\s|_|$)|sort|order|latitude|longitude|phone|mobile|enabled?|disabled?|visible|deleted|status|state|type|category|version|timeout|retry|limit|pagesize|page size|offset|loaded|load count|record count|data count|排序|经度|纬度|电话|手机|启用|禁用|显示|删除|状态|类型|分类|版本|超时|重试|限制|分页|本页|加载|记录数/iu.test(e)?!1:be(e,["amount","money","price","total","count","quantity","number","score","rate","progress","budget","cost","fee","tax","discount","income","expense","balance","point","weight","volume","area","duration","hour","day","\u91D1\u989D","\u603B\u989D","\u4EF7\u683C","\u6570\u91CF","\u4E2A\u6570","\u79EF\u5206","\u6BD4\u4F8B","\u8FDB\u5EA6","\u4F59\u989D","\u9884\u7B97","\u6210\u672C","\u8D39\u7528","\u7A0E\u989D","\u6298\u6263","\u6536\u5165","\u652F\u51FA","\u91CD\u91CF","\u4F53\u79EF","\u9762\u79EF","\u65F6\u957F","\u5DE5\u65F6","\u5929\u6570","\u8BC4\u5206","\u5B8C\u6210\u5EA6"])}function $f(t){return Array.isArray(t)?t:typeof t!="string"||!t.trim()?[]:k2(t)}function Cf(t,e,r){for(let n of e)if(Object.prototype.hasOwnProperty.call(t,n)&&typeof t[n]=="string")return String(t[n]).trim();return r()}function Dl(t){let e=ie(t,"fields","Fields").filter(g=>{let y=S(g,"name","Name"),x=oe(g,"visible","Visible");return!!y&&x!==0&&!Pl(y)&&!LY.has(Ot(g))}),r=Le(t,"formBanner","FormBanner"),n=H(r),i=g=>e.map((y,x)=>({field:y,index:x,score:g(y,x)})).filter(y=>y.score>0).sort((y,x)=>x.score-y.score||y.index-x.index).map(y=>y.field),o=Cf(n,["titleField","TitleField"],()=>S(i((g,y)=>{let x=Tf(g,["title","name","subject","code","no","number","\u6807\u9898","\u540D\u79F0","\u4E3B\u9898","\u7F16\u53F7","\u5355\u53F7","\u7F16\u7801"],20-y);return Ot(g)==="autonumber"?x+=50:Ot(g)==="text"&&(x+=20),(G0.has(Ot(g))||X0(g))&&(x-=80),x})[0]||{},"name","Name")),a=Cf(n,["subtitleField","SubtitleField"],()=>S(i((g,y)=>S(g,"name","Name")===o||X0(g)||Ot(g)==="imgupload"?0:Tf(g,["subtitle","customer","client","project","company","category","type","date","contact","\u526F\u6807\u9898","\u5BA2\u6237","\u9879\u76EE","\u516C\u53F8","\u5355\u4F4D","\u5206\u7C7B","\u7C7B\u578B","\u65E5\u671F","\u8054\u7CFB\u4EBA","\u8BF4\u660E"],12-y)+(["text","select","radio","datetime","department","selecttree"].includes(Ot(g))?18:0))[0]||{},"name","Name")),s=Cf(n,["imageField","ImageField"],()=>S(e.find(g=>["imgupload","imageupload"].includes(Ot(g)))||{},"name","Name")),c=Le(n,"tagFields","TagFields","tags","Tags"),l=c!==void 0?$f(c):i((g,y)=>G0.has(Ot(g))?Tf(g,["status","state","stage","type","category","level","\u72B6\u6001","\u9636\u6BB5","\u7C7B\u578B","\u5206\u7C7B","\u7EA7\u522B"],30-y):0).slice(0,3).map(g=>({Key:S(g,"name","Name"),Field:S(g,"name","Name"),Label:S(g,"label","Label")||S(g,"name","Name")})),u=Le(n,"metrics","Metrics"),p=u!==void 0?$f(u):i(g=>BY(g)?Tf(g,["amount","money","price","total","count","quantity","number","score","rate","progress","budget","cost","fee","tax","discount","income","expense","balance","point","weight","\u91D1\u989D","\u603B\u989D","\u4EF7\u683C","\u6570\u91CF","\u4E2A\u6570","\u79EF\u5206","\u6BD4\u4F8B","\u8FDB\u5EA6","\u4F59\u989D","\u9884\u7B97","\u6210\u672C","\u8D39\u7528"],0):0).slice(0,3).map(g=>({Key:S(g,"name","Name"),Field:S(g,"name","Name"),Label:S(g,"label","Label")||S(g,"name","Name"),Auto:!0})),m={FormBannerEnabled:Zr(n,"enabled","Enabled")===!1?0:1,FormBannerTitleField:o,FormBannerSubtitleField:a,FormBannerImageField:s,FormBannerIcon:S(n,"icon","Icon")||"far fa-file-alt",FormBannerBackgroundField:Cf(n,["backgroundField","BackgroundField"],()=>""),FormBannerTagFields:JSON.stringify(l)},h=e.some(g=>Ot(g)==="tablechild"||rw(g)?.cardinality==="1:N");return(u!==void 0||p.length>0||!h)&&(m.FormBannerMetrics=JSON.stringify(p)),m}async function b2(t,e){let r=await t.validateLowCodeSystem(e);if(r.Code!==1)return r;let n=H(r.Data),i=Array.isArray(n.Errors)?[...n.Errors]:[],o=ie(e,"tables","Tables");for(let a=0;a<o.length;a+=100){let s=o.slice(a,a+100).map(u=>({name:S(u,"name","Name"),patch:{...Dl(u),...Le(u,"readPrimary","ReadPrimary")!==void 0?{ReadPrimary:Le(u,"readPrimary","ReadPrimary")}:{}}})),c=[...new Set(s.flatMap(u=>Object.keys(u.patch)))],l;try{let u=await t.getTableData("diy_table",{_Where:[["Name","In",s.map(p=>p.name)]],_SelectFields:["Id","Name",...c],_PageIndex:1,_PageSize:s.length+1});if(u.Code!==1)throw new Error("readback");l=I2(u.Data)}catch{i.push("\u8868\u5355 Banner \u56DE\u8BFB\u5931\u8D25\uFF1B\u8BF7\u68C0\u67E5\u5E73\u53F0\u5347\u7EA7\u4E0E\u5143\u6570\u636E\u8BFB\u53D6\u6743\u9650\uFF0C\u518D\u91CD\u65B0\u9A8C\u6536\u3002");continue}for(let u of s){let p=l.filter(h=>S(h,"Name").toLowerCase()===u.name.toLowerCase());if(p.length!==1){i.push(`\u8868 ${u.name} \u7684 Banner \u5143\u6570\u636E\u5E94\u552F\u4E00\uFF0C\u56DE\u8BFB\u6570\u91CF\u4E3A ${p.length}\u3002`);continue}let f=p[0],m=Object.entries(u.patch).filter(([h,g])=>!Object.hasOwn(f,h)||String(f[h]??"")!==String(g??""));m.length&&i.push(`\u8868 ${u.name} \u7684 Banner \u914D\u7F6E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${m.map(([h])=>h).join(", ")}\uFF1B\u7F3A\u5C11\u7269\u7406\u5B57\u6BB5\u65F6\u9700\u5148\u5B8C\u6210\u5E73\u53F0\u5347\u7EA7\uFF0C\u518D\u914D\u7F6E\u548C\u9A8C\u6536\u3002`)}}return i.length||n.Passed===!1?{...r,Code:0,Msg:r.Msg||"\u4F4E\u4EE3\u7801\u7CFB\u7EDF\u914D\u7F6E\u9A8C\u6536\u672A\u901A\u8FC7",Data:{...n,Passed:!1,Errors:i}}:r}function qY(t){if(typeof t=="string"){if(!t.trim())return{};try{return H(JSON.parse(t))}catch{return{}}}return H(t)}function VY(t){return S(t,"table","tableName","diyTableName","DiyTableName")}function UY(t){let e=[],r=[],n=ie(t,"tables","Tables"),i=ie(t,"modules","Modules"),o=new Map,a=new Map;for(let s of n){let c=S(s,"name","Name");c&&o.set(De(c),s)}for(let s of i){let c=S(s,"name","Name");c&&a.set(De(c),s)}return n.forEach((s,c)=>{let l=S(s,"name","Name"),u=ie(s,"fields","Fields"),p=new Set(u.map(f=>De(S(f,"name","Name"))).filter(Boolean));u.forEach((f,m)=>{let h=De(S(f,"component","Component"));if(h!=="joinform"&&h!=="tablechild")return;let g=`tables[${c}].fields[${m}]`,y=S(f,"name","Name"),x=rw(f);if(!x){e.push(`${g} (${l}.${y}) \u4F7F\u7528 ${h==="joinform"?"JoinForm":"TableChild"} \u65F6\u5FC5\u987B\u58F0\u660E portable relation\uFF1B\u7981\u6B62\u76F4\u63A5\u5199\u5165\u79DF\u6237 Id \u6216\u672A\u521D\u59CB\u5316 Config`);return}if(x.cardinality||e.push(`${g}.relation.cardinality \u4EC5\u5141\u8BB8 1:1\u3001N:1 \u6216 1:N`),!x.targetTable){e.push(`${g}.relation.targetTable \u4E0D\u80FD\u4E3A\u7A7A`);return}De(x.targetTable)===De(l)&&e.push(`${g} \u5173\u8054\u76EE\u6807 ${x.targetTable} \u4E0E\u5F53\u524D\u8868\u76F8\u540C\uFF1BJoinForm/TableChild \u7981\u6B62\u81EA\u5173\u8054`);let b=o.get(De(x.targetTable));if(!b){e.push(`${g}.relation.targetTable \u5F15\u7528\u672A\u5728 Manifest tables \u4E2D\u58F0\u660E\u7684\u8868 "${x.targetTable}"\uFF1B\u5B8C\u6574\u7CFB\u7EDF\u751F\u6210\u5FC5\u987B\u58F0\u660E\u76EE\u6807\u8868\u4EE5\u5B8C\u6210\u524D\u7F6E\u6821\u9A8C`);return}if(h==="joinform"){x.cardinality!=="1:1"&&x.cardinality!=="N:1"&&e.push(`${g} \u7684 JoinForm \u53EA\u5141\u8BB8 1:1 \u6216 N:1\uFF1B1:N \u660E\u7EC6\u5FC5\u987B\u6539\u7528 TableChild`),x.joinFieldName?p.has(De(x.joinFieldName))?De(x.joinFieldName)===De(y)&&e.push(`${g}.relation.joinFieldName \u4E0D\u80FD\u6307\u5411 JoinForm \u7EC4\u4EF6\u5B57\u6BB5\u81EA\u8EAB`):e.push(`${g}.relation.joinFieldName \u5F15\u7528\u5F53\u524D\u8868\u4E0D\u5B58\u5728\u7684\u5B57\u6BB5 "${x.joinFieldName}"`):e.push(`${g}.relation.joinFieldName \u4E0D\u80FD\u4E3A\u7A7A\uFF0C\u4E14\u5FC5\u987B\u6307\u5411\u5F53\u524D\u4E3B\u8868\u4E2D\u4FDD\u5B58\u76EE\u6807\u8BB0\u5F55 Id \u7684\u5B57\u6BB5`);return}x.cardinality!=="1:N"&&e.push(`${g} \u7684 TableChild \u53EA\u5141\u8BB8 1:N\uFF1B1:1/N:1 \u5E94\u4F7F\u7528 JoinForm`);let v=ie(b,"fields","Fields"),_=new Set(v.map(E=>De(S(E,"name","Name"))).filter(Boolean));if(x.childForeignKey?_.has(De(x.childForeignKey))||e.push(`${g}.relation.childForeignKey \u5F15\u7528\u5B50\u8868 ${x.targetTable} \u4E0D\u5B58\u5728\u7684\u5B57\u6BB5 "${x.childForeignKey}"`):e.push(`${g}.relation.childForeignKey \u4E0D\u80FD\u4E3A\u7A7A`),!x.childModule)e.push(`${g}.relation.childModule \u4E0D\u80FD\u4E3A\u7A7A`);else{let E=a.get(De(x.childModule));E?(De(VY(E))!==De(x.targetTable)&&e.push(`${g}.relation.childModule \u5FC5\u987B\u7ED1\u5B9A\u5B50\u8868 ${x.targetTable}`),(oe(E,"display","Display")!==0||oe(E,"appDisplay","AppDisplay")!==0||oe(E,"hasChild","HasChild")!==0)&&e.push(`${g}.relation.childModule \u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E display=0\u3001appDisplay=0\u3001hasChild=0`)):e.push(`${g}.relation.childModule \u5F15\u7528\u4E0D\u5B58\u5728\u7684\u6A21\u5757 "${x.childModule}"`)}let w=_.has("osclient")?["osclient",De(x.childForeignKey)]:[De(x.childForeignKey)],C=ie(b,"indexes","Indexes").some(E=>{let T=Ss(E,"columns","Columns").map(De);return w.every((A,I)=>T[I]===A)});if(x.childForeignKey&&!C){let E=_.has("osclient")?`OsClient, ${x.childForeignKey}`:x.childForeignKey;e.push(`${g} \u7684\u5B50\u8868 ${x.targetTable} \u5FC5\u987B\u58F0\u660E\u4EE5 (${E}) \u5F00\u5934\u7684\u7D22\u5F15`)}})}),{errors:e,warnings:r}}function HY(t,e,r,n){let i=De(S(t,"component","Component")),o=rw(t);if(!o||i!=="joinform"&&i!=="tablechild")throw new Error(`${e}.${S(t,"name","Name")} \u7F3A\u5C11\u6709\u6548 relation`);let a=r.get(De(o.targetTable));if(!a)throw new Error(`\u65E0\u6CD5\u89E3\u6790\u5173\u8054\u76EE\u6807\u8868 ${o.targetTable} \u7684\u5F53\u524D\u79DF\u6237 diy_table.Id`);let s=qY(Le(t,"config","Config"));if(i==="joinform")return{...s,JoinForm:{...H(s.JoinForm),TableId:a,TableName:o.targetTable,JoinFieldName:o.joinFieldName}};let c=n.get(De(o.childModule));if(!c)throw new Error(`\u65E0\u6CD5\u89E3\u6790\u9690\u85CF\u5B50\u8868\u6A21\u5757 ${o.childModule} \u7684\u5F53\u524D\u79DF\u6237 sys_menu.Id`);return{...s,TableChildTableId:a,TableChildSysMenuId:c,TableChildSysMenuName:o.childModule,TableChildFkFieldName:o.childForeignKey,TableChild:{...H(s.TableChild),PrimaryTableFieldName:o.primaryTableFieldName}}}function Y0(t){let e=String(t||"").trim().replace(/\\/gu,"/");if(!e)return"/";if(e.startsWith("/")||(e=`/${e}`),e=e.replace(/\/{2,}/gu,"/"),e.length>1&&(e=e.replace(/\/+$/gu,"")),!/^\/(?:[A-Za-z0-9][A-Za-z0-9_-]*(?:\/[A-Za-z0-9][A-Za-z0-9_-]*)*)?$/u.test(e)||e.includes(".."))throw new Error(`\u4E0D\u5408\u6CD5\uFF1A${t}`);return e}async function JY(t,e){let r=S(e,"openType","OpenType"),n=S(e,"microServiceKey","MicroServiceKey"),i=S(e,"microServiceRoutePath","MicroServiceRoutePath"),o=S(e,"microServiceId","MicroServiceId"),a=S(e,"microServicePageId","MicroServicePageId");if(!(["microservice","codeform"].includes(r.toLowerCase())||!!(oe(e,"isMicroiService","IsMicroiService")===1||n||i||o||a)))return;if(r.toLowerCase()==="codeform"&&!S(e,"diyTableId","DiyTableId","table","tableName","diyTableName","DiyTableName"))throw new Error("CodeForm \u83DC\u5355\u5FC5\u987B\u7ED1\u5B9A\u771F\u5B9E diy_table\uFF0C\u4F9B\u8868\u5355\u4EE3\u7801\u83B7\u53D6\u83DC\u5355\u4E0E\u8868\u6743\u9650\u4E0A\u4E0B\u6587");if(!n||!/^[A-Za-z0-9][A-Za-z0-9_-]{0,79}$/u.test(n))throw new Error(`MicroService \u83DC\u5355\u7F3A\u5C11\u5408\u6CD5\u7684 microServiceKey\uFF1A${n||"(empty)"}`);if(!i)throw new Error("MicroService \u83DC\u5355\u7F3A\u5C11 microServiceRoutePath");let c=Y0(i),l=await t.getMicroService(n);if(!l||l.Code!==1)throw new Error(`\u65E0\u6CD5\u89E3\u6790\u5FAE\u670D\u52A1 ${n}\uFF1A${l?.Msg||"\u63A5\u53E3\u65E0\u8FD4\u56DE"}`);let u=H(l.Data),p=H(u.Service),f=S(p,"Id","id"),m=S(p,"MsKey","MicroServiceKey","AppKey");if(!f||m.toLowerCase()!==n.toLowerCase())throw new Error(`\u5FAE\u670D\u52A1 ${n} \u7684\u8FD0\u884C\u5143\u6570\u636E\u4E0D\u5B8C\u6574\u6216\u4E1A\u52A1\u952E\u4E0D\u4E00\u81F4`);if(o&&o!==f)throw new Error(`MicroServiceId \u5DF2\u8FC7\u671F\uFF1AManifest=${o}\uFF0C\u5F53\u524D\u79DF\u6237=${f}`);let g=(Array.isArray(u.Pages)?u.Pages.map(H):[]).find(b=>{let v=S(b,"RoutePath","routePath","Path","path");if(!v)return!1;try{return Y0(v)===c}catch{return!1}}),y=g?S(g,"Id","id"):"";if(!y)throw new Error(`\u5FAE\u670D\u52A1 ${n} \u4E0D\u5B58\u5728\u53EF\u7528\u9875\u9762 ${c}`);if(a&&a!==y)throw new Error(`MicroServicePageId \u5DF2\u8FC7\u671F\uFF1AManifest=${a}\uFF0C\u5F53\u524D\u79DF\u6237=${y}`);let x=c==="/"?"":`/${c.slice(1).split("/").map(b=>encodeURIComponent(b)).join("/")}`;return{IsMicroiService:1,OpenType:r.toLowerCase()==="codeform"?"CodeForm":"MicroService",ComponentName:S(e,"componentName","ComponentName")||"MicroService",ComponentPath:S(e,"componentPath","ComponentPath")||"/micro-app/host",Url:S(e,"url","Url")||`/micro-app/${encodeURIComponent(n)}${x}`,MicroServiceId:f,MicroServicePageId:y,MicroServiceRoutePath:c,MicroServiceKey:n}}function v2(t){return dn({...t,Id:S(t,"Id","roleId","RoleId")||void 0,Name:S(t,"Name","name"),Level:oe(t,"Level","level"),Sort:oe(t,"Sort","sort"),Remark:S(t,"Remark","remark","description"),DeptIds:S(t,"DeptIds","deptIds"),BaseLimit:S(t,"BaseLimit","baseLimit")})}function x2(t){let e=S(t,"DataSourceType","dataSourceType")||"V8",r=e.trim().toUpperCase(),n=r.includes("SQL")?S(t,"SqlDataSource","sqlDataSource","sql"):r.includes("JSON")||e.includes("\u666E\u901A")?$l(t.JsonDataSource??t.jsonDataSource??t.NormalDataSource??t.normalDataSource??t.json):r.includes("API")?S(t,"ApiDataSource","apiDataSource"):S(t,"V8DataSource","v8DataSource"),i=dn({...t,Id:S(t,"Id","dataSourceId","DataSourceId")||void 0,DataSourceName:S(t,"DataSourceName","dataSourceName","name","Name"),DataSourceKey:S(t,"DataSourceKey","dataSourceKey"),DataSourceType:e,ApiV8Code:S(t,"ApiV8Code","apiV8Code","code")||n,TestParam:$l(t.TestParam??t.testParam),DataSourceRole:S(t,"DataSourceRole","dataSourceRole"),AllowAnonymous:oe(t,"AllowAnonymous","allowAnonymous"),IsEnable:oe(t,"IsEnable","isEnable")??1});for(let o of["SqlDataSource","sqlDataSource","sql","V8DataSource","v8DataSource","JsonDataSource","jsonDataSource","json","NormalDataSource","normalDataSource","ApiDataSource","apiDataSource"])delete i[o];return i}function w2(t){let e=Yo(t.PageObj??t.pageObj);if(!e.ok||!e.json)throw new Error(`printTemplates.${S(t,"Title","title")||"(untitled)"} PageObj invalid: ${e.errors.join("; ")}`);let r=Qo(t.PrintObj??t.printObj);if(!r.ok||!r.json)throw new Error(`printTemplates.${S(t,"Title","title")||"(untitled)"} PrintObj invalid: ${r.errors.join("; ")}`);return dn({...t,Id:S(t,"Id","printId","PrintId")||void 0,Title:S(t,"Title","title"),Number:S(t,"Number","number"),Desc:S(t,"Desc","desc","description"),DataApi:S(t,"DataApi","dataApi"),PageObj:e.json,PrintObj:r.json})}function _2(t){return dn({...t,Id:S(t,"Id","jobId","JobId")||void 0,JobName:S(t,"JobName","jobName","name","Name"),CronExpression:S(t,"CronExpression","cronExpression","cron"),JobType:S(t,"JobType","jobType")||"1",ApiEngineKey:S(t,"ApiEngineKey","apiEngineKey"),JobParam:$l(t.JobParam??t.jobParam??t.params),JobDesc:S(t,"JobDesc","jobDesc","description"),CronDesc:S(t,"CronDesc","cronDesc"),DllName:S(t,"DllName","dllName"),JobPath:S(t,"JobPath","jobPath")})}function D2(t){let e=De(S(t,"component","Component"));return e==="joinform"||e==="tablechild"}function S2(t,e,r,n,i){let o=H(e.configSource??e.ConfigSource),a=S(o,"sourceType")?R2(S(o,"sourceType"),o):void 0;return dn({TableId:r,Name:S(e,"name","Name"),Label:S(e,"label","Label"),Type:S(e,"type","Type")||(D2(e)?"mediumtext":""),Component:S(e,"component","Component"),Visible:oe(e,"visible","Visible")??1,AppVisible:oe(e,"appVisible","AppVisible")??1,Tab:S(e,"tab","Tab")||n.fieldTabs.get(S(e,"name","Name")),TableWidth:oe(e,"tableWidth","TableWidth")??Mf(e),Sort:oe(e,"sort","Sort"),Readonly:oe(e,"readonly","Readonly"),NotEmpty:oe(e,"notEmpty","NotEmpty"),Unique:oe(e,"unique","Unique"),DefaultValue:S(e,"defaultValue","DefaultValue"),Placeholder:S(e,"placeholder","Placeholder"),FormWidth:oe(e,"formWidth","FormWidth"),Data:a?.data??S(e,"data","Data"),Config:i!==void 0?JSON.stringify(i):a?JSON.stringify(a.config):$l(e.config??e.Config),Description:S(e,"description","Description"),Encrypt:oe(e,"encrypt","Encrypt"),InTableEdit:oe(e,"inTableEdit","InTableEdit")})}function ZY(t){return{osClient:t,workflow:["Call microi_get_db_schema first to inspect existing tables.","Call microi_get_manifest_schema to draft a manifest from the user requirement.","Call microi_plan_system with the manifest and fix all errors.","Call microi_generate_system with dryRun=true.",`Call microi_generate_system with dryRun=false and confirmExecution="${t||"EXECUTE"}" only after the user confirms writes.`,"Call microi_validate_system after generation if you need an independent validation pass."],manifestShape:{name:"System name",roles:[{name:"Admin",level:999}],tables:[{name:"Biz_Order",description:"Order main table",v8Limit:!1,readPrimary:null,tabs:[{Id:"basic",Name:"Basic Info",Sort:10},{Id:"business",Name:"Business Info",Sort:20}],formBanner:{enabled:!0,titleField:"OrderNo",subtitleField:"CustomerName",imageField:"",icon:"far fa-file-alt",backgroundField:"",tagFields:[{Field:"Status",Label:"Status"}],metrics:[{Field:"Amount",Label:"Order Amount",Prefix:"\xA5",Icon:"fas fa-coins"},{Key:"Pending",Label:"Pending",ApiEngineKey:"biz_order_metrics",ValuePath:"Data.Pending",RefreshSeconds:30}]},fields:[{name:"OrderNo",label:"Order No",type:"varchar(50)",component:"AutoNumber",tab:"basic",configSource:{sourceType:"AutoNumber",prefix:"ORD",length:6},notEmpty:1,unique:1,tableWidth:160,sort:10},{name:"CustomerName",label:"Customer",type:"varchar(100)",component:"Text",tab:"basic",notEmpty:1,tableWidth:160,sort:20},{name:"OwnerName",label:"Owner",type:"varchar(100)",component:"Text",tab:"basic",tableWidth:150,sort:30},{name:"Amount",label:"Order Amount",type:"decimal(18,2)",component:"NumberText",tab:"business",tableWidth:140,sort:40},{name:"Status",label:"Status",type:"varchar(50)",component:"Select",tab:"business",configSource:{sourceType:"KeyValue",items:[{Key:"Draft",Value:"Draft"},{Key:"Submitted",Value:"Submitted"}]},tableWidth:130,sort:50}],indexes:[{name:"uk_biz_order_no",columns:["OrderNo"],unique:!0,purpose:"\u72EC\u7ACB\u79DF\u6237\u5E93\u5185\u8BA2\u5355\u53F7\u552F\u4E00\uFF1B\u5171\u4EAB\u8868\u987B\u663E\u5F0F\u58F0\u660E\u5E76\u6821\u9A8C\u79DF\u6237\u7269\u7406\u5217"},{name:"ix_biz_order_status_time",columns:["Status","CreateTime"],unique:!1,purpose:"\u6309\u72B6\u6001\u53CA\u521B\u5EFA\u65F6\u95F4\u67E5\u8BE2"}]}],engines:[{apiEngineKey:"biz_order_submit",apiName:"Submit order",category:"Biz_Order",v8Limit:!1,code:"return { Code: 1, Data: V8.Param };"},{apiEngineKey:"biz_order_metrics",apiName:"Order metrics",category:"Biz_Order",code:["var result = V8.FormEngine.GetTableData('Biz_Order', {"," _Where: [['Status', '=', 'Submitted']],"," _SelectFields: ['Id'],"," _PageIndex: 1,"," _PageSize: 1","});","if (result.Code !== 1) return result;","var count = result.DataCount || 0;","return { Code: 1, Data: { Value: count, Pending: count } };"].join(`
136
136
  `)}],events:[{formEngineKey:"Biz_Order",eventType:"SubmitBeforeServerV8",code:"if (!V8.Form.OrderNo) return { Code: 0, Msg: 'OrderNo required' };"}],modules:[{name:"Orders",table:"Biz_Order",icon:"Document",listFields:["OrderNo","CustomerName","OwnerName","Amount","Status","CreateTime"],searchFields:["OrderNo","CustomerName","Status"],sortFields:["CreateTime"],defaultOrderBy:[{field:"CreateTime",type:"DESC"}],menuBadgeEnabled:1,menuBadgeApiEngineKey:"biz_order_metrics",enableViewSchema:1,viewSchemaVersion:"1.0",viewConfigVersion:1,viewSchema:{Views:[{Scene:"List",Device:"PC",Priority:100,Layout:{Hero:{Title:"Orders",Description:"Track order value, pending work and current filtered results",Metrics:[{Key:"pending",Label:"Pending",ApiEngineKey:"biz_order_metrics",ValuePath:"Data.Pending",Icon:"fas fa-clock",Tone:"warning"},{Key:"amount",Label:"Order Amount",Source:"Field",Field:"Amount",Icon:"fas fa-coins",Tone:"success"},{Key:"records",Label:"Filtered Results",Source:"DataCount",Icon:"fas fa-layer-group",Tone:"info"}]},List:{Density:"Comfortable",Columns:[{Field:"OrderNo",Lines:[{Name:"CustomerName",Label:"Customer",ShowLabel:!0,Tone:"info"}],TrailingFields:[{Name:"Status",DisplayStyle:"Tag"},{Name:"Amount",Icon:"fas fa-coins",Tone:"warning"}],RequiredFields:["CustomerName","Status","Amount"],MinWidth:380}]}}},{Scene:"Detail",Device:"All",Priority:100,Layout:{Hero:{Title:"Order Detail",TitleField:"OrderNo",StatusField:"Status"},Blocks:[{Type:"ResponsiveSection",Title:"Order Info",Fields:["OrderNo","CustomerName","Status"]}]}},{Scene:"Card",Device:"Mobile",Priority:100,Layout:{Card:{AvatarTextField:"CustomerName",TitleField:"OrderNo",SubtitleFields:["CustomerName"],StatusFields:[{Name:"Status",DisplayStyle:"Tag"}],TopFields:[],RightFields:[{Name:"Amount",Format:"currency",Tone:"danger"}],Fields:[{Name:"OwnerName",Label:"Owner"}],MetaFields:[{Name:"CreateTime",Label:"Created At",Format:"datetime"}],BottomFields:[]}}}]},moreBtns:[{Name:"Submit",BtnStyle:"primary",V8CodeShow:"V8.Result=V8.Form.Status=='Draft';",V8Code:"var r=await V8.ApiEngine.Run({ApiEngineKey:'biz_order_submit',Id:V8.Form.Id});V8.Result=r;"}]}],permissions:[{roleId:"admin",moduleNames:["Orders"]}],dataSources:[],pages:[{title:"Operations Dashboard",number:"page_operations_dashboard",routePath:"/page/operations-dashboard",JsonObj:{formConfig:{gutter:0,mask:!1,drag:!1,hover:!1,shadow:!0,link:!0,dark:!1,dynamicStyle:{padding:"12px 0 0 0",backgroundColor:"#f3f4f6",opacity:1}},wrapperList:[{type:"pannel",label:"Card",wrapperOption:{span:24,height:180,titleOption:{hidden:!0,title:"Core Metrics"}},widgetList:[]}]}}],printTemplates:[{title:"Business Print Template",number:"print_business_template",PageObj:{panels:[{index:0,name:"A4 Template",paperType:"A4",height:297,width:210,paperHeader:0,paperFooter:841.8897637795277,printElements:[]}]},PrintObj:{}}],workflows:[{FlowDesign:{FlowName:"Order approval",TableId:"<Biz_Order table id or tableName-resolved id>",IsEnable:1},Nodes:[{Id:"start",NodeName:"\u53D1\u8D77\u4EBA",NodeType:"Start",AllowSelectUsers:0,PositionLeft:"80px",PositionTop:"160px",LineValueV8:""},{Id:"manager",NodeName:"\u90E8\u95E8\u7ECF\u7406\u5BA1\u6279",NodeType:"Approve",Roles:[{Id:"<\u4ECE microi_list_roles \u67E5\u8BE2>",Name:"\u90E8\u95E8\u7ECF\u7406"}],AllowSelectUsers:0,PositionLeft:"320px",PositionTop:"160px"},{Id:"end",NodeName:"\u7ED3\u675F",NodeType:"AutoEnd",PositionLeft:"560px",PositionTop:"160px"}],Lines:[{Id:"line_start_manager",FromNodeId:"start",ToNodeId:"manager",LineName:"\u53D1\u8D77\u4EBA \u5230 \u90E8\u95E8\u7ECF\u7406\u5BA1\u6279",LineValue:""},{Id:"line_manager_end",FromNodeId:"manager",ToNodeId:"end",LineName:"\u90E8\u95E8\u7ECF\u7406\u5BA1\u6279 \u5230 \u7ED3\u675F",LineValue:""}]}],jobs:[]},workflowModuleExample:{name:"\u8BA2\u5355\u5BA1\u6279",table:"Biz_Order",openType:"WorkFlow",flowName:"Order approval",display:1,appDisplay:1},relationExamples:{joinForm:{parentStorageField:{name:"CustomerId",label:"Customer Id",type:"varchar(50)",component:"Text",visible:0,appVisible:0},displayField:{name:"CustomerProfile",label:"Customer Profile",type:"mediumtext",component:"JoinForm",formWidth:24,relation:{cardinality:"N:1",targetTable:"Biz_Customer",joinFieldName:"CustomerId"}}},tableChild:{parentField:{name:"OrderItems",label:"Order Items",type:"mediumtext",component:"TableChild",formWidth:24,relation:{cardinality:"1:N",targetTable:"Biz_OrderItem",childForeignKey:"OrderId",childModule:"Order Items (hidden)",primaryTableFieldName:"Id"}},childForeignKeyField:{name:"OrderId",label:"Order Id",type:"varchar(50)",component:"Text",visible:0,appVisible:0},childIndex:{name:"ix_biz_orderitem_order",columns:["OrderId"],unique:!1},hiddenChildModule:{name:"Order Items (hidden)",table:"Biz_OrderItem",display:0,appDisplay:0,hasChild:0}}},naturalFieldKeys:{tables:{tabs:"diy_table.Tabs form groups. When omitted and the table has more than 12 business fields, generator creates Basic/Contact/Business/Attachment/Extra tabs and assigns empty field tab values.",formBanner:"diy_table \u7684 Banner \u8BED\u4E49\u914D\u7F6E\uFF0C\u4F7F\u7528 enabled/titleField/subtitleField/imageField/icon/backgroundField/tagFields/metrics\uFF0C\u4E0D\u5199 sys_menu\u3002\u7701\u7565\u65F6\u6309\u771F\u5B9E\u7C7B\u578B\u63A8\u65AD\u4E1A\u52A1\u6807\u9898\u3001\u5BA2\u6237\u6216\u9879\u76EE\u526F\u6807\u9898\u3001\u9996\u4E2A\u56FE\u7247\u3001\u6700\u591A3\u4E2A\u6807\u7B7E\u548C3\u4E2A\u4E1A\u52A1\u6307\u6807\u3002\u5B57\u6BB5\u7ED1\u5B9A\u663E\u5F0F\u7A7A\u5B57\u7B26\u4E32\u8868\u793A\u4E0D\u7ED1\u5B9A\uFF0C\u7701\u7565/null \u624D\u5141\u8BB8\u63A8\u65AD\uFF1B\u7A7A\u5B57\u7B26\u4E32\u4F18\u5148\u4E8E\u65E7\u5927\u5C0F\u5199\u522B\u540D\u3002Id/\u6392\u5E8F/\u542F\u7528/\u72B6\u6001/\u7248\u672C/\u672C\u9875\u6570\u91CF\u4E0D\u5F97\u5145\u5F53\u6307\u6807\u3002TableChild \u53EF\u7701\u7565 metrics\uFF0C\u7531\u8FD0\u884C\u65F6\u6309\u5B8C\u6574\u6388\u6743\u5B50\u8868\u7EDF\u8BA1\uFF1B\u663E\u5F0F [] \u5173\u95ED\u63A8\u65AD\u3002\u8DE8\u8868\u6307\u6807\u652F\u6301 ApiEngineKey + ValuePath + ParamMap + RefreshSeconds\u3002",column:"Form column count. Omit to use 2 columns for generated systems unless the user asks for a single-column form.",formOpenType:"Default Dialog. Use Drawer only for extremely large forms (roughly 36+ business fields, 2+ child tables, or similarly heavy content).",formOpenWidth:"Default 80% for generated Dialog forms. Preserve an explicit business-specific width.",indexes:"\u7269\u7406\u7D22\u5F15\u6309columns\u987A\u5E8F\u53CAunique\u58F0\u660E\uFF0C\u901A\u8FC7microi_create_table_index\u6216Manifest\u521B\u5EFA\u3002\u72EC\u7ACB\u79DF\u6237\u5E93\u4E0D\u81EA\u52A8\u521B\u5EFAOsClient\u5217\uFF0C\u5B50\u8868\u7D22\u5F15\u4EE5\u771F\u5B9E\u5916\u952E\u5F00\u5934\uFF1B\u53EA\u6709\u663E\u5F0F\u58F0\u660EOsClient\u7269\u7406\u5217\u7684\u5171\u4EAB\u8868\u624D\u4EE5OsClient+\u5916\u952E\u5F00\u5934\u3002\u56FA\u5B9A\u5217\u4E3AId/CreateTime/UpdateTime/UserId/UserName/IsDeleted\uFF0CTableChild\u4E0E\u5E03\u5C40\u63A7\u4EF6\u4E0D\u80FD\u7D22\u5F15\u3002",v8Limit:"Default false. Missing/null/false means no per-execution Jint budgets; true enables timeout, statement, recursion and allocation limits for this table's backend V8 events. Legacy v8Unlimited is accepted only as an inverted compatibility alias.",readPrimary:"null/0 keeps the existing read replica default; 1 routes native rows/count/sum/tree/export to this table database writer. Omit to preserve existing metadata. Explicit DbTrans remains unchanged and may retain an older RR snapshot. Requires the backend capability and official form-engine ReadPrimary field."},engines:{v8Limit:"Default false. false means no Jint per-execution budget; true applies this engine's configured timeout, statement, allocation and recursion limits. Omit to preserve an existing engine setting during upsert."},fields:{component:"Use the real Microi component name. Available controls include Text, Textarea, NumberText, DateTime, Select, MultipleSelect, Radio, Checkbox, Switch, Rate, Progress, Slider, ColorPicker, AutoNumber, Divider, CollapseGroup, Tabs, Alert, StaticText, Html, RichText, CodeEditor, JsonTable, ImgUpload, FileUpload, Autocomplete, TagInput, Transfer, Cascader, Address, Department, SelectTree, TreeCheckbox, OpenTable, JoinTable, JoinForm, TableChild, Map, MapArea, Qrcode, FontAwesome, DevComponent.",tab:"Assign a field to a diy_table.Tabs Id/Name. For many fields, prefer table-level Tabs; use CollapseGroup or field component Tabs only when an in-page section needs collapsible or nested grouping.",relation:'Required for JoinForm/TableChild. Use {cardinality:"1:1"|"N:1",targetTable,joinFieldName} for JoinForm, or {cardinality:"1:N",targetTable,childForeignKey,childModule,primaryTableFieldName:"Id"} for TableChild. Names are resolved to tenant ids only after resources exist; raw ids are not portable.'},modules:{workflow:"\u6D41\u7A0B\u6A21\u5757\u8BBE\u7F6E openType=WorkFlow\uFF0C\u5E76\u7528 flowName \u5F15\u7528\u540C\u4E00 Manifest \u5185\u5DF2\u542F\u7528\u6D41\u7A0B\uFF1B\u751F\u6210\u540E\u81EA\u52A8\u5199\u5165 sys_menu.FlowDesignId\u3002\u5F15\u7528\u73B0\u6709\u6D41\u7A0B\u65F6\u4F20\u7CBE\u786E flowDesignId\u3002\u6A21\u5757 table/diyTableId \u5FC5\u987B\u4E0E wf_flowdesign.TableId \u76F8\u540C\u3002",table:"Bind by table name. The generator resolves the table Id after create/refresh schema.",hasChild:"For a hidden TableChild carrier module set display=0, appDisplay=0 and hasChild=0 explicitly.",microServiceKey:"Portable sys_microiservice.MsKey reference for openType=MicroService or CodeForm. CodeForm must also bind a diyTableId/table. The generator resolves the tenant-specific MicroServiceId before any writes.",microServiceRoutePath:"Portable sys_microiservice_page.RoutePath reference such as /overview. The generator resolves and verifies MicroServicePageId before any writes.",listFields:"Field names/labels/ids for grid columns. Produces TableDiyFieldIds and SelectFields. When omitted, generator chooses title/no/status/person/amount/time fields.",tableHeaders:'Optional multilevel grid header groups, for example [{Label:"\u4EBA\u6570\uFF08\u4EBA\uFF09",Fields:["Total","Male","Female"]}]. Fields must be visible, consecutive listFields. Nested groups use Children. Stored in sys_menu.TableHeaders; omitted keeps one header row.',hideTableBanner:"Set to 1 to hide the module grid top Banner and skip its metric API calls; omitted/0 keeps the Banner.",hideFormBanner:"Set to 1 to hide the module form top Banner and skip its metric API calls; omitted/0 keeps the Banner.",searchFields:"Field names/labels/ids for search controls. Produces SearchFieldIds object array. When omitted, generator chooses title/no/status/type/category/person/time fields.",sortFields:"Field names/labels/ids for sortable fields. Produces SortFieldIds. When omitted, generator chooses date/time, Sort and numeric business fields.",hiddenFields:"Field names/labels/ids to hide. Produces NotShowFields. When omitted, generator hides Id-like fields, foreign keys, system fields and layout/large controls.",editableFields:"Field names/labels/ids for in-table editing. Produces InTableEditFields.",mobileFields:"Field names/labels/ids for mobile card list. Produces MobileListFields. When omitted, generator picks 3-4 compact title/status/summary fields.",cardTitleFields:"Field names/labels/ids for card title tags. Produces CardTitleTagFields. When omitted, generator picks status/type/category fields.",cardBottomFields:"Field names/labels/ids for card bottom tags. Produces CardBottomTagFields. When omitted, generator picks amount/count/date fields.",statisticsFields:"Field names/labels/ids for table footer statistics. When omitted, generator sums amount/price/count/point/balance numeric fields.",menuBadgeEnabled:"Set to 1 for important menus that need a sidebar statistic badge.",menuBadgeApiEngineKey:"API engine used by the sidebar statistic badge. Return {Code:1,Data:{Value:number}}; keep the query tenant-scoped and inexpensive.",enableViewSchema:"Set to 1 only when Detail/Edit should use custom form views. Configured List/Card presentation is always applied and does not depend on this switch.",viewSchemaVersion:"Optional protocol version. Blank or omitted values resolve to 1.0.",viewConfigVersion:"Optional monotonic configuration version. Omitted values resolve to 1 and later changes increment it.",viewSchema:"Versioned Detail/Edit/List/Card layouts for PC/Mobile/All. Every visible bound module gets generated List/Card defaults when omitted, but AI must still business-tune Hero metrics, composite columns and mobile regions. Layout.List supports multi-line columns and trailing fields; Layout.Card supports top/right/body/meta/bottom field groups. The full declarative object is preserved. Use ActionSchema only; never place arbitrary client V8Code in mobile actions."}},rules:["Use table and field names in manifests; do not ask the user for diy_field ids.","Every generated business table must have a useful compact theme-colored dark-gradient form Banner. Put its configuration in tables[].formBanner/diy_table, not in modules/sys_menu. Prefer a business number/name title, a customer/project subtitle, real option tags and at most 3 business-semantic current-record or authorized full-child metrics; exclude technical numbers and never fabricate statistics.","JoinForm\u53EA\u7528\u4E8E1:1/N:1\uFF0C\u901A\u8FC7\u771F\u5B9E\u7236\u8868Id\u5B57\u6BB5\u5F15\u7528\u4E0D\u540C\u8868\u30021:N\u4F7F\u7528TableChild\uFF0C\u58F0\u660E\u5B50\u8868\u3001\u771F\u5B9E\u5916\u952E\u3001\u9690\u85CF\u5B50\u83DC\u5355\u53CA\u5916\u952E\u7D22\u5F15\uFF1B\u5171\u4EAB\u8868\u663E\u5F0F\u542BOsClient\u7269\u7406\u5217\u65F6\u6539\u4E3A(OsClient,foreignKey)\u7D22\u5F15\u3002\u4E0D\u5F97\u865A\u6784\u79DF\u6237\u5217\u6216\u4F20\u672A\u89E3\u6790\u7684Config\u3002","Put business logic in API engines and call them from menu button V8Code.",'For workflow manifests, include exactly one start node, at least one end node, valid FromNodeId/ToNodeId lines, and stable LineName values in the form "{from node} \u5230 {to node}".',"For multi-route workflow nodes, generate LineValueV8 with the visual condition marker and prefer assigning V8.NextNodeId; then call microi_check_workflow_package and microi_test_workflow_condition before microi_save_workflow_package.","Use parameterized V8.Db SQL or V8.FormEngine CRUD in engine/event code.","Interface engines use positive v8Limit semantics: false/default means no Jint per-execution budget; true enables the configured limits. Process resident-memory, cancellation, concurrency, permissions and database protections remain active in both modes.","Leave diy_field.FormWidth null/omitted for normal fields; use formWidth: 24 only for full-row controls such as CodeEditor, Textarea, RichText, upload, TableChild, map/layout/custom components.","Do not leave sys_menu list configuration empty. If the user does not specify it, rely on the generator defaults for NotShowFields, SearchFieldIds, SortFieldIds, StatisticsFields, MobileListFields, CardTitleTagFields and CardBottomTagFields.","Every visible bound business module must have a compact Hero title, a real business subtitle and 2-4 meaningful dynamic metrics. Prefer pending/overdue/amount/capacity/risk aggregates; DataCount/PageCount are truthful fallback only. Never generate random or fabricated statistics.","Give every list field a semantic TableWidth. Build at least one PC composite column with a reasonable MinWidth, remove its Lines/TrailingFields from standalone columns, and configure mobile title/subtitle/top/status/right/body/meta/bottom regions without repeating the same field.","Use sidebar menu badges only for a small set of actionable important menus. Add PageTabs and More/Page/Form/Batch/Export button badges when their counts help the workflow; batch one statistics API and never issue N+1 requests.","EnableViewSchema controls Detail/Edit custom forms only. List/Card presentation and generated Hero/metrics remain active when it is 0.","Do not use diy_table.DiyConfig, diy_field.DiyConfig or sys_menu.DiyConfig for new configuration. Add dedicated physical columns and expose them through DIY metadata.","For forms with many fields, use diy_table.Tabs first. Use CollapseGroup for optional/secondary sections and field component Tabs for nested in-page grouping.","Open generated forms in an 80% Dialog by default. Use Drawer only for extremely large forms with many fields, multiple TableChild controls, or comparable heavy content; never make Drawer the blanket module default.","Use dryRun=true until the user explicitly asks to write.","For Page Engine pages, save only the JsonObj layer to mic_page.JsonObj: {formConfig, wrapperList}. Do not wrap it in formData.","Page Engine defaults: formConfig.themeMode=system, density=compact, wrapperOption.heightMode=content; reserve fixed only for explicit fixed canvases. Use platform colour variables and statistic widgetParams[24].value=summary/detail for compact reference dashboards. Verify light/dark visuals and real data separately.","For Print Engine templates, PageObj must be a hiprint object with panels[].printElements; PrintObj is sample/runtime data.","For natural-language UI or print design, prefer microi_build_page_design or microi_build_print_template_design, then save after confirmation."]}}function F2(t,e,r){let n=r.osClient,i=n||"EXECUTE";t.tool("microi_get_manifest_schema","Return the recommended full-system manifest schema for natural-language Microi generation, including field-name based module configuration.",{},async()=>W(JSON.stringify(ZY(n),null,2))),t.tool("microi_validate_menu_buttons","Validate and normalize sys_menu button/tab JSON arrays (MoreBtns/FormBtns/BatchSelectMoreBtns/PageTabs/ExportMoreBtns/PageBtns). Returns canonical JSON strings with generated Id/Sort/default visibility.",{moreBtns:d.unknown().optional(),formBtns:d.unknown().optional(),batchSelectMoreBtns:d.unknown().optional(),pageTabs:d.unknown().optional(),exportMoreBtns:d.unknown().optional(),pageBtns:d.unknown().optional()},async s=>{let c=ks(s);return W(JSON.stringify({ok:c.errors.length===0,...c},null,2),c.errors.length>0)}),t.tool("microi_build_field_config",`Build and validate Microi diy_field Data/Config JSON for option controls, SQL/APIEngine/DataSource sources, JoinForm, AutoNumber and DateTime. OsClient: ${n}`,{sourceType:d.enum(["Data","KeyValue","Sql","ApiEngine","DataSource","AutoNumber","JoinForm","DateTime","FileUpload"]).describe("Config source type. FileUpload \u7684 options \u652F\u6301 EnableRolePermission\u3001HideUnauthorizedFiles\u3001ShowUnauthorizedFileName\u3001DisableRoleInheritance\uFF0C\u5747\u4E3A boolean\uFF0C\u9ED8\u8BA4 false\uFF1BConfigurableRoleIds \u662F\u6700\u591A 100 \u4E2A\u771F\u5B9E\u89D2\u8272 Id \u7684\u6570\u7EC4\uFF0C\u9ED8\u8BA4 [] \u5141\u8BB8\u6240\u6709\u89D2\u8272\uFF0C\u975E\u7A7A\u65F6\u4EC5\u53EF\u65B0\u589E\u5176\u4E2D\u89D2\u8272\u7684\u9644\u4EF6\u6388\u6743\u3002\u542F\u7528\u89D2\u8272\u6743\u9650\u81EA\u52A8 Limit=true\u3002"),options:tr.optional().describe("Source options, such as data/options, sql, apiEngineKey, dataSourceId, tableId, prefix, length")},async({sourceType:s,options:c})=>{let l=R2(s,c||{});return W(JSON.stringify({ok:l.warnings.length===0,...l,configJson:JSON.stringify(l.config)},null,2))}),t.tool("microi_plan_system","Create a dry-run execution plan for a full low-code system manifest. This performs local structural validation only and does not write to Microi.",{manifest:tr.describe("System manifest with tables, engines, modules, permissions, pages, dataSources, printTemplates, workflows, jobs")},async({manifest:s})=>{let c=q0(s);return W(JSON.stringify({ok:c.errors.length===0,dryRun:!0,...c},null,2),c.errors.length>0)}),t.tool("microi_check_workflow_package",'\u4FDD\u5B58\u524D\u68C0\u67E5 wf_flowdesign + wf_node + wf_line \u7684\u62D3\u6251\u3001\u8282\u70B9\u7C7B\u578B\u3001Id\u3001\u8FDE\u7EBF\u3001\u5F00\u59CB/\u7ED3\u675F\u8282\u70B9\u53CA\u591A\u8DEF\u7EBF\u914D\u7F6E\u3002\u53EA\u6709 FlowDesign.IsEnable \u663E\u5F0F\u4E3A 0 \u6216 "0" \u7684\u7981\u7528\u5B89\u88C5\u6BCD\u7248\u5141\u8BB8\u4EBA\u5DE5\u8282\u70B9\u7A7A\u7ED1\u5B9A\uFF1B\u542F\u7528\u6216\u7701\u7565\u4ECD\u8981\u6C42\u4EBA\u5458\u7B56\u7565\u3002\u4EFB\u4F55\u975E\u7A7A\u7ED1\u5B9A\u5FC5\u987B\u4E3A Id/Name \u5BF9\u8C61\uFF0C\u4FDD\u5B58\u65F6\u7EE7\u7EED\u56DE\u8BFB\u5F53\u524D\u79DF\u6237\u771F\u5B9E\u5F15\u7528\u3002',{workflow:tr.describe("Workflow package with FlowDesign, Nodes and Lines")},async({workflow:s})=>{let c=W0(s);return W(JSON.stringify(c,null,2),!c.ok)}),t.tool("microi_test_workflow_condition","Test a workflow LineValueV8 generated by the visual condition designer against sample formData. For safety this only evaluates Microi visual-condition marker JSON, not arbitrary hand-written V8.",{workflow:tr.optional().describe("Optional workflow package; when provided the tool reads the selected node LineValueV8"),nodeId:d.string().optional().describe("Node Id whose LineValueV8 should be tested. If omitted, uses the start node or first node."),lineValueV8Code:d.string().optional().describe("Direct LineValueV8 JavaScript code containing MICROI_WF_LINE_CONDITION_JSON marker"),formData:tr.optional().describe("Sample business form data used for rule evaluation")},async s=>W(JSON.stringify(MY(s),null,2))),t.tool("microi_validate_system",`Validate that a generated low-code system exists on Microi server after generation. OsClient: ${n}`,{manifest:tr.describe("The same manifest used by microi_generate_system")},async({manifest:s})=>{try{let c=q0(s);if(c.errors.length>0)return W(JSON.stringify({ok:!1,failedAt:"manifestPreflight",errors:c.errors,warnings:c.warnings},null,2),!0);let l=await b2(e,s);return ht("Low-Code System Validation",l)}catch(c){return W(`Error: ${c instanceof Error?c.message:String(c)}`,!0)}}),t.tool("microi_generate_system",`Generate a complete Microi low-code system from a manifest. Supports dryRun execution plans and post-generation validation. Writes require confirmExecution="${i}". OsClient: ${n}`,{manifest:tr.describe("System manifest with tables, fields, dataSources, engines, events, modules, permissions, pages, printTemplates, workflows and jobs"),dryRun:d.boolean().optional().describe("Default true. When true, only returns an execution plan."),confirmExecution:d.string().optional().describe(`Required when dryRun=false. Must equal "${i}".`)},async({manifest:s,dryRun:c=!0,confirmExecution:l})=>{let u=q0(s);if(u.errors.length>0)return W(JSON.stringify({ok:!1,...u},null,2),!0);if(c)return W(JSON.stringify({ok:!0,dryRun:!0,...u},null,2));if(l!==i)return W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u91CD\u65B0\u8C03\u7528\u5E76\u4F20 confirmExecution="${i}"\u3002
137
137
 
138
138
  ${JSON.stringify({plan:u.plan,warnings:u.warnings},null,2)}`,!0);let p=[],f=new Map,m=new Map,h=new Map,g=new Map,y=eY(),x=ie(s,"modules","Modules"),b=[];try{for(let E=0;E<x.length;E+=1)try{b[E]=await JY(e,x[E])}catch(T){return W(JSON.stringify({ok:!1,failedAt:"resolveMicroServiceModule",module:S(x[E],"name","Name"),error:T instanceof Error?T.message:String(T),results:p},null,2),!0)}await qr(e,"microi_generate_system:start",S(s,"name","Name")||"manifest",s);for(let E of ie(s,"roles","Roles")){let T=v2(E),A=await e.saveRole(T),I=S(T,"Name");if(p.push({step:"saveRole",roleName:I,response:A}),A.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"saveRole",role:T,response:A,results:p},null,2),!0);let R=S(H(A.Data),"Id","RoleId");I&&R&&h.set(I.toLowerCase(),R)}let v=ie(s,"tables","Tables"),_=[];for(let E of v){let T=S(E,"name","Name"),A=K0(E),I=FY(E),R=await e.createTable(T,S(E,"description","Description"),{Tabs:$l(E.tabs??E.Tabs??A.tabs),IsTree:oe(E,"isTree","IsTree"),ReadPrimary:Le(E,"readPrimary","ReadPrimary"),Column:oe(E,"column","Column")??A.column??2,FormOpenType:I.type,FormOpenWidth:I.width,V8Limit:Ol(E)===void 0?void 0:Ol(E)?1:0});if(p.push({step:"createTable",tableName:T,response:R}),R.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"createTable",tableName:T,response:R,results:p},null,2),!0);let F=S(H(R.Data),"TableId","Id");if(!F)return W(JSON.stringify({ok:!1,failedAt:"resolveCreatedTableId",tableName:T,response:R,results:p},null,2),!0);f.set(T.toLowerCase(),F)}for(let E of v){let T=S(E,"name","Name"),A=f.get(T.toLowerCase())||"",I=K0(E);for(let z of ie(E,"fields","Fields")){if(D2(z)){_.push({table:E,field:z,tableId:A,tableName:T,tableLayout:I});continue}let j=S2(E,z,A,I),K=await e.addField(j);if(p.push({step:"addField",tableName:T,fieldName:S(z,"name","Name"),response:K}),K.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"addField",tableName:T,field:z,response:K,results:p},null,2),!0);let ee=S(H(K.Data),"FieldId","Id"),_e=S(j,"Name");ee&&_e&&T2(y,{id:ee,name:_e,label:S(j,"Label")||_e,tableId:A,tableName:T,tableDescription:S(E,"description","Description")||T,component:S(j,"Component")||"Text",type:S(j,"Type")||"varchar(255)"})}for(let z of ie(E,"indexes","Indexes")){let j=Ss(z,"columns","Columns"),K=S(z,"name","Name"),ee=await e.createTableIndex({TableName:T,IndexName:K||void 0,Columns:j,Unique:Zr(z,"unique","Unique")??!1});if(p.push({step:"createTableIndex",tableName:T,indexName:K||j.join("_"),response:ee}),ee.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"createTableIndex",tableName:T,index:z,response:ee,results:p},null,2),!0)}let R=Dl(E),F=await e.updateTable({Id:A,...R});if(p.push({step:"configureFormBanner",tableName:T,banner:R,response:F}),F.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"configureFormBanner",tableName:T,banner:R,response:F,results:p},null,2),!0)}let w=await e.getDbSchema();p.push({step:"refreshDbSchemaBeforeModules",response:{Code:w.Code,Msg:w.Msg,Summary:H(H(w.Data).Summary)}}),w.Code===1?l2(y,w.Data,f):u.warnings.push(`Could not refresh schema before module field resolution: ${w.Msg||w.Code}`);for(let E of ie(s,"dataSources","DataSources")){let T=x2(E),A=await e.saveDataSource(T);if(p.push({step:"saveDataSource",key:S(T,"DataSourceKey"),response:A}),A.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"saveDataSource",dataSource:T,response:A,results:p},null,2),!0)}for(let E of ie(s,"engines","Engines")){let T=await y2(e,E);if(p.push({step:"upsertEngine",apiEngineKey:S(E,"apiEngineKey","ApiEngineKey"),response:T}),T.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"upsertEngine",engine:E,response:T,results:p},null,2),!0)}for(let E of ie(s,"events","Events")){let T=await e.saveEventCode(S(E,"formEngineKey","FormEngineKey"),S(E,"eventType","EventType"),S(E,"code","Code","V8Code"));if(p.push({step:"saveEvent",event:E,response:T}),T.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"saveEvent",event:E,response:T,results:p},null,2),!0)}for(let E=0;E<x.length;E+=1){let T=x[E],A={...DY(T,f,m,y),...b[E]||{}},I=await e.createModule(A);if(p.push({step:"createModule",moduleName:A.Name,response:I}),I.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"createModule",module:A,response:I,results:p},null,2),!0);let R=S(H(I.Data),"ModuleId","Id");R&&typeof A.Name=="string"&&m.set(A.Name.toLowerCase(),R)}for(let E of _){let T;try{T=HY(E.field,E.tableName,f,m)}catch(F){return W(JSON.stringify({ok:!1,failedAt:"resolveRelationConfig",tableName:E.tableName,fieldName:S(E.field,"name","Name"),error:F instanceof Error?F.message:String(F),results:p},null,2),!0)}let A=S2(E.table,E.field,E.tableId,E.tableLayout,T),I=await e.addField(A);if(p.push({step:"addRelationField",tableName:E.tableName,fieldName:S(E.field,"name","Name"),response:I}),I.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"addRelationField",tableName:E.tableName,field:E.field,response:I,results:p},null,2),!0);let R=H(I.Data);if(Zr(R,"Skipped")===!0){let F=await e.updateField(dn({Id:S(R,"FieldId","Id"),TableId:E.tableId,Name:S(A,"Name"),Label:S(A,"Label"),Component:S(A,"Component"),Config:S(A,"Config"),FormWidth:oe(A,"FormWidth")}));if(p.push({step:"repairRelationField",tableName:E.tableName,fieldName:S(E.field,"name","Name"),response:F}),F.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"repairRelationField",tableName:E.tableName,field:E.field,response:F,results:p},null,2),!0)}}if(_.length>0){let E=await e.getDbSchema();if(p.push({step:"refreshDbSchemaAfterRelations",response:{Code:E.Code,Msg:E.Msg,Summary:H(H(E.Data).Summary)}}),E.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"refreshDbSchemaAfterRelations",response:E,results:p},null,2),!0);l2(y,E.Data,f)}for(let E of ie(s,"permissions","Permissions")){let T=S(E,"roleName","RoleName","name","Name"),A=S(E,"roleId","RoleId")||(T?h.get(T.toLowerCase()):"")||"admin",I=Ss(E,"menuIds","MenuIds"),R=Ss(E,"moduleNames","ModuleNames"),F=I.length?I:R.map(j=>m.get(j.toLowerCase())||"").filter(Boolean),z=await e.setRolePermission(A,F);if(p.push({step:"setRolePermission",roleId:A,menuIds:F,response:z}),z.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"setRolePermission",permission:E,response:z,results:p},null,2),!0)}for(let E of ie(s,"pages","Pages")){let T=ti(E.json??E.JsonObj??E.JsonStr??E);if(!T.ok||!T.json)return W(JSON.stringify({ok:!1,failedAt:"savePage:normalize",page:E,errors:T.errors,warnings:T.warnings,results:p},null,2),!0);let A=await e.savePageEngine({PageId:S(E,"pageId","PageId","Id")||void 0,Title:S(E,"title","Title"),Number:S(E,"number","Number")||void 0,Desc:S(E,"desc","Desc")||void 0,JsonStr:T.json,RoutePath:S(E,"routePath","RoutePath")||void 0,ComponentPath:S(E,"componentPath","ComponentPath")||void 0});if(p.push({step:"savePage",title:S(E,"title","Title"),response:A}),A.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"savePage",page:E,response:A,results:p},null,2),!0)}for(let E of ie(s,"printTemplates","PrintTemplates")){let T=w2(E),A=await e.savePrintTemplate(T);if(p.push({step:"savePrintTemplate",title:S(T,"Title"),response:A}),A.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"savePrintTemplate",template:T,response:A,results:p},null,2),!0)}for(let E of ie(s,"workflows","Workflows")){let T=h2(E,f),A=await g2(e,T);if(A.length)return W(JSON.stringify({ok:!1,failedAt:"saveWorkflowPackage:references",errors:A,results:p},null,2),!0);let I=await e.saveWorkflowPackage(T);if(p.push({step:"saveWorkflowPackage",workflow:S(H(T.FlowDesign??T.flowDesign??T),"FlowName","flowName"),response:I}),I.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"saveWorkflowPackage",workflow:T,response:I,results:p},null,2),!0);let R=S(H(T.FlowDesign),"FlowName"),F=S(H(I.Data),"FlowDesignId");R&&F&&g.set(R,F)}for(let E of x){if(S(E,"openType","OpenType").toLowerCase()!=="workflow")continue;let T=S(E,"name","Name"),A=S(E,"flowName","FlowName");if(!A)continue;let I=g.get(A),R=m.get(T.toLowerCase());if(!I||!R)return W(JSON.stringify({ok:!1,failedAt:"bindWorkflowModule",moduleName:T,flowName:A,results:p},null,2),!0);let F=await e.updateModule({ModuleId:R,OpenType:"WorkFlow",FlowDesignId:I});if(p.push({step:"bindWorkflowModule",moduleName:T,flowName:A,flowId:I,response:F}),F.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"bindWorkflowModule",moduleName:T,flowName:A,response:F,results:p},null,2),!0)}for(let E of ie(s,"jobs","Jobs")){let T=_2(E),A=await e.saveJob(T);if(p.push({step:"saveJob",jobName:S(T,"JobName"),response:A}),A.Code!==1)return W(JSON.stringify({ok:!1,failedAt:"saveJob",job:T,response:A,results:p},null,2),!0)}let C=await b2(e,s);return await qr(e,"microi_generate_system:finish",S(s,"name","Name")||"manifest",{results:p,validation:C}),W(JSON.stringify(aY(p,C),null,2),C.Code!==1)}catch(v){return W(`Error: ${v instanceof Error?v.message:String(v)}
139
139
 
140
- ${JSON.stringify({results:p},null,2)}`,!0)}}),t.tool("microi_list_roles",`List roles for OsClient ${n}.`,{keyword:d.string().optional()},async({keyword:s})=>ht("Roles",await e.listRoles(s))),t.tool("microi_save_role",`Create or update a role for OsClient ${n}.`,{role:tr,confirmExecution:d.string().optional()},async({role:s,confirmExecution:c})=>{let l=v2(s),u=S(l,"Name");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_save_role",u,l),ht("Save Role",await e.saveRole(l)))}),t.tool("microi_list_modules",`List menu modules for OsClient ${n}.`,{keyword:d.string().optional()},async({keyword:s})=>ht("Modules",await e.listModules(s))),t.tool("microi_get_module",`Get one menu module by ModuleId for OsClient ${n}.`,{moduleId:d.string()},async({moduleId:s})=>ht("Module Detail",await e.getModule(s))),t.tool("microi_update_module",`Incrementally update an existing menu module, including TableHeaders multirow groups [{Label,Fields:[visible consecutive field names]}], HideTableBanner/HideFormBanner (1 hides the corresponding top Banner), MenuBadgeEnabled/MenuBadgeApiEngineKey, ViewSchema, and button/tab JSON. OsClient ${n}. The tool validates JSON and verifies the saved fields by remote readback, including recovery after uncertain transport timeouts. Pass plain JSON arrays for TableHeaders/MoreBtns/FormBtns/PageTabs etc.; never Base64-encode them or bypass this tool with raw FormEngine/SQL writes.`,{module:tr,confirmExecution:d.string().optional()},async({module:s,confirmExecution:c})=>{let l=ks(s);if(l.errors.length)return W(JSON.stringify(l,null,2),!0);let u=S(s,"moduleId","ModuleId","Id")||S(s,"name","Name");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_update_module",u,l.data),ht("Update Module",await e.updateModule(l.data)))}),t.tool("microi_upsert_engine",`Create an API engine if missing, otherwise update only the supplied code and/or v8Limit setting. Omitted v8Limit preserves the current value; omitted code never clears existing source. v8Limit=false/default means unrestricted Jint per-execution budgets; true enables the configured runtime limits. OsClient ${n}.`,{engine:tr.describe("Fields include apiEngineKey, apiName, category, code and optional boolean v8Limit"),confirmExecution:d.string().optional()},async({engine:s,confirmExecution:c})=>{let l=S(s,"apiEngineKey","ApiEngineKey");return l?c!==l&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${l}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_upsert_engine",l,s),ht("Upsert Engine",await y2(e,s))):W("ApiEngineKey \u4E0D\u80FD\u4E3A\u7A7A",!0)}),t.tool("microi_list_data_sources",`List typed API engines that replace legacy sys_datasource rows for OsClient ${n}.`,{keyword:d.string().optional()},async({keyword:s})=>ht("Data Sources",await e.listDataSources(s))),t.tool("microi_save_data_source",`Create or update a typed sys_apiengine data source. Put SQL, V8 JavaScript or JSON in ApiV8Code; legacy SqlDataSource/V8DataSource/JsonDataSource inputs are accepted only as compatibility aliases and are not persisted. OsClient ${n}.`,{dataSource:tr,confirmExecution:d.string().optional()},async({dataSource:s,confirmExecution:c})=>{let l=x2(s),u=S(l,"DataSourceKey");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_save_data_source",u,l),ht("Save Data Source",await e.saveDataSource(l)))}),t.tool("microi_run_data_source",`Run a typed API-engine data source through the legacy-compatible key contract. May have side effects if its V8 code writes data. OsClient ${n}.`,{dataSourceKey:d.string(),params:tr.optional(),confirmExecution:d.string().optional()},async({dataSourceKey:s,params:c,confirmExecution:l})=>l!==s&&l!=="EXECUTE"?W(`\u6267\u884C\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${s}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_run_data_source",s,c||{}),ht("Run Data Source",await e.runDataSource(s,c)))),t.tool("microi_list_print_templates",`List print engine templates for OsClient ${n}.`,{keyword:d.string().optional()},async({keyword:s})=>ht("Print Templates",await e.listPrintTemplates(s))),t.tool("microi_save_print_template",`Create or update a mic_print print template. OsClient ${n}.`,{template:tr,confirmExecution:d.string().optional()},async({template:s,confirmExecution:c})=>{let l=w2(s),u=S(l,"Title");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_save_print_template",u,l),ht("Save Print Template",await e.savePrintTemplate(l)))}),t.tool("microi_save_workflow_package",`\u5728\u5F53\u524D\u79DF\u6237 ${n} \u4E00\u6B21\u4FDD\u5B58 wf_flowdesign + wf_node + wf_line\u3002\u663E\u5F0F IsEnable=0 \u6216 "0" \u7684\u7981\u7528\u5B89\u88C5\u6BCD\u7248\u53EF\u4FDD\u6301\u7A7A\u4EBA\u5458\u7ED1\u5B9A\uFF0C\u4ECD\u68C0\u67E5\u5168\u90E8\u62D3\u6251\u548C\u7ED1\u5B9A\u683C\u5F0F\uFF1B\u4EFB\u4F55\u5DF2\u586B\u5199\u7684\u7528\u6237\u3001\u89D2\u8272\u3001\u90E8\u95E8\u3001\u5C97\u4F4D\u5747\u987B\u5F53\u524D\u79DF\u6237\u771F\u5B9E\u56DE\u8BFB\uFF0C\u5047\u5360\u4F4D Id \u6216\u5F15\u7528\u56DE\u8BFB\u5931\u8D25\u4F1A\u62D2\u7EDD\u4FDD\u5B58\u3002\u542F\u7528\u6216\u7701\u7565 IsEnable \u4ECD\u5F3A\u5236\u4EBA\u5DE5\u8282\u70B9\u4EBA\u5458\u7B56\u7565\u3002`,{workflow:tr,confirmExecution:d.string().optional()},async({workflow:s,confirmExecution:c})=>{let l=S(H(s.FlowDesign??s.flowDesign??s),"FlowName","flowName","name"),u=W0(s);if(!u.ok)return W(JSON.stringify(u,null,2),!0);if(c!==l&&c!=="EXECUTE")return W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${l}" \u6216 "EXECUTE"\u3002`,!0);let p=new Map;if(S(H(s.FlowDesign??s.flowDesign),"table","tableName")){let h=await e.getDbSchema();if(h.Code!==1)return ht("Read workflow table schema",h);for(let g of ii(H(h.Data).Tables)){let y=S(g,"Name"),x=S(g,"Id");y&&x&&p.set(y.toLowerCase(),x)}}let f;try{f=h2(s,p)}catch(h){return W(h instanceof Error?h.message:String(h),!0)}let m=await g2(e,f);return m.length?W(JSON.stringify({ok:!1,errors:m},null,2),!0):(await qr(e,"microi_save_workflow_package",l,s),ht("Save Workflow Package",await e.saveWorkflowPackage(f)))}),t.tool("microi_save_job",`Create or update a scheduled job. For ApiEngine jobs use JobType="1" and ApiEngineKey. OsClient ${n}.`,{job:tr,confirmExecution:d.string().optional()},async({job:s,confirmExecution:c})=>{let l=_2(s),u=S(l,"JobName");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_save_job",u,l),ht("Save Job",await e.saveJob(l)))}),t.tool("microi_query_job_runtime",`Read current-node Quartz diagnostics or monthly execution logs for the authenticated tenant ${n}. Diagnostics never triggers or re-registers a job. Logs use MongoDB; HistoryLogs retains relational history. Cursor pagination returns HasMore, not an exact total. Backend administrator checks remain mandatory; a running scheduler is not proof of execution.`,{action:d.enum(["Diagnostics","Logs","HistoryLogs"]),jobName:d.string().min(1).max(100),searchMonth:d.string().regex(/^\d{4}(0[1-9]|1[0-2])$/).optional(),pageSize:d.number().int().min(1).max(100).optional(),beforeLogTime:d.string().max(50).optional(),beforeLogId:d.string().max(100).optional()},async({action:s,jobName:c,searchMonth:l,pageSize:u,beforeLogTime:p,beforeLogId:f})=>s!=="Diagnostics"&&!l?W("\u65E5\u5FD7\u67E5\u8BE2\u5FC5\u987B\u6307\u5B9A searchMonth\uFF08yyyyMM\uFF09\u3002",!0):!!p!=!!f?W("\u7FFB\u9875\u5FC5\u987B\u540C\u65F6\u63D0\u4F9B beforeLogTime \u548C beforeLogId\u3002",!0):ht("Job Runtime",await e.executeEngine("platform-schedule-job",{Action:s,JobName:c,SearchMonth:l,PageSize:u??20,BeforeLogTime:p,BeforeLogId:f}))),t.tool("microi_list_database_backup_tenants",`List the enabled MySQL tenants eligible for database backup on the current backend runtime. The server strictly filters sys_osclients by its own OsClientType and OsClientNetwork and never returns connection strings. OsClient ${n}.`,{},async()=>ht("Database Backup Tenants",await e.listDatabaseBackupTenants())),t.tool("microi_run_database_backup",`Queue a durable database backup task for the current backend runtime. Omit tenantOsClients to back up every eligible tenant; when provided, every key must be in microi_list_database_backup_tenants. idempotencyKey is caller-generated and must be reused after timeout or any uncertain response. The server serializes execution with a renewable Redis lease and uploads only to the main tenant private HDFS. OsClient ${n}.`,{tenantOsClients:d.array(d.string().regex(/^[A-Za-z0-9._-]{1,100}$/)).min(1).max(2e3).optional(),retainCount:d.number().int().min(1).max(100).optional(),idempotencyKey:d.string().regex(/^[A-Za-z0-9:._-]{8,128}$/).describe("Stable caller request id; reuse the exact value for uncertain retries"),confirmExecution:d.literal("DATABASE_BACKUP").optional()},async({tenantOsClients:s,retainCount:c,idempotencyKey:l,confirmExecution:u})=>{if(u!=="DATABASE_BACKUP")return W('\u6267\u884C\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="DATABASE_BACKUP"\u3002',!0);let p={TenantOsClients:s,RetainCount:c??7,IdempotencyKey:l,SelectionMode:s===void 0?"AllEligible":"Selected"};return await qr(e,"microi_run_database_backup",p.SelectionMode,p),ht("Run Database Backup",await e.runDatabaseBackup({tenantOsClients:s,retainCount:c,idempotencyKey:l}))});let o={storeId:d.string().regex(/^[A-Za-z0-9:._-]{1,100}$/).describe("\u5546\u57CE sys_microistore \u8BB0\u5F55 Id"),storeVersionId:d.string().regex(/^[A-Za-z0-9:._-]{1,100}$/).optional().describe("\u53EF\u9009\uFF1Amic_data_version \u4E0D\u53EF\u53D8\u5B8C\u6574\u5305\u5FEB\u7167 Id\uFF0C\u7528\u4E8E\u53D1\u5E03\u5347\u7248\u540E\u7684\u7CBE\u786E\u6062\u590D"),requestId:d.string().regex(/^[A-Za-z0-9:._-]{8,100}$/).describe("\u8C03\u7528\u65B9\u751F\u6210\u5E76\u5728\u4E0D\u786E\u5B9A\u91CD\u8BD5\u65F6\u590D\u7528\u7684\u7A33\u5B9A\u5E42\u7B49 Id"),appId:d.string().max(100).optional(),appName:d.string().max(200).optional(),appVersion:d.string().max(50).optional(),installParentSysMenuId:d.string().max(100).optional(),resumeInstall:d.boolean().optional(),confirmExecution:d.string().optional().describe("\u771F\u5B9E\u6267\u884C\u65F6\u5FC5\u987B\u7CBE\u786E\u7B49\u4E8E storeId")},a=(s,c)=>{let l=c==="update"?"\u66F4\u65B0":"\u5B89\u88C5";t.tool(s,`${l}\u4E00\u4E2A\u5E94\u7528\u5546\u57CE\u5E94\u7528\u5230\u5F53\u524D MCP \u7ED1\u5B9A\u79DF\u6237 ${n}\u3002\u4EFB\u52A1\u53EA\u4F20 StoreId\u3001\u53EF\u9009\u4E0D\u53EF\u53D8 StoreVersionId \u548C\u5546\u57CE\u6E90\u5B9A\u4F4D\u4FE1\u606F\uFF0C\u7531\u670D\u52A1\u7AEF\u6301\u4E45\u961F\u5217\u8C03\u7528 import-microi-store-package\uFF1B\u9996\u6B21\u8C03\u7528\u4E0D\u4F20 confirmExecution \u53EA\u8FD4\u56DE\u9884\u68C0\uFF0C\u771F\u5B9E\u6267\u884C\u540E\u5FC5\u987B\u8F6E\u8BE2\u540E\u53F0\u4EFB\u52A1\u81F3 Succeeded\u3002`,o,async u=>{let p;try{p=nY({operation:c,storeId:u.storeId,storeVersionId:u.storeVersionId,requestId:u.requestId,appId:u.appId,appName:u.appName,appVersion:u.appVersion,installParentSysMenuId:u.installParentSysMenuId,resumeInstall:u.resumeInstall})}catch(f){return W(f instanceof Error?f.message:String(f),!0)}return u.confirmExecution!==u.storeId?W(JSON.stringify({DryRun:!0,Operation:c,TargetOsClient:n,Request:p,Confirmation:`\u786E\u8BA4\u540E\u4F20 confirmExecution="${u.storeId}"`,NextStep:"\u771F\u5B9E\u63D0\u4EA4\u540E\u8F6E\u8BE2\u53F3\u4E0A\u89D2\u540E\u53F0\u4EFB\u52A1/\u5171\u4EAB\u4EFB\u52A1\u8868\u81F3 Succeeded\uFF0C\u518D\u505A\u8FDC\u7AEF\u8D44\u6E90\u4E0E UI \u9A8C\u6536\u3002"},null,2)):(await qr(e,s,u.storeId,{Operation:c,StoreId:u.storeId,StoreVersionId:p.Param.StoreVersionId,StoreApiBase:p.Param.StoreApiBase,StoreOsClient:p.Param.StoreOsClient,IdempotencyKey:p.Options.IdempotencyKey}),ht(`${l}\u5546\u57CE\u5E94\u7528`,await e.runBackgroundApiEngine({apiEngineKey:p.ApiEngineKey,title:p.Title,param:p.Param,options:p.Options})))})};a("microi_install_store_application","install"),a("microi_update_store_application","update")}var KY=d.record(d.unknown());function Ts(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}function Fn(t,e){let r=[`## ${t}`,`- Code: ${e.Code}`,e.Msg?`- Message: ${e.Msg}`:"","","```json",JSON.stringify(e.Data??{},null,2),"```"].filter(Boolean);return Ts(r.join(`
140
+ ${JSON.stringify({results:p},null,2)}`,!0)}}),t.tool("microi_list_roles",`List roles for OsClient ${n}.`,{keyword:d.string().optional()},async({keyword:s})=>ht("Roles",await e.listRoles(s))),t.tool("microi_save_role",`Create or update a role for OsClient ${n}.`,{role:tr,confirmExecution:d.string().optional()},async({role:s,confirmExecution:c})=>{let l=v2(s),u=S(l,"Name");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_save_role",u,l),ht("Save Role",await e.saveRole(l)))}),t.tool("microi_list_modules",`List menu modules for OsClient ${n}.`,{keyword:d.string().optional()},async({keyword:s})=>ht("Modules",await e.listModules(s))),t.tool("microi_get_module",`Get one menu module by ModuleId for OsClient ${n}.`,{moduleId:d.string()},async({moduleId:s})=>ht("Module Detail",await e.getModule(s))),t.tool("microi_update_module",`Incrementally update an existing menu module, including FieldPermissions v1 (Rules with Users/Roles/Departments/Jobs and Fields.Visible/Editable), TreeDragSortEnabled/TreeDragSortField, TableHeaders multirow groups [{Label,Fields:[visible consecutive field names]}], HideTableBanner/HideFormBanner (1 hides the corresponding top Banner), MenuBadgeEnabled/MenuBadgeApiEngineKey, ViewSchema, and button/tab JSON. OsClient ${n}. The tool validates JSON and verifies the saved fields by remote readback, including recovery after uncertain transport timeouts. Pass plain JSON arrays for TableHeaders/MoreBtns/FormBtns/PageTabs etc.; never Base64-encode them or bypass this tool with raw FormEngine/SQL writes.`,{module:tr,confirmExecution:d.string().optional()},async({module:s,confirmExecution:c})=>{let l=ks(s);if(l.errors.length)return W(JSON.stringify(l,null,2),!0);let u=S(s,"moduleId","ModuleId","Id")||S(s,"name","Name");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_update_module",u,l.data),ht("Update Module",await e.updateModule(l.data)))}),t.tool("microi_upsert_engine",`Create an API engine if missing, otherwise update only the supplied code and/or v8Limit setting. Omitted v8Limit preserves the current value; omitted code never clears existing source. v8Limit=false/default means unrestricted Jint per-execution budgets; true enables the configured runtime limits. OsClient ${n}.`,{engine:tr.describe("Fields include apiEngineKey, apiName, category, code and optional boolean v8Limit"),confirmExecution:d.string().optional()},async({engine:s,confirmExecution:c})=>{let l=S(s,"apiEngineKey","ApiEngineKey");return l?c!==l&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${l}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_upsert_engine",l,s),ht("Upsert Engine",await y2(e,s))):W("ApiEngineKey \u4E0D\u80FD\u4E3A\u7A7A",!0)}),t.tool("microi_list_data_sources",`List typed API engines that replace legacy sys_datasource rows for OsClient ${n}.`,{keyword:d.string().optional()},async({keyword:s})=>ht("Data Sources",await e.listDataSources(s))),t.tool("microi_save_data_source",`Create or update a typed sys_apiengine data source. Put SQL, V8 JavaScript or JSON in ApiV8Code; legacy SqlDataSource/V8DataSource/JsonDataSource inputs are accepted only as compatibility aliases and are not persisted. OsClient ${n}.`,{dataSource:tr,confirmExecution:d.string().optional()},async({dataSource:s,confirmExecution:c})=>{let l=x2(s),u=S(l,"DataSourceKey");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_save_data_source",u,l),ht("Save Data Source",await e.saveDataSource(l)))}),t.tool("microi_run_data_source",`Run a typed API-engine data source through the legacy-compatible key contract. May have side effects if its V8 code writes data. OsClient ${n}.`,{dataSourceKey:d.string(),params:tr.optional(),confirmExecution:d.string().optional()},async({dataSourceKey:s,params:c,confirmExecution:l})=>l!==s&&l!=="EXECUTE"?W(`\u6267\u884C\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${s}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_run_data_source",s,c||{}),ht("Run Data Source",await e.runDataSource(s,c)))),t.tool("microi_list_print_templates",`List print engine templates for OsClient ${n}.`,{keyword:d.string().optional()},async({keyword:s})=>ht("Print Templates",await e.listPrintTemplates(s))),t.tool("microi_save_print_template",`Create or update a mic_print print template. OsClient ${n}.`,{template:tr,confirmExecution:d.string().optional()},async({template:s,confirmExecution:c})=>{let l=w2(s),u=S(l,"Title");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_save_print_template",u,l),ht("Save Print Template",await e.savePrintTemplate(l)))}),t.tool("microi_save_workflow_package",`\u5728\u5F53\u524D\u79DF\u6237 ${n} \u4E00\u6B21\u4FDD\u5B58 wf_flowdesign + wf_node + wf_line\u3002\u663E\u5F0F IsEnable=0 \u6216 "0" \u7684\u7981\u7528\u5B89\u88C5\u6BCD\u7248\u53EF\u4FDD\u6301\u7A7A\u4EBA\u5458\u7ED1\u5B9A\uFF0C\u4ECD\u68C0\u67E5\u5168\u90E8\u62D3\u6251\u548C\u7ED1\u5B9A\u683C\u5F0F\uFF1B\u4EFB\u4F55\u5DF2\u586B\u5199\u7684\u7528\u6237\u3001\u89D2\u8272\u3001\u90E8\u95E8\u3001\u5C97\u4F4D\u5747\u987B\u5F53\u524D\u79DF\u6237\u771F\u5B9E\u56DE\u8BFB\uFF0C\u5047\u5360\u4F4D Id \u6216\u5F15\u7528\u56DE\u8BFB\u5931\u8D25\u4F1A\u62D2\u7EDD\u4FDD\u5B58\u3002\u542F\u7528\u6216\u7701\u7565 IsEnable \u4ECD\u5F3A\u5236\u4EBA\u5DE5\u8282\u70B9\u4EBA\u5458\u7B56\u7565\u3002`,{workflow:tr,confirmExecution:d.string().optional()},async({workflow:s,confirmExecution:c})=>{let l=S(H(s.FlowDesign??s.flowDesign??s),"FlowName","flowName","name"),u=W0(s);if(!u.ok)return W(JSON.stringify(u,null,2),!0);if(c!==l&&c!=="EXECUTE")return W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${l}" \u6216 "EXECUTE"\u3002`,!0);let p=new Map;if(S(H(s.FlowDesign??s.flowDesign),"table","tableName")){let h=await e.getDbSchema();if(h.Code!==1)return ht("Read workflow table schema",h);for(let g of ii(H(h.Data).Tables)){let y=S(g,"Name"),x=S(g,"Id");y&&x&&p.set(y.toLowerCase(),x)}}let f;try{f=h2(s,p)}catch(h){return W(h instanceof Error?h.message:String(h),!0)}let m=await g2(e,f);return m.length?W(JSON.stringify({ok:!1,errors:m},null,2),!0):(await qr(e,"microi_save_workflow_package",l,s),ht("Save Workflow Package",await e.saveWorkflowPackage(f)))}),t.tool("microi_save_job",`Create or update a scheduled job. For ApiEngine jobs use JobType="1" and ApiEngineKey. OsClient ${n}.`,{job:tr,confirmExecution:d.string().optional()},async({job:s,confirmExecution:c})=>{let l=_2(s),u=S(l,"JobName");return c!==u&&c!=="EXECUTE"?W(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="${u}" \u6216 "EXECUTE"\u3002`,!0):(await qr(e,"microi_save_job",u,l),ht("Save Job",await e.saveJob(l)))}),t.tool("microi_query_job_runtime",`Read current-node Quartz diagnostics or monthly execution logs for the authenticated tenant ${n}. Diagnostics never triggers or re-registers a job. Logs use MongoDB; HistoryLogs retains relational history. Cursor pagination returns HasMore, not an exact total. Backend administrator checks remain mandatory; a running scheduler is not proof of execution.`,{action:d.enum(["Diagnostics","Logs","HistoryLogs"]),jobName:d.string().min(1).max(100),searchMonth:d.string().regex(/^\d{4}(0[1-9]|1[0-2])$/).optional(),pageSize:d.number().int().min(1).max(100).optional(),beforeLogTime:d.string().max(50).optional(),beforeLogId:d.string().max(100).optional()},async({action:s,jobName:c,searchMonth:l,pageSize:u,beforeLogTime:p,beforeLogId:f})=>s!=="Diagnostics"&&!l?W("\u65E5\u5FD7\u67E5\u8BE2\u5FC5\u987B\u6307\u5B9A searchMonth\uFF08yyyyMM\uFF09\u3002",!0):!!p!=!!f?W("\u7FFB\u9875\u5FC5\u987B\u540C\u65F6\u63D0\u4F9B beforeLogTime \u548C beforeLogId\u3002",!0):ht("Job Runtime",await e.executeEngine("platform-schedule-job",{Action:s,JobName:c,SearchMonth:l,PageSize:u??20,BeforeLogTime:p,BeforeLogId:f}))),t.tool("microi_list_database_backup_tenants",`List the enabled MySQL tenants eligible for database backup on the current backend runtime. The server strictly filters sys_osclients by its own OsClientType and OsClientNetwork and never returns connection strings. OsClient ${n}.`,{},async()=>ht("Database Backup Tenants",await e.listDatabaseBackupTenants())),t.tool("microi_run_database_backup",`Queue a durable database backup task for the current backend runtime. Omit tenantOsClients to back up every eligible tenant; when provided, every key must be in microi_list_database_backup_tenants. idempotencyKey is caller-generated and must be reused after timeout or any uncertain response. The server serializes execution with a renewable Redis lease and uploads only to the main tenant private HDFS. OsClient ${n}.`,{tenantOsClients:d.array(d.string().regex(/^[A-Za-z0-9._-]{1,100}$/)).min(1).max(2e3).optional(),retainCount:d.number().int().min(1).max(100).optional(),idempotencyKey:d.string().regex(/^[A-Za-z0-9:._-]{8,128}$/).describe("Stable caller request id; reuse the exact value for uncertain retries"),confirmExecution:d.literal("DATABASE_BACKUP").optional()},async({tenantOsClients:s,retainCount:c,idempotencyKey:l,confirmExecution:u})=>{if(u!=="DATABASE_BACKUP")return W('\u6267\u884C\u5DF2\u62E6\u622A\uFF1A\u8BF7\u4F20 confirmExecution="DATABASE_BACKUP"\u3002',!0);let p={TenantOsClients:s,RetainCount:c??7,IdempotencyKey:l,SelectionMode:s===void 0?"AllEligible":"Selected"};return await qr(e,"microi_run_database_backup",p.SelectionMode,p),ht("Run Database Backup",await e.runDatabaseBackup({tenantOsClients:s,retainCount:c,idempotencyKey:l}))});let o={storeId:d.string().regex(/^[A-Za-z0-9:._-]{1,100}$/).describe("\u5546\u57CE sys_microistore \u8BB0\u5F55 Id"),storeVersionId:d.string().regex(/^[A-Za-z0-9:._-]{1,100}$/).optional().describe("\u53EF\u9009\uFF1Amic_data_version \u4E0D\u53EF\u53D8\u5B8C\u6574\u5305\u5FEB\u7167 Id\uFF0C\u7528\u4E8E\u53D1\u5E03\u5347\u7248\u540E\u7684\u7CBE\u786E\u6062\u590D"),requestId:d.string().regex(/^[A-Za-z0-9:._-]{8,100}$/).describe("\u8C03\u7528\u65B9\u751F\u6210\u5E76\u5728\u4E0D\u786E\u5B9A\u91CD\u8BD5\u65F6\u590D\u7528\u7684\u7A33\u5B9A\u5E42\u7B49 Id"),appId:d.string().max(100).optional(),appName:d.string().max(200).optional(),appVersion:d.string().max(50).optional(),installParentSysMenuId:d.string().max(100).optional(),resumeInstall:d.boolean().optional(),confirmExecution:d.string().optional().describe("\u771F\u5B9E\u6267\u884C\u65F6\u5FC5\u987B\u7CBE\u786E\u7B49\u4E8E storeId")},a=(s,c)=>{let l=c==="update"?"\u66F4\u65B0":"\u5B89\u88C5";t.tool(s,`${l}\u4E00\u4E2A\u5E94\u7528\u5546\u57CE\u5E94\u7528\u5230\u5F53\u524D MCP \u7ED1\u5B9A\u79DF\u6237 ${n}\u3002\u4EFB\u52A1\u53EA\u4F20 StoreId\u3001\u53EF\u9009\u4E0D\u53EF\u53D8 StoreVersionId \u548C\u5546\u57CE\u6E90\u5B9A\u4F4D\u4FE1\u606F\uFF0C\u7531\u670D\u52A1\u7AEF\u6301\u4E45\u961F\u5217\u8C03\u7528 import-microi-store-package\uFF1B\u9996\u6B21\u8C03\u7528\u4E0D\u4F20 confirmExecution \u53EA\u8FD4\u56DE\u9884\u68C0\uFF0C\u771F\u5B9E\u6267\u884C\u540E\u5FC5\u987B\u8F6E\u8BE2\u540E\u53F0\u4EFB\u52A1\u81F3 Succeeded\u3002`,o,async u=>{let p;try{p=nY({operation:c,storeId:u.storeId,storeVersionId:u.storeVersionId,requestId:u.requestId,appId:u.appId,appName:u.appName,appVersion:u.appVersion,installParentSysMenuId:u.installParentSysMenuId,resumeInstall:u.resumeInstall})}catch(f){return W(f instanceof Error?f.message:String(f),!0)}return u.confirmExecution!==u.storeId?W(JSON.stringify({DryRun:!0,Operation:c,TargetOsClient:n,Request:p,Confirmation:`\u786E\u8BA4\u540E\u4F20 confirmExecution="${u.storeId}"`,NextStep:"\u771F\u5B9E\u63D0\u4EA4\u540E\u8F6E\u8BE2\u53F3\u4E0A\u89D2\u540E\u53F0\u4EFB\u52A1/\u5171\u4EAB\u4EFB\u52A1\u8868\u81F3 Succeeded\uFF0C\u518D\u505A\u8FDC\u7AEF\u8D44\u6E90\u4E0E UI \u9A8C\u6536\u3002"},null,2)):(await qr(e,s,u.storeId,{Operation:c,StoreId:u.storeId,StoreVersionId:p.Param.StoreVersionId,StoreApiBase:p.Param.StoreApiBase,StoreOsClient:p.Param.StoreOsClient,IdempotencyKey:p.Options.IdempotencyKey}),ht(`${l}\u5546\u57CE\u5E94\u7528`,await e.runBackgroundApiEngine({apiEngineKey:p.ApiEngineKey,title:p.Title,param:p.Param,options:p.Options})))})};a("microi_install_store_application","install"),a("microi_update_store_application","update")}var KY=d.record(d.unknown());function Ts(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}function Fn(t,e){let r=[`## ${t}`,`- Code: ${e.Code}`,e.Msg?`- Message: ${e.Msg}`:"","","```json",JSON.stringify(e.Data??{},null,2),"```"].filter(Boolean);return Ts(r.join(`
141
141
  `),e.Code!==1)}async function nw(t,e,r,n){try{await t.writeAuditLog(e,r,JSON.stringify(n).slice(0,6e3))}catch(i){console.error("[microi-mcp] blueprint audit log failed:",i instanceof Error?i.message:String(i))}}var WY=`# Microi \u4E1A\u52A1\u67B6\u6784\u84DD\u56FE\uFF08System Blueprint\uFF09\u534F\u8BAE
142
142
 
143
143
  ## \u9876\u5C42\u7ED3\u6784
@@ -550,7 +550,7 @@ ${JSON.stringify(p.Data||{},null,2)}`}],isError:!0}:{content:[{type:"text",text:
550
550
  ${JSON.stringify(u.Data||{},null,2)}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(u,null,2)}]}}catch(u){return{content:[{type:"text",text:`Error: ${u instanceof Error?u.message:String(u)}`}],isError:!0}}}),i.tool("microi_list_database_types","List all database types certified by the current Microi Dos.ORM runtime, including aliases, default ports, and redacted connection-string examples.",{},async()=>{try{let a=await t.getSupportedDatabaseTypes();return a.Code!==1?{content:[{type:"text",text:`Error: ${a.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(a.Data,null,2)}]}}catch(a){return{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],isError:!0}}}),i.tool("microi_inspect_external_database",`Connect to an external database through Dos.ORM for OsClient "${r}" and return physical tables, columns, native types, nullability, keys, and comments. Prefer dbKey after saving a connection so credentials are not repeatedly passed to AI tools. This tool never returns the connection string.`,{dbKey:d.string().optional().describe("Saved and enabled microi_database DbKey. Preferred over passing connectionString."),databaseType:d.string().optional().describe("Required only with a temporary connectionString. Call microi_list_database_types for certified values."),connectionString:d.string().optional().describe("Temporary database connection string. Sensitive: never place it in generated code, logs, or narrative output."),tableName:d.string().optional().describe("Optional case-insensitive partial table-name filter."),maxTables:d.number().int().min(1).max(5e3).optional().describe("Maximum returned tables. Default 500."),includeColumns:d.boolean().optional().describe("Whether to load columns for each table. Default true."),commandTimeoutSeconds:d.number().int().min(1).max(600).optional().describe("Metadata query timeout. Default 60 seconds.")},async({dbKey:a,databaseType:s,connectionString:c,tableName:l,maxTables:u,includeColumns:p,commandTimeoutSeconds:f})=>{if(!a&&(!s||!c))return{content:[{type:"text",text:"Error: pass dbKey, or both databaseType and connectionString."}],isError:!0};try{let m=await t.inspectExternalDatabase({DbKey:a,DatabaseType:s,ConnectionString:c,TableName:l,MaxTables:u,IncludeColumns:p,CommandTimeoutSeconds:f});return m.Code!==1?{content:[{type:"text",text:`Error: ${m.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(m.Data,null,2)}]}}catch(m){return{content:[{type:"text",text:`Error: ${m instanceof Error?m.message:String(m)}`}],isError:!0}}}),i.tool("microi_query_external_database",`Run a bounded, parameterized, read-only SELECT/CTE query against an external Dos.ORM database for OsClient "${r}". Use this after schema inspection to read source rows for migration or synchronization. Multi-statement, DML, DDL, procedures, and file-reading SQL are rejected.`,{sql:d.string().min(1).describe("Single read-only SELECT or WITH ... SELECT statement. Use named parameters."),parameters:d.record(d.unknown()).optional().describe("Named SQL parameter values, e.g. { status: 1 }. Never concatenate dynamic values into SQL."),dbKey:d.string().optional().describe("Saved and enabled microi_database DbKey. Preferred."),databaseType:d.string().optional().describe("Required only with a temporary connectionString."),connectionString:d.string().optional().describe("Temporary connection string. Sensitive and never returned."),maxRows:d.number().int().min(1).max(5e3).optional().describe("Maximum returned rows. Default 200."),commandTimeoutSeconds:d.number().int().min(1).max(600).optional().describe("Query timeout. Default 60 seconds.")},async({sql:a,parameters:s,dbKey:c,databaseType:l,connectionString:u,maxRows:p,commandTimeoutSeconds:f})=>{if(!c&&(!l||!u))return{content:[{type:"text",text:"Error: pass dbKey, or both databaseType and connectionString."}],isError:!0};try{let m=await t.queryExternalDatabase({Sql:a,Parameters:s,DbKey:c,DatabaseType:l,ConnectionString:u,MaxRows:p,CommandTimeoutSeconds:f});return m.Code!==1?{content:[{type:"text",text:`Error: ${m.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(m.Data,null,2)}]}}catch(m){return{content:[{type:"text",text:`Error: ${m instanceof Error?m.message:String(m)}`}],isError:!0}}}),i.tool("microi_execute_external_database",`Execute explicitly confirmed administrative SQL against an external Dos.ORM database for OsClient "${r}". This Level >= 9999 control-plane tool intentionally permits DML, DDL, stored procedures, provider-specific commands, and driver-supported multi-statement scripts. The SQL text and connection string are never written to audit logs.`,{sql:d.string().min(1).describe("Raw administrative SQL. It may change schema/data or invoke provider-specific capabilities."),mode:d.enum(["Query","Scalar","NonQuery"]).describe("How Dos.ORM should consume the result. Use NonQuery for DML/DDL/scripts."),parameters:d.record(d.unknown()).optional().describe("Optional named parameters. Use parameters for dynamic values whenever the provider supports them."),dbKey:d.string().optional().describe("Saved and enabled microi_database DbKey. Preferred."),databaseType:d.string().optional().describe("Required only with a temporary connectionString."),connectionString:d.string().optional().describe("Temporary connection string. Sensitive and never returned or audited."),maxRows:d.number().int().min(1).max(1e5).optional().describe("Query response cap only; it does not limit SQL permissions. Default 1000."),commandTimeoutSeconds:d.number().int().min(1).max(86400).optional().describe("Default 600 seconds."),confirmExecution:d.string().optional().describe("Required. Pass EXECUTE or the SHA-256 shown by the dry run.")},async({sql:a,mode:s,parameters:c,dbKey:l,databaseType:u,connectionString:p,maxRows:f,commandTimeoutSeconds:m,confirmExecution:h})=>{if(!l&&(!u||!p))return{content:[{type:"text",text:"Error: pass dbKey, or both databaseType and connectionString."}],isError:!0};let g=nt.default.createHash("sha256").update(a,"utf8").digest("hex");if(h!=="EXECUTE"&&h?.toLowerCase()!==g)return{content:[{type:"text",text:JSON.stringify({dryRun:!0,action:"execute_external_database_sql",target:l?`DbKey:${l}`:`temporary:${u}`,mode:s,sqlSha256:g,sqlLength:a.length,parameterNames:Object.keys(c||{}),connectionStringProvided:!!p,requiresConfirmation:"EXECUTE or sqlSha256"},null,2)}]};try{let y=await t.executeExternalDatabaseSql({Sql:a,Mode:s,Parameters:c,DbKey:l,DatabaseType:u,ConnectionString:p,MaxRows:f,CommandTimeoutSeconds:m,ConfirmExecution:h});return y.Code!==1?{content:[{type:"text",text:`Error: ${y.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(y.Data,null,2)}]}}catch(y){return{content:[{type:"text",text:`Error: ${y instanceof Error?y.message:String(y)}`}],isError:!0}}}),i.tool("microi_save_database_connection",`Validate and add or update a connection in the protected microi_database table for OsClient "${r}". The backend tests the connection before writing, never returns the secret, and invalidates the local V8.Dbs cache. Requires explicit confirmation.`,{dbKey:d.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,49}$/).describe("Stable V8 key used as V8.Dbs.{DbKey}."),dbName:d.string().max(100).optional().describe("Display name. Defaults to dbKey."),databaseType:d.string().describe("Certified type returned by microi_list_database_types."),connectionString:d.string().min(1).describe("Sensitive database connection string. It is validated and never echoed."),dbReadConn:d.string().optional().describe("Optional read-replica connection string of the same database type."),dbVersion:d.string().optional(),remark:d.string().optional(),isEnable:d.number().int().min(0).max(1).optional().describe("Default 1."),commandTimeoutSeconds:d.number().int().min(5).max(120).optional().describe("Connection validation timeout. Default 30 seconds."),confirmExecution:d.string().optional().describe("Required. Pass the exact dbKey or EXECUTE.")},async({dbKey:a,dbName:s,databaseType:c,connectionString:l,dbReadConn:u,dbVersion:p,remark:f,isEnable:m,commandTimeoutSeconds:h,confirmExecution:g})=>{if(g!==a&&g!=="EXECUTE")return{content:[{type:"text",text:JSON.stringify({dryRun:!0,action:"save_database_connection",dbKey:a,dbName:s||a,databaseType:c,connectionStringProvided:!0,requiresConfirmation:a},null,2)}]};try{let y=await t.saveDatabaseConnection({DbKey:a,DbName:s,DatabaseType:c,ConnectionString:l,DbReadConn:u,DbVersion:p,Remark:f,IsEnable:m,CommandTimeoutSeconds:h,ConfirmExecution:g});return y.Code!==1?{content:[{type:"text",text:`Error: ${y.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(y.Data,null,2)}]}}catch(y){return{content:[{type:"text",text:`Error: ${y instanceof Error?y.message:String(y)}`}],isError:!0}}}),i.tool("microi_import_external_attachment",`Stream one attachment from HTTP(S), an absolute server-local path, or a UNC path into Microi storage for OsClient "${r}". This Level >= 9999 control-plane tool intentionally permits private-network and server-filesystem access. It bypasses Base64 buffering and has no fixed MCP size ceiling; MaxBytes is an optional caller safety limit. Requires explicit confirmation and writes a redacted audit record.`,{sourceUrl:d.string().url().refine(a=>/^https?:\/\//i.test(a),"sourceUrl must use http or https").optional().describe("HTTP(S) attachment URL. Provide exactly one of sourceUrl/sourcePath."),sourcePath:d.string().optional().describe("Absolute path visible to the API service account, including Windows UNC paths such as \\\\server\\share\\file.bin. Provide exactly one source."),headers:d.record(d.string()).optional().describe("Optional authentication headers. Sensitive values are never returned."),fileName:d.string().optional(),path:d.string().optional().describe("Target Microi storage directory."),filePathName:d.string().optional().describe("Exact tenant-scoped target path; bucket visibility follows limit."),limit:d.boolean().optional(),preview:d.boolean().optional(),maxBytes:d.number().int().nonnegative().optional().describe("Optional caller limit in bytes. Omit or pass 0 for no MCP-level size cap."),timeoutSeconds:d.number().int().min(5).max(86400).optional().describe("HTTP transfer timeout. Default 3600 seconds."),targetTable:d.string().optional(),targetId:d.string().optional(),targetField:d.string().optional(),confirmExecution:d.string().optional().describe("Required. Pass EXECUTE, the exact source value, or its dry-run SHA-256.")},async({sourceUrl:a,sourcePath:s,headers:c,fileName:l,path:u,filePathName:p,limit:f,preview:m,maxBytes:h,timeoutSeconds:g,targetTable:y,targetId:x,targetField:b,confirmExecution:v})=>{if(!!a==!!s)return{content:[{type:"text",text:"Error: provide exactly one of sourceUrl or sourcePath."}],isError:!0};let _=a||s||"",w=nt.default.createHash("sha256").update(_,"utf8").digest("hex");if(v!==_&&v!=="EXECUTE"&&v?.toLowerCase()!==w){let C=s?"[LOCAL_OR_UNC_SOURCE]":"[INVALID_URL]";if(a)try{let E=new URL(a);C=`${E.protocol}//${E.host}/[REDACTED]`}catch{}return{content:[{type:"text",text:JSON.stringify({dryRun:!0,action:"import_external_attachment",source:C,sourceKind:s?"LocalOrUncPath":"Http",sourceSha256:w,headersProvided:!!c&&Object.keys(c).length>0,targetTable:y,targetId:x,targetField:b,requiresConfirmation:"EXECUTE, exact source, or sourceSha256"},null,2)}]}}try{let C=await t.importExternalAttachment({SourceUrl:a,SourcePath:s,Headers:c,FileName:l,Path:u,FilePathName:p,Limit:f,Preview:m,MaxBytes:h,TimeoutSeconds:g,TargetTable:y,TargetId:x,TargetField:b,ConfirmExecution:v});return C.Code!==1?{content:[{type:"text",text:`Error: ${C.Msg}`}],isError:!0}:{content:[{type:"text",text:JSON.stringify(C.Data,null,2)}]}}catch(C){return{content:[{type:"text",text:`Error: ${C instanceof Error?C.message:String(C)}`}],isError:!0}}}),i.tool("microi_get_playwright_context",`Get Playwright E2E testing context for OsClient "${r}". Returns callable API engines, anonymous/public flags, and menu routes for writing browser automation tests.`,{keyword:d.string().optional().describe("Optional keyword to filter engines/modules by name, key, route, category, or table name."),pageSize:d.number().int().min(100).max(2e4).optional().describe("Maximum number of engines/modules returned by the backend context API. Default: 5000.")},async({keyword:a,pageSize:s})=>{try{let c=await t.getPlaywrightContext(a,s);return c.Code!==1||!c.Data?{content:[{type:"text",text:`Error: ${c.Msg||"GetPlaywrightContext failed"}`}],isError:!0}:{content:[{type:"text",text:Qte(c.Data,e.apiBaseUrl)}]}}catch(c){return{content:[{type:"text",text:`Error: ${c instanceof Error?c.message:String(c)}`}],isError:!0}}}),i.tool("microi_plan_playwright_e2e",`Create a Playwright E2E starter plan for a Microi frontend connected to OsClient "${r}". Use this before scaffolding tests in a PC Vue or uni-app H5 project.`,{appType:d.enum(["pc-vue","uniapp-h5","web"]).optional().describe("Frontend type. Default: uniapp-h5."),frontendBaseUrl:d.string().optional().describe("Local frontend URL, e.g. http://127.0.0.1:5180."),homePath:d.string().optional().describe("Home route, e.g. /#/pages/index/index for uni-app H5."),loginEngineKey:d.string().optional().describe("ApiEngineKey used for login."),smokeEngineKey:d.string().optional().describe("Public ApiEngineKey used for API smoke assertion."),keyword:d.string().optional().describe("Keyword to focus context on a module or business area."),pageSize:d.number().int().min(100).max(2e4).optional().describe("Maximum number of engines/modules requested from the backend context API. Default: 5000.")},async({appType:a,frontendBaseUrl:s,homePath:c,loginEngineKey:l,smokeEngineKey:u,keyword:p,pageSize:f})=>{try{let m=await t.getPlaywrightContext(p,f),h=m.Code===1?m.Data:void 0;return{content:[{type:"text",text:ere({osClient:r,apiBaseUrl:h?.ApiBaseUrl||e.apiBaseUrl,frontendBaseUrl:s,appType:a,homePath:c,loginEngineKey:l,smokeEngineKey:u,pageSize:f,context:h})}]}}catch(m){return{content:[{type:"text",text:`Error: ${m instanceof Error?m.message:String(m)}`}],isError:!0}}}),i.tool("microi_list_engines",`List API engines (\u63A5\u53E3\u5F15\u64CE) for OsClient "${r}". Each engine is a server-side JavaScript function with V8 APIs for database queries, HTTP calls, caching, etc.`,{keyword:d.string().optional().describe("Search keyword to filter engines by name or key")},async({keyword:a})=>{try{let s=await t.getEngineList(a);if(s.Code!==1)return{content:[{type:"text",text:`Error: ${s.Msg}`}],isError:!0};let c=ir(s.Data);if(a&&(c=c.filter(u=>jn(u.ApiEngineKey,a)||jn(u.ApiName,a)||jn(u.Category,a)||jn(u.ApiRemark,a))),!c.length)return{content:[{type:"text",text:"No engines found."}]};let l=[`# API Engines (${c.length})
551
551
  `,"| # | Engine Key | Name | Category | V8 Runtime Limit | Description |","|---|-----------|------|----------|--------------|-------------|"];return c.forEach((u,p)=>{let f=u.V8Limit!==void 0&&u.V8Limit!==null?Number(u.V8Limit||0):u.V8Unlimited!==void 0&&u.V8Unlimited!==null?Number(u.V8Unlimited||0)===1?0:1:0;l.push(`| ${p+1} | ${u.ApiEngineKey||""} | ${u.ApiName||""} | ${u.Category||""} | ${f===1?"ON":"OFF"} | ${u.ApiRemark||u.Description||""} |`)}),{content:[{type:"text",text:l.join(`
552
552
  `)}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}),i.tool("microi_get_engine_code",`Get JavaScript source code of a specific API engine (OsClient: ${r}). Large source is returned in explicit character chunks so the MCP host cannot silently replace missing code with a "tokens truncated" marker. Read every chunk before editing; never save a single partial chunk as complete source.`,{apiEngineKey:d.string().describe("The unique key of the API engine"),charOffset:d.number().int().nonnegative().optional().describe("Zero-based character offset. Start with 0, then use nextCharOffset until hasMore=false."),maxChars:d.number().int().min(1e3).max(16e3).optional().describe("Characters per chunk (default 6000, max 16000).")},async({apiEngineKey:a,charOffset:s,maxChars:c})=>{try{let l=await t.getEngineCode(a);if(l.Code!==1)return{content:[{type:"text",text:`Error: ${l.Msg}`}],isError:!0};let u=l.Data,p=Vt(u,"ApiV8Code","Code","V8Code"),f=Math.min(s||0,p.length),m=c||6e3,h=Math.min(f+m,p.length),g=p.slice(f,h),y=h<p.length,x=nt.default.createHash("sha256").update(p,"utf8").digest("hex");return{content:[{type:"text",text:[`## API Engine: ${u?.ApiEngineKey||a}`,u?.ApiName?`- **Name**: ${u.ApiName}`:"",u?.Category?`- **Category**: ${u.Category}`:"",u?.ApiAddress?`- **Address**: ${u.ApiAddress}`:"",u?.ApiRoutes?`- **\u591A\u8DEF\u7531**: ${u.ApiRoutes}`:"",u?.ApiRemark?`- **Remark**: ${u.ApiRemark}`:"",`- **V8Limit**: ${u?.V8Limit!==void 0&&u?.V8Limit!==null?Number(u.V8Limit||0)===1:u?.V8Unlimited!==void 0&&u?.V8Unlimited!==null?Number(u.V8Unlimited||0)!==1:!1}`,`- **Source completeness**: ${y||f>0?"PARTIAL CHUNK \u2014 do not save this chunk alone":"COMPLETE"}`,`- **Character range**: [${f}, ${h}) of ${p.length}`,`- **Full source SHA-256**: ${x}`,y?`- **Next call**: charOffset=${h}, maxChars=${m}`:"- **Has more**: false","","```javascript",g||"// No code available","```"].filter(Boolean).join(`
553
- `)}]}}catch(l){return{content:[{type:"text",text:`Error: ${l instanceof Error?l.message:String(l)}`}],isError:!0}}}),i.tool("microi_run_engine",`\u6267\u884C\u5F53\u524D\u79DF\u6237 ${r} \u7684\u63A5\u53E3\u5F15\u64CE\uFF0C\u53EF\u80FD\u5199\u6570\u636E\u5E93\u6216\u8C03\u7528\u5916\u90E8\u63A5\u53E3\uFF0C\u5FC5\u987B\u660E\u786E\u6267\u884C\u786E\u8BA4\u3002\u6807\u51C6 stdio \u7684\u5355\u6761 JSON-RPC \u672A\u89E3\u6790\u7F13\u51B2\u4E0A\u9650\u4E3A128MiB\uFF0C\u8C03\u7528\u7AEF\u4E5F\u987B\u652F\u6301\u54CD\u5E94\u5927\u5C0F\uFF1B\u8BE5\u4F20\u8F93\u4E0A\u9650\u4E0D\u6539\u53D8\u540E\u7AEF\u4E1A\u52A1\u6216HDFS\u5305\u9650\u989D\u3002\u5B8C\u6574\u5305Base64\u8BF7\u6C42\u8981\u8BA1\u7B97\u6574\u4E2Awire\u5B57\u8282\u6570\uFF0CData/Result\u7B49\u91CD\u590D\u54CD\u5E94\u4E5F\u8BA1\u5165\uFF1B\u8D85\u9650\u8D44\u4EA7\u4F7F\u7528\u5DF2\u6709\u76EE\u5F55/\u6587\u4EF6\u6D41\u5F0F\u534F\u8BAE\uFF0C\u4E0D\u6269\u5927\u4E3A\u65E0\u9650\u7F13\u51B2\u3002`,{apiEngineKey:d.string().describe("The unique key of the API engine to execute"),params:d.record(d.unknown()).optional().describe("Optional parameters to pass to the engine (available via V8.Param in the engine code)"),confirmExecution:d.string().optional().describe("Required because engine execution may write data. Use apiEngineKey or EXECUTE.")},async({apiEngineKey:a,params:s,confirmExecution:c})=>{try{if(c!==a&&c!=="EXECUTE")return{content:[{type:"text",text:`\u6267\u884C\u5DF2\u62E6\u622A\uFF1Amicroi_run_engine \u53EF\u80FD\u4EA7\u751F\u5199\u5165\u6216\u5916\u90E8\u8C03\u7528\uFF0C\u8BF7\u91CD\u65B0\u8C03\u7528\u5E76\u4F20 confirmExecution="${a}" \u6216 "EXECUTE"\u3002`}],isError:!0};await t.writeAuditLog("microi_run_engine",a,JSON.stringify(s||{}));let l=await t.executeEngine(a,s);return{content:[{type:"text",text:[`## Execution Result: ${a}`,`- **Code**: ${l.Code}`,l.Msg?`- **Message**: ${l.Msg}`:"","","```json",JSON.stringify(l.Data,null,2),"```"].filter(Boolean).join(`
553
+ `)}]}}catch(l){return{content:[{type:"text",text:`Error: ${l instanceof Error?l.message:String(l)}`}],isError:!0}}}),i.tool("microi_run_engine",`\u6267\u884C\u5F53\u524D\u79DF\u6237 ${r} \u7684\u63A5\u53E3\u5F15\u64CE\uFF0C\u53EF\u80FD\u5199\u6570\u636E\u5E93\u6216\u8C03\u7528\u5916\u90E8\u63A5\u53E3\uFF0C\u5FC5\u987B\u660E\u786E\u6267\u884C\u786E\u8BA4\u3002\u6807\u51C6 stdio \u7684\u5355\u6761 JSON-RPC \u672A\u89E3\u6790\u7F13\u51B2\u4E0A\u9650\u4E3A128MiB\uFF0C\u8C03\u7528\u7AEF\u4E5F\u987B\u652F\u6301\u54CD\u5E94\u5927\u5C0F\uFF1B\u8BE5\u4F20\u8F93\u4E0A\u9650\u4E0D\u6539\u53D8\u540E\u7AEF\u4E1A\u52A1\u6216HDFS\u5305\u9650\u989D\u3002\u5B8C\u6574\u5305Base64\u8BF7\u6C42\u8981\u8BA1\u7B97\u6574\u4E2Awire\u5B57\u8282\u6570\uFF0CData/Result\u7B49\u91CD\u590D\u54CD\u5E94\u4E5F\u8BA1\u5165\uFF1B\u8D85\u9650\u8D44\u4EA7\u4F7F\u7528\u5DF2\u6709\u76EE\u5F55/\u6587\u4EF6\u6D41\u5F0F\u534F\u8BAE\uFF0C\u4E0D\u6269\u5927\u4E3A\u65E0\u9650\u7F13\u51B2\u3002`,{apiEngineKey:d.string().describe("The unique key of the API engine to execute"),params:d.record(d.unknown()).optional().describe("\u63A5\u53E3\u5F15\u64CE\u53C2\u6570\uFF0C\u539F\u6837\u4F20\u5165 V8.Param\u3002\u6807\u51C6\u5546\u57CE export-microi-store-package / ai_app_publish_store \u652F\u6301 SparseTableSelections:[{TableId,FieldIds}]\uFF1A\u4EC5\u9009\u65E2\u6709\u5171\u4EAB\u8868\u7684\u6743\u5A01\u5B57\u6BB5\uFF0C\u4E0D\u63A5\u53D7\u4EFB\u610F\u6B63\u6587\u8986\u76D6\uFF1BV3\u4ECD\u8981\u6C42 CommittedProof + ExpectedResourceSnapshotHash\uFF0C\u5386\u53F2\u7A00\u758F\u9009\u96C6\u5FC5\u987B\u663E\u5F0F\u5237\u65B0\u3002\u5B89\u88C5\u524D\u5148\u5347\u7EA7\u5546\u57CE\u5B89\u88C5\u5668\u5E76\u5177\u5907\u5171\u4EAB\u8868\u8D23\u4EFB\u5305\uFF0CRuntimeAssetsOnly \u7981\u6B62\u7A00\u758F\u8D44\u6E90\u3002"),confirmExecution:d.string().optional().describe("Required because engine execution may write data. Use apiEngineKey or EXECUTE.")},async({apiEngineKey:a,params:s,confirmExecution:c})=>{try{if(c!==a&&c!=="EXECUTE")return{content:[{type:"text",text:`\u6267\u884C\u5DF2\u62E6\u622A\uFF1Amicroi_run_engine \u53EF\u80FD\u4EA7\u751F\u5199\u5165\u6216\u5916\u90E8\u8C03\u7528\uFF0C\u8BF7\u91CD\u65B0\u8C03\u7528\u5E76\u4F20 confirmExecution="${a}" \u6216 "EXECUTE"\u3002`}],isError:!0};await t.writeAuditLog("microi_run_engine",a,JSON.stringify(s||{}));let l=await t.executeEngine(a,s);return{content:[{type:"text",text:[`## Execution Result: ${a}`,`- **Code**: ${l.Code}`,l.Msg?`- **Message**: ${l.Msg}`:"","","```json",JSON.stringify(l.Data,null,2),"```"].filter(Boolean).join(`
554
554
  `)}],isError:l.Code!==1}}catch(l){return{content:[{type:"text",text:`Error: ${l instanceof Error?l.message:String(l)}`}],isError:!0}}}),i.tool("microi_seed_table_data",`Seed sample/demo rows into any low-code table for OsClient "${r}". Wraps V8.FormEngine.AddTableData. Use this for filling\u5546\u54C1/\u8BA2\u5355/\u4F1A\u5458\u7B49\u6837\u4F8B\u6570\u636E\u3002Each row will get Id/CreateTime/OsClient auto-filled by the platform.`,{tableName:d.string().describe('Target diy_table name (e.g. "mall_product")'),rows:d.array(d.record(d.unknown())).describe("Array of row objects. Each object = one record. Field names must match diy_field PascalCase names."),skipIfExists:d.boolean().optional().describe("When true, skips seeding if table already has any rows. Default: false."),confirmExecution:d.string().optional().describe('Required because this writes to DB. Use tableName or "EXECUTE".')},async({tableName:a,rows:s,skipIfExists:c,confirmExecution:l})=>{try{if(l!==a&&l!=="EXECUTE")return{content:[{type:"text",text:`\u6267\u884C\u5DF2\u62E6\u622A\uFF1Amicroi_seed_table_data \u4F1A\u5199\u5165 ${s.length} \u6761\u5230\u8868 ${a}\uFF0C\u8BF7\u91CD\u65B0\u8C03\u7528\u5E76\u4F20 confirmExecution="${a}" \u6216 "EXECUTE"\u3002`}],isError:!0};await t.writeAuditLog("microi_seed_table_data",a,JSON.stringify({count:s.length,skipIfExists:!!c}));let u=await t.executeEngine("_mcp_seed_table_data",{tableName:a,rows:s,skipIfExists:!!c});return{content:[{type:"text",text:`## Seed: ${a}
555
555
  - **Code**: ${u.Code}
556
556
  - **Msg**: ${u.Msg??""}