@microi.net/cli 5.1.6 → 5.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.codebuddy-plugin/marketplace.json +2 -2
- package/.codebuddy-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.workbuddy-plugin/marketplace.json +2 -2
- package/.workbuddy-plugin/plugin.json +1 -1
- package/assets/build-meta.json +4 -4
- package/cordis.patch.yml +1 -1
- package/package.json +1 -1
- package/scripts/mcp-server.js +3 -2
- package/scripts/microi-skills.meta.json +187 -187
- package/skills/.microi-skills-version.json +2 -2
- package/skills/.progressive-disclosure-manifest.json +7 -7
- package/skills/app-store/SKILL.md +1 -1
- package/skills/microi-form-layout/SKILL.md +1 -1
- package/skills/microi-system-delivery/references/progressive-01-/346/240/207/345/207/206/345/267/245/344/275/234/346/265/201.md +3 -1
- package/skills/module-engine/SKILL.md +7 -4
- package/skills/module-engine/references/module-config.md +7 -1
- package/skills/ui-design/SKILL.md +1 -1
- package/skills/v8-security/SKILL.md +2 -2
- package/skills/v8-utilities/references/server-api-index.md +1 -0
- package/skills/v8-workflow/SKILL.md +13 -5
package/scripts/mcp-server.js
CHANGED
|
@@ -126,7 +126,7 @@ Content-Type: application/octet-stream\r
|
|
|
126
126
|
]))`;continue}}if(r.s&&n[c]==="."){i+=o?`${n[c]}\r
|
|
127
127
|
`:`[${n[c]}\r
|
|
128
128
|
]`;continue}i+=n[c],n[c]==="\\"?a=!0:o&&n[c]==="]"?o=!1:!o&&n[c]==="["&&(o=!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 vp(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]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??Ue(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:K(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}=bp(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}=yp(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function SP(t,e){if(e.mapStrategy==="record")return vp(t,e);let r=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ue(e),n=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ue(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function EP(t){let e=t.values,n=Object.keys(t.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),i=Array.from(new Set(n.map(a=>typeof a)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:n}}function kP(t){return t.target==="openAi"?void 0:{not:Ue({...t,currentPath:[...t.currentPath,"not"]})}}function TP(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ac={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function PP(t,e){if(e.target==="openApi3")return CP(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ac&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,a)=>{let o=ac[a._def.typeName];return o&&!i.includes(o)?[...i,o]: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,a)=>{let o=typeof a._def.value;switch(o){case"string":case"number":case"boolean":return[...i,o];case"bigint":return[...i,"integer"];case"object":if(a._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(n.length===r.length){let i=n.filter((a,o,s)=>s.indexOf(a)===o);return{type:i.length>1?i:i[0],enum:r.reduce((a,o)=>a.includes(o._def.value)?a:[...a,o._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,i)=>[...n,...i._def.values.filter(a=>!n.includes(a))],[])};return CP(t,e)}var CP=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>K(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 AP(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:ac[t.innerType._def.typeName],nullable:!0}:{type:[ac[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function IP(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",Gy(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?me(r,"minimum",n.value,n.message,e):me(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),me(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?me(r,"maximum",n.value,n.message,e):me(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),me(r,"maximum",n.value,n.message,e));break;case"multipleOf":me(r,"multipleOf",n.value,n.message,e);break}return r}function RP(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},i=[],a=t.shape();for(let s in a){let c=a[s];if(c===void 0||c._def===void 0)continue;let l=iB(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=K(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 o=nB(t,e);return o!==void 0&&(n.additionalProperties=o),n}function nB(t,e){if(t.catchall._def.typeName!=="ZodNever")return K(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 iB(t){try{return t.isOptional()}catch{return!0}}var $P=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ue(e)},r]}:Ue(e)};var OP=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let r=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function NP(t,e){return K(t.type._def,e)}function MP(t,e){let n={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&me(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&me(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function DP(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function zP(t){return{not:Ue(t)}}function FP(t){return Ue(t)}var jP=(t,e)=>K(t.innerType._def,e);var LP=(t,e,r)=>{switch(e){case M.ZodString:return bp(t,r);case M.ZodNumber:return IP(t,r);case M.ZodObject:return RP(t,r);case M.ZodBigInt:return mP(t,r);case M.ZodBoolean:return hP();case M.ZodDate:return Xy(t,r);case M.ZodUndefined:return zP(r);case M.ZodNull:return TP(r);case M.ZodArray:return fP(t,r);case M.ZodUnion:case M.ZodDiscriminatedUnion:return PP(t,r);case M.ZodIntersection:return xP(t,r);case M.ZodTuple:return DP(t,r);case M.ZodRecord:return vp(t,r);case M.ZodLiteral:return wP(t,r);case M.ZodEnum:return vP(t);case M.ZodNativeEnum:return EP(t);case M.ZodNullable:return AP(t,r);case M.ZodOptional:return $P(t,r);case M.ZodMap:return SP(t,r);case M.ZodSet:return MP(t,r);case M.ZodLazy:return()=>t.getter()._def;case M.ZodPromise:return NP(t,r);case M.ZodNaN:case M.ZodNever:return kP(r);case M.ZodEffects:return bP(t,r);case M.ZodAny:return Ue(r);case M.ZodUnknown:return FP(r);case M.ZodDefault:return yP(t,r);case M.ZodBranded:return yp(t,r);case M.ZodReadonly:return jP(t,r);case M.ZodCatch:return gP(t,r);case M.ZodPipeline:return OP(t,r);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(n=>{})(e)}};function K(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==uP)return s}if(n&&!r){let s=aB(n,e);if(s!==void 0)return s}let i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);let a=LP(t,t.typeName,e),o=typeof a=="function"?K(a(),e):a;if(o&&oB(t,e,o),e.postProcess){let s=e.postProcess(o,t,e);return i.jsonSchema=o,s}return i.jsonSchema=o,o}var aB=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:gp(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`),Ue(e)):e.$refStrategy==="seen"?Ue(e):void 0}},oB=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var eb=(t,e)=>{let r=dP(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:K(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Ue(r)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=K(t._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??Ue(r),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(a.title=o),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?{...a,[r.definitionPath]:n}:a:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,i].join("/"),[r.definitionPath]:{...n,[i]:a}};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 sB(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function tb(t,e){return fr(t)?Am(t,{target:sB(e?.target),io:e?.pipeStrategy??"input"}):eb(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function rb(t){let r=Kn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=hp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function nb(t,e){let r=Hn(t,e);if(!r.success)throw r.error;return r.data}var cB=6e4,xp=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(bl,r=>{this._oncancel(r)}),this.setNotificationHandler(xl,r=>{this._onprogress(r)}),this.setRequestHandler(vl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wl,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new V(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(Sl,async(r,n)=>{let i=async()=>{let a=r.params.taskId;if(this._taskMessageQueue){let s;for(;s=await this._taskMessageQueue.dequeue(a,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,d=new V(p.error.code,p.error.message,p.error.data);u(d)}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 o=await this._taskStore.getTask(a,n.sessionId);if(!o)throw new V(Z.InvalidParams,`Task not found: ${a}`);if(!Wn(o.status))return await this._waitForTaskUpdate(a,n.signal),await i();if(Wn(o.status)){let s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[Rn]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(El,async(r,n)=>{try{let{tasks:i,nextCursor:a}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:i,nextCursor:a,_meta:{}}}catch(i){throw new V(Z.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Tl,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new V(Z.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wn(i.status))throw new V(Z.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 a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new V(Z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof V?i:new V(Z.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,a=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(i,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:a,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),V.fromError(Z.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=a=>{n?.(a),this._onerror(a)};let i=this._transport?.onmessage;this._transport.onmessage=(a,o)=>{i?.(a,o),ns(a)||$w(a)?this._onresponse(a):Vm(a)?this._onrequest(a,o):Rw(a)?this._onnotification(a):this._onerror(new Error(`Unknown message type: ${JSON.stringify(a)}`))},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=V.fromError(Z.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,a=e.params?._meta?.[Rn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:Z.MethodNotFound,message:"Method not found"}};a&&this._taskMessageQueue?this._enqueueTaskMessage(a,{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 o=new AbortController;this._requestHandlerAbortControllers.set(e.id,o);let s=Pw(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,i?.sessionId):void 0,l={signal:o.signal,sessionId:i?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(o.signal.aborted)return;let p={relatedRequestId:e.id};a&&(p.relatedTask={taskId:a}),await this.notification(u,p)},sendRequest:async(u,p,d)=>{if(o.signal.aborted)throw new V(Z.ConnectionClosed,"Request was cancelled");let h={...d,relatedRequestId:e.id};a&&!h.relatedTask&&(h.relatedTask={taskId:a});let m=h.relatedTask?.taskId??a;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,p,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:a,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(o.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{type:"response",message:p,timestamp:Date.now()},i?.sessionId):await i?.send(p)},async u=>{if(o.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Z.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};a&&this._taskMessageQueue?await this._enqueueTaskMessage(a,{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)===o&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,i=Number(r),a=this._progressHandlers.get(i);if(!a){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(i),s=this._timeoutInfo.get(i);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(i)}catch(c){this._responseHandlers.delete(i),this._progressHandlers.delete(i),this._cleanupTimeout(i),o(c);return}a(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ns(e))n(e);else{let o=new V(e.error.code,e.error.message,e.error.data);n(o)}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 a=!1;if(ns(e)&&e.result&&typeof e.result=="object"){let o=e.result;if(o.task&&typeof o.task=="object"){let s=o.task;typeof s.taskId=="string"&&(a=!0,this._taskProgressTokens.set(s.taskId,r))}}if(a||this._progressHandlers.delete(r),ns(e))i(e);else{let o=V.fromError(e.error.code,e.error.message,e.error.data);i(o)}}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(o){yield{type:"error",error:o instanceof V?o:new V(Z.InternalError,String(o))}}return}let a;try{let o=await this.request(e,va,n);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new V(Z.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},Wn(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new V(Z.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new V(Z.InternalError,`Task ${a} was cancelled`)});return}if(s.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)};return}let c=s.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof V?o:new V(Z.InternalError,String(o))}}}request(e,r,n){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,task:s,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=x=>{u(x)};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(x){p(x);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),s&&(h.params={...h.params,task:s}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[Rn]:c}});let m=x=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(x)}},{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let b=x instanceof V?x:new V(Z.RequestTimeout,String(x));u(b)};this._responseHandlers.set(d,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return u(x);try{let b=Hn(r,x.result);b.success?l(b.data):u(b.error)}catch(b){u(b)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let g=n?.timeout??cB,y=()=>m(V.fromError(Z.RequestTimeout,"Request timed out",{timeout:g}));this._setupTimeout(d,g,n?.maxTotalTimeout,y,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let x=b=>{let S=this._responseHandlers.get(d);S?S(b):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,x),this._enqueueTaskMessage(v,{type:"request",message:h,timestamp:Date.now()}).catch(b=>{this._cleanupTimeout(d),u(b)})}else this._transport.send(h,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(x=>{this._cleanupTimeout(d),u(x)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},_l,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},kl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Nw,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||{},[Rn]: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||{},[Rn]:r.relatedTask}}}),this._transport?.send(s,r).catch(c=>this._onerror(c))});return}let o={...e,jsonrpc:"2.0"};r?.relatedTask&&(o={...o,params:{...o.params,_meta:{...o.params?._meta||{},[Rn]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=rb(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=nb(e,i);return Promise.resolve(r(o,a))})}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=rb(e);this._notificationHandlers.set(n,i=>{let a=nb(e,i);return Promise.resolve(r(a))})}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"&&Vm(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new V(Z.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(a)):this._onerror(new Error(`Resolver missing for request ${a} 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,a)=>{if(r.aborted){a(new V(Z.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),a(new V(Z.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 a=await n.getTask(i,r);if(!a)throw new V(Z.InvalidParams,"Failed to retrieve task: Task not found");return a},storeTaskResult:async(i,a,o)=>{await n.storeTaskResult(i,a,o,r);let s=await n.getTask(i,r);if(s){let c=cs.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Wn(s.status)&&this._cleanupTaskProgressHandler(i)}},getTaskResult:i=>n.getTaskResult(i,r),updateTaskStatus:async(i,a,o)=>{let s=await n.getTask(i,r);if(!s)throw new V(Z.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Wn(s.status))throw new V(Z.InvalidParams,`Cannot update task "${i}" from terminal status "${s.status}" to "${a}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(i,a,o,r);let c=await n.getTask(i,r);if(c){let l=cs.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Wn(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function VP(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function qP(t,e){let r={...t};for(let n in e){let i=n,a=e[i];if(a===void 0)continue;let o=r[i];VP(o)&&VP(a)?r[i]={...o,...a}:r[i]=a}return r}var PI=$e(qv(),1),AI=$e(CI(),1);function QH(){let t=new PI.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,AI.default)(t),t}var rd=class{constructor(e){this._ajv=e??QH()}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 nd=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],a=Array.isArray(i.content)?i.content:[i.content],o=a.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(o){if(a.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(d=>d.type==="tool_use").map(d=>d.id)),p=new Set(a.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==p.size||![...u].every(d=>p.has(d)))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},ps,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 a=i==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:a},_a,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 II(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 RI(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 id=class extends xp{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(us.options.map((n,i)=>[n,i])),this.isMessageIgnored=(n,i)=>{let a=this._loggingLevels.get(i);return a?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(a):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new rd,this.setRequestHandler(Um,n=>this._oninitialize(n)),this.setNotificationHandler(Zm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ym,async(n,i)=>{let a=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=n.params,s=us.safeParse(o);return s.success&&this._loggingLevels.set(a,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new nd(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=qP(this._capabilities,e)}setRequestHandler(e,r){let i=Kn(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(fr(i)){let s=i;a=s._zod?.def?.value??s.value}else{let s=i;a=s._def?.value??s.value}if(typeof a!="string")throw new Error("Schema method literal must be a string");if(a==="tools/call"){let s=async(c,l)=>{let u=Hn(wa,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new V(Z.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,d=await Promise.resolve(r(c,l));if(p.task){let m=Hn(va,d);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new V(Z.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let h=Hn(Ol,d);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new V(Z.InvalidParams,`Invalid tools/call result: ${m}`)}return h.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){RI(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&II(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:kw.includes(r)?r:jm,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"},yl)}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],a=i.some(l=>l.type==="tool_result"),o=e.messages.length>1?e.messages[e.messages.length-2]:void 0,s=o?Array.isArray(o.content)?o.content:[o.content]:[],c=s.some(l=>l.type==="tool_use");if(a){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},Qm,r):this.request({method:"sampling/createMessage",params:e},ps,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},_a,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"},a=await this.request({method:"elicitation/create",params:i},_a,r);if(a.action==="accept"&&a.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!s.valid)throw new V(Z.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(o){throw o instanceof V?o:new V(Z.InternalError,`Error validating elicitation response: ${o instanceof Error?o.message:String(o)}`)}return a}}}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},eh,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 OI=Symbol.for("mcp.completable");function Gv(t){return!!t&&typeof t=="object"&&OI in t}function NI(t){return t[OI]?.complete}var $I;(function(t){t.Completable="McpCompletable"})($I||($I={}));var ad=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,a=0;for(;i<e.length;)if(e[i]==="{"){n&&(r.push(n),n="");let o=e.indexOf("}",i);if(o===-1)throw new Error("Unclosed template expression");if(a++,a>1e4)throw new Error("Template contains too many expressions (max 10000)");let s=e.slice(i+1,o),c=this.getOperator(s),l=s.includes("*"),u=this.getNames(s),p=u[0];for(let d of u)t.validateLength(d,1e6,"Variable name");r.push({name:p,operator:c,names:u,exploded:l}),i=o+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 o=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 o.length===0?"":(e.operator==="?"?"?":"&")+o.join("&")}if(e.names.length>1){let o=e.names.map(s=>r[s]).filter(s=>s!==void 0);return o.length===0?"":o.map(s=>Array.isArray(s)?s[0]:s).join(",")}let n=r[e.name];if(n===void 0)return"";let a=(Array.isArray(n)?n:[n]).map(o=>this.encodeValue(o,e.operator));switch(e.operator){case"":return a.join(",");case"+":return a.join(",");case"#":return"#"+a.join(",");case".":return"."+a.join(".");case"/":return"/"+a.join("/");default:return a.join(",")}}expand(e){let r="",n=!1;for(let i of this.parts){if(typeof i=="string"){r+=i;continue}let a=this.expandPart(i,e);a&&((i.operator==="?"||i.operator==="&")&&n?r+=a.replace("?","&"):r+=a,(i.operator==="?"||i.operator==="&")&&(n=!0))}return r}escapeRegExp(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}partToRegExp(e){let r=[];for(let a of e.names)t.validateLength(a,1e6,"Variable name");if(e.operator==="?"||e.operator==="&"){for(let a=0;a<e.names.length;a++){let o=e.names[a],s=a===0?"\\"+e.operator:"&";r.push({pattern:s+this.escapeRegExp(o)+"=([^&]+)",name:o})}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),a=e.match(i);if(!a)return null;let o={};for(let s=0;s<n.length;s++){let{name:c,exploded:l}=n[s],u=a[s+1],p=c.replace("*","");l&&u.includes(",")?o[p]=u.split(","):o[p]=u}return o}};var eK=/^[A-Za-z0-9._-]{1,128}$/;function tK(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"),!eK.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,i,a)=>a.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 rK(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 Xv(t){let e=tK(t);return rK(t,e.warnings),e.isValid}var od=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 sd=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 id(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new od(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ii($l)),this.server.assertCanSetRequestHandler(ii(wa)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler($l,()=>({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=so(r.inputSchema);return i?tb(i,{strictUnions:!0,pipeStrategy:"input"}):nK})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let i=so(r.outputSchema);i&&(n.outputSchema=tb(i,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(wa,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new V(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new V(Z.InvalidParams,`Tool ${e.params.name} disabled`);let i=!!e.params.task,a=n.execution?.taskSupport,o="createTask"in n.handler;if((a==="required"||a==="optional")&&!o)throw new V(Z.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!i)throw new V(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(a==="optional"&&!i&&o)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 V&&n.code===Z.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 a=so(e.inputSchema)??e.inputSchema,o=await fp(a,r);if(!o.success){let s="error"in o?o.error:"Unknown error",c=mp(s);throw new V(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return o.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new V(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let i=so(e.outputSchema),a=await fp(i,r.structuredContent);if(!a.success){let o="error"in a?a.error:"Unknown error",s=mp(o);throw new V(Z.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 o={...n,taskStore:n.taskStore};if(e.inputSchema){let s=i;return await Promise.resolve(s.createTask(r,o))}else{let s=i;return await Promise.resolve(s.createTask(o))}}if(e.inputSchema){let o=i;return await Promise.resolve(o(r,n))}else{let o=i;return await Promise.resolve(o(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),a=e.handler,o={...n,taskStore:n.taskStore},s=i?await Promise.resolve(a.createTask(i,o)):await Promise.resolve(a.createTask(o)),c=s.task.taskId,l=s.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(d=>setTimeout(d,u));let p=await n.taskStore.getTask(c);if(!p)throw new V(Z.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ii(Nl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Nl,async e=>{switch(e.params.ref.type){case"ref/prompt":return Lw(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Vw(e),this.handleResourceCompletion(e,e.params.ref);default:throw new V(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new V(Z.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new V(Z.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Mc;let a=Kn(n.argsSchema)?.[e.params.argument.name];if(!Gv(a))return Mc;let o=NI(a);if(!o)return Mc;let s=await o(e.params.argument.value,e.params.context);return DI(s)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(o=>o.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Mc;throw new V(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=n.resourceTemplate.completeCallback(e.params.argument.name);if(!i)return Mc;let a=await i(e.params.argument.value,e.params.context);return DI(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ii(Cl)),this.server.assertCanSetRequestHandler(ii(Pl)),this.server.assertCanSetRequestHandler(ii(Al)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Cl,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([a,o])=>o.enabled).map(([a,o])=>({uri:a,name:o.name,...o.metadata})),i=[];for(let a of Object.values(this._registeredResourceTemplates)){if(!a.resourceTemplate.listCallback)continue;let o=await a.resourceTemplate.listCallback(r);for(let s of o.resources)i.push({...a.metadata,...s})}return{resources:[...n,...i]}}),this.server.setRequestHandler(Pl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Al,async(e,r)=>{let n=new URL(e.params.uri),i=this._registeredResources[n.toString()];if(i){if(!i.enabled)throw new V(Z.InvalidParams,`Resource ${n} disabled`);return i.readCallback(n,r)}for(let a of Object.values(this._registeredResourceTemplates)){let o=a.resourceTemplate.uriTemplate.match(n.toString());if(o)return a.readCallback(n,o,r)}throw new V(Z.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ii(Il)),this.server.assertCanSetRequestHandler(ii(Rl)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Il,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?iK(r.argsSchema):void 0}))})),this.server.setRequestHandler(Rl,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new V(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new V(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let i=so(n.argsSchema),a=await fp(i,e.params.arguments);if(!a.success){let c="error"in a?a.error:"Unknown error",l=mp(c);throw new V(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let o=a.data,s=n.callback;return await Promise.resolve(s(o,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 a=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,void 0,r,i,a);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,void 0,r,i,a);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}registerResource(e,r,n,i){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let a=this._createRegisteredResource(e,n.title,r,n,i);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,n.title,r,n,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),a}}_createRegisteredResource(e,r,n,i,a){let o={name:e,title:r,metadata:i,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({uri:null}),update:s=>{typeof s.uri<"u"&&s.uri!==n&&(delete this._registeredResources[n],s.uri&&(this._registeredResources[s.uri]=o)),typeof s.name<"u"&&(o.name=s.name),typeof s.title<"u"&&(o.title=s.title),typeof s.metadata<"u"&&(o.metadata=s.metadata),typeof s.callback<"u"&&(o.readCallback=s.callback),typeof s.enabled<"u"&&(o.enabled=s.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=o,o}_createRegisteredResourceTemplate(e,r,n,i,a){let o={resourceTemplate:n,title:r,metadata:i,readCallback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=o)),typeof l.title<"u"&&(o.title=l.title),typeof l.template<"u"&&(o.resourceTemplate=l.template),typeof l.metadata<"u"&&(o.metadata=l.metadata),typeof l.callback<"u"&&(o.readCallback=l.callback),typeof l.enabled<"u"&&(o.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=o;let s=n.uriTemplate.variableNames;return Array.isArray(s)&&s.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),o}_createRegisteredPrompt(e,r,n,i,a){let o={title:r,description:n,argsSchema:i===void 0?void 0:Wi(i),callback:a,enabled:!0,disable:()=>o.update({enabled:!1}),enable:()=>o.update({enabled:!0}),remove:()=>o.update({name:null}),update:s=>{typeof s.name<"u"&&s.name!==e&&(delete this._registeredPrompts[e],s.name&&(this._registeredPrompts[s.name]=o)),typeof s.title<"u"&&(o.title=s.title),typeof s.description<"u"&&(o.description=s.description),typeof s.argsSchema<"u"&&(o.argsSchema=Wi(s.argsSchema)),typeof s.callback<"u"&&(o.callback=s.callback),typeof s.enabled<"u"&&(o.enabled=s.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=o,i&&Object.values(i).some(c=>{let l=c instanceof Bt?c._def?.innerType:c;return Gv(l)})&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,r,n,i,a,o,s,c,l){Xv(e);let u={title:r,description:n,inputSchema:MI(i),outputSchema:MI(a),annotations:o,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"&&Xv(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=Wi(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Wi(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,a,o;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Yv(c))i=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Yv(r[0])&&(o=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`);o=r.shift()}}let s=r[0];return this._createRegisteredTool(e,void 0,n,i,a,o,{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:a,inputSchema:o,outputSchema:s,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,i,a,o,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 a=r[0],o=this._createRegisteredPrompt(e,void 0,n,i,a);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:i,description:a,argsSchema:o}=r,s=this._createRegisteredPrompt(e,i,a,o,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()}},cd=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new ad(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},nK={type:"object",properties:{}};function zI(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function FI(t){return"_def"in t||"_zod"in t||zI(t)}function Yv(t){return typeof t!="object"||t===null||FI(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(zI)}function MI(t){if(t){if(Yv(t))return Wi(t);if(!FI(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function iK(t){let e=Kn(t);return e?Object.entries(e).map(([r,n])=>{let i=sP(n),a=cP(n);return{name:r,description:i,required:!a}}):[]}function ii(t){let r=Kn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=hp(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function DI(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Mc={completion:{values:[],hasMore:!1}};var Qe=$e(require("node:crypto"),1),yt=$e(require("node:fs"),1),_t=$e(require("node:path"),1);var Qv=$e(require("node:crypto"),1),ai=$e(require("node:fs"),1),rr=$e(require("node:path"),1),ex=100*1024*1024,tx=Math.ceil(ex/3)*4+512,aK=new Set([".pdf",".png",".jpg",".jpeg",".gif",".bmp",".tif",".tiff",".webp"]);function jI(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=rr.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=rr.default.extname(r).toLowerCase();if(n&&!aK.has(n))throw new Error("OCR \u4EC5\u652F\u6301 PDF\u3001PNG\u3001JPEG\u3001GIF\u3001BMP\u3001TIFF \u6216 WebP \u6587\u4EF6\u3002");return r}function oK(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>tx)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>ex)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 rx(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=jI(t.fileName);if(e){let a=String(t.filePath).trim();if(!rr.default.isAbsolute(a))throw new Error("filePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let o=ai.default.lstatSync(a);if(o.isSymbolicLink())throw new Error("filePath \u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\u3002");if(!o.isFile())throw new Error("filePath \u5FC5\u987B\u6307\u5411\u666E\u901A\u6587\u4EF6\u3002");if(o.size<=0||o.size>ex)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=jI(rr.default.basename(a));if(!s||!rr.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=ai.default.readFileSync(a),n.length!==o.size)throw new Error("OCR \u6587\u4EF6\u5728\u8BFB\u53D6\u671F\u95F4\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002")}else n=oK(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:Qv.default.createHash("sha256").update(n).digest("hex"),auditFileName:i||"(unnamed OCR input)"}}function nx(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 a=r;return i.Pages=(t.Pages||[]).map(o=>{let s=String(o.Text||""),c=s.slice(0,a);return a=Math.max(0,a-c.length),c.length<s.length&&(i.TextTruncated=!0),{PageIndex:o.PageIndex,Text:c,AverageConfidence:o.AverageConfidence,...e.includeRegions?{Regions:o.Regions||[]}:{}}}),i}var ix=20*1024*1024,sK=25*1024*1024,ax=2*1024*1024,ox=Math.ceil(ix/3)*4+512,cK=new Set([".txt",".html",".htm",".odt",".odp",".docx",".pptx",".xlsx",".epub",".pdf"]);function LI(t){let e=String(t||"").trim();if(!e||e.includes("\0"))throw new Error("fileName \u65E0\u6548\u3002");let r=rr.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(!cK.has(rr.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 lK(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>ox)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>ix||i.toString("base64").replace(/=+$/u,"")!==n.replace(/=+$/u,""))throw new Error("fileByteBase64 \u65E0\u6548\u6216\u8D85\u8FC7 20 MB\u3002");return i}function sx(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 a=String(t.filePath).trim();if(!rr.default.isAbsolute(a))throw new Error("filePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let o=ai.default.lstatSync(a);if(o.isSymbolicLink()||!o.isFile())throw new Error("filePath \u5FC5\u987B\u6307\u5411\u975E\u7B26\u53F7\u94FE\u63A5\u7684\u666E\u901A\u6587\u4EF6\u3002");if(o.size<=0||o.size>ix)throw new Error("\u7FFB\u8BD1\u6587\u4EF6\u5FC5\u987B\u5927\u4E8E 0 \u5B57\u8282\u4E14\u4E0D\u8D85\u8FC7 20 MB\u3002");if(i=LI(t.fileName||rr.default.basename(a)),n=ai.default.readFileSync(a),n.length!==o.size)throw new Error("\u7FFB\u8BD1\u6587\u4EF6\u5728\u8BFB\u53D6\u671F\u95F4\u53D1\u751F\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u3002")}else i=LI(t.fileName),n=lK(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:Qv.default.createHash("sha256").update(n).digest("hex"),auditFileName:i}}function cx(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>sK||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 VI(t,e){let r=String(t||"").trim(),n=rr.default.resolve(r);if(!rr.default.isAbsolute(r))throw new Error("outputFilePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");if(ai.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=ai.default.lstatSync(rr.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 ai.default.writeFileSync(n,e,{flag:"wx"}),n}var ud={gutter:0,mask:!1,drag:!1,left:!1,hover:!1,shadow:!0,link:!0,watermark:!1,mobile:!1,dark:!1,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 se(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}var uK=new Set(["true","false","axis","item","none","vertical","horizontal"]);function pK(t){if(typeof t!="string")return"";let e=t.trim();return e?uK.has(e.toLowerCase())?"":e:""}function Po(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 qI(t,e){return{...t,...se(e)}}function pd(){return Math.floor(Math.random()*8e4+1e4)}function dK(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 a={sort:t,label:e,type:r,value:n};return i&&(a.typeOptions=i),a}var fK=[{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 mK(){return{prop:"period",label:"\u7EDF\u8BA1\u5468\u671F",type:"select",value:"month",defaultValue:"month",remote:!1,options:fK.map(t=>({...t}))}}function sa(t){let e=Array.isArray(t)?t.map(n=>se(n)).filter(n=>Object.keys(n).length):[];return e.some(n=>n.prop==="period"||n.prop==="_period")?e:[mK(),...e]}function ZI(t){return{...t,searchData:sa(t.searchData)}}function hK(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=se(e[n]);Object.keys(i).length&&(i.value=!0,e[n]=i)}}function ux(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 BI(t,e,r){return ux(se(t[e]).value,r)}function ld(t,e){return se(t[e]).value===!0}function gK(t){let e=Array.isArray(t.widgetParams)?t.widgetParams:[],r=se(e[0]),n=se(r.typeOptions).dataJson;if(Array.isArray(n))return n.length;let i=se(n);return Array.isArray(i.data)?i.data.length:Array.isArray(i.bodyData)?i.bodyData.length:0}function yK(t){let e=oi(t,"type"),r=Array.isArray(t.widgetParams)?t.widgetParams:[],n=gK(t);if(e==="statistic"){let i=Math.min(24,Math.max(1,BI(r,1,6))),a=Math.max(1,Math.floor(24/i)),o=Math.max(1,Math.ceil(Math.max(n,1)/a)),s=ld(r,18)||ld(r,19)?44:0;return Math.max(190,s+o*88+18)}if(e==="progress"){let i=Math.min(24,Math.max(1,BI(r,1,12))),a=Math.max(1,Math.floor(24/i)),o=Math.max(1,Math.ceil(Math.max(n,1)/a)),s=ld(r,26)||ld(r,27)?44:0;return Math.max(180,s+o*108+24)}return 0}function bK(t,e,r){let n=yK(t);if(!n)return 0;let i=se(t.widgetOption);return ux(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 vK(t,e,r){return{number:pd(),wrapperNumber:t,span:e,offset:0,push:0,pull:0,height:r,marginTop:0,dynamicStyle:{padding:"8px",backgroundColor:""}}}function xK(t,e){return[D(0,"Data source","textarea","",{rows:3,dataJson:{data:t,searchData:sa([])}}),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")]}function lx(t,e,r,n=""){let i=ZI(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"),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 wK(t){return[D(0,"Data source","textarea","",{rows:3,dataJson:ZI(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 To(t,e,r,n,i,a){return{type:t,label:e,category:0,show:1,icon:"",img:"",widgetOption:vK(r,n,i),widgetParams:a}}function Co(t,e,r,n,i){let a=pd();return{type:"pannel",label:"Card",hidden:!1,icon:"",img:"",wrapperOption:{number:a,gutter:0,span:e,offset:0,push:0,pull:0,height:r,marginTop:0,margin:"0px 10px 10px 0px",pannelColor:i?"#111827":"#ffffff",dynamicStyle:{padding:"12px",backgroundColor:i?"#111827":"#ffffff"},titleOption:{hidden:!0,title:t,dynamicStyle:{textAlign:"left",padding:"0px",height:"22px",lineHeight:"22px",fontSize:"14px",color:i?"#e5e7eb":"#111827"},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(a)}}function px(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 JI(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 _K(t){let e=t.prompt||"",r=px(e,t.theme),n=/dark|深色|黑色|大屏|驾驶舱/.test(`${e} ${t.style||""}`.toLowerCase()),i=JI(r),a=t.title||i.title,o=t.desc||i.subtitle;return{formConfig:{...ud,dark:n,title:a,dynamicStyle:{padding:"12px 0 0 0",backgroundColor:n?"#0f172a":"#f3f4f6",opacity:1}},wrapperList:[Co(a,24,120,c=>[To("workbench","Workbench",c,24,90,[D(0,"Data source","textarea","",{rows:3,dataJson:{icon:"",title:a,subTitle:o}})])],n),Co("\u6838\u5FC3\u6307\u6807",24,220,c=>[To("statistic","Statistic",c,24,190,xK(i.stats,n))],n),Co("\u8D8B\u52BF\u5206\u6790",12,340,c=>[To("bar","Bar Chart",c,24,300,lx("bar",{xAxis:i.xAxis,series:i.barSeries,searchData:[]},"\u4E1A\u52A1\u8D8B\u52BF",""))],n),Co("\u7ED3\u6784\u5360\u6BD4",12,340,c=>[To("pie","Pie Chart",c,24,300,lx("pie",{data:i.pieData,searchData:[]},"\u5206\u7C7B\u5360\u6BD4",""))],n),Co("\u6548\u7387\u8D70\u52BF",12,340,c=>[To("line","Line Chart",c,24,300,lx("line",{xAxis:i.xAxis,series:i.lineSeries,searchData:[]},"\u6548\u7387\u8D70\u52BF",""))],n),Co("\u91CD\u70B9\u660E\u7EC6",12,340,c=>[To("tabel","Table",c,24,300,wK({headerData:i.tableHeaders,bodyData:i.tableRows,total:i.tableRows.length,searchData:[]}))],n)]}}function Ye(t,e,r,n,i,a={}){return{options:{left:t,top:e,width:r,height:n,title:i,fontSize:9,lineHeight:n,...a},printElementType:{title:"Text",type:"text"}}}function UI(t,e,r){return{options:{left:t,top:e,width:r,height:1,borderStyle:"solid"},printElementType:{title:"Line",type:"hline"}}}function SK(t,e,r,n){return{options:{left:t,top:e,width:r,height:n,borderWidth:1},printElementType:{title:"Rect",type:"rect"}}}function EK(t){return px(t)}function kK(t){let e=EK(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}]],a=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"}]},o=[Ye(40,18,520,24,r,{fontSize:18,fontWeight:"700",textAlign:"center",lineHeight:24}),UI(36,50,535),Ye(42,66,76,16,e==="maintenance"?"\u5DE5\u5355\u53F7":"\u5355\u636E\u53F7",{fontWeight:"600"}),Ye(118,66,160,16,"",{field:e==="maintenance"?"WorkOrderNo":"BillNo",testData:e==="maintenance"?a.WorkOrderNo:a.BillNo}),Ye(320,66,76,16,"\u65E5\u671F",{fontWeight:"600"}),Ye(396,66,160,16,"",{field:e==="maintenance"?"ServiceDate":"BillDate",testData:e==="maintenance"?a.ServiceDate:a.BillDate}),Ye(42,92,76,16,"\u5BA2\u6237",{fontWeight:"600"}),Ye(118,92,160,16,"",{field:"CustomerName",testData:a.CustomerName}),Ye(320,92,76,16,"\u8054\u7CFB\u4EBA",{fontWeight:"600"}),Ye(396,92,160,16,"",{field:"ContactName",testData:a.ContactName}),Ye(42,118,76,16,e==="maintenance"?"\u8BBE\u5907":"\u8D1F\u8D23\u4EBA",{fontWeight:"600"}),Ye(118,118,160,16,"",{field:e==="maintenance"?"DeviceName":"OwnerName",testData:e==="maintenance"?a.DeviceName:a.OwnerName}),Ye(320,118,76,16,e==="maintenance"?"\u5DE5\u7A0B\u5E08":"\u5236\u5355\u4EBA",{fontWeight:"600"}),Ye(396,118,160,16,"",{field:e==="maintenance"?"EngineerName":"OwnerName",testData:e==="maintenance"?a.EngineerName:a.OwnerName}),SK(38,150,535,70),Ye(48,160,70,16,e==="maintenance"?"\u6545\u969C\u63CF\u8FF0":"\u6458\u8981",{fontWeight:"600"}),Ye(118,160,430,46,"",{field:e==="maintenance"?"FaultDesc":"Summary",testData:e==="maintenance"?a.FaultDesc:a.Summary,lineHeight:18}),Ye(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"}},Ye(42,392,76,16,e==="maintenance"?"\u5904\u7406\u65B9\u6848":"\u5907\u6CE8",{fontWeight:"600"}),Ye(118,392,430,38,"",{field:e==="maintenance"?"Solution":"Summary",testData:e==="maintenance"?a.Solution:a.Summary,lineHeight:18}),UI(36,468,535),Ye(60,492,120,16,"\u5BA2\u6237\u7B7E\u5B57\uFF1A"),Ye(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:o}]},printObj:a}}function oa(t){let e=Po(t);if(!e.ok)return t;let r=e.value;if(typeof r=="string"){let a=Po(r);a.ok&&(r=a.value)}let n=se(r);if(n.JsonObj!==void 0)return oa(n.JsonObj);if(n.jsonObj!==void 0)return oa(n.jsonObj);if(n.JsonStr!==void 0)return oa(n.JsonStr);if(n.jsonStr!==void 0)return oa(n.jsonStr);let i=se(n.formData??n.FormData);if(Object.keys(i).length){if(i.JsonObj!==void 0)return oa(i.JsonObj);if(i.jsonObj!==void 0)return oa(i.jsonObj);if(i.formConfig!==void 0||i.wrapperList!==void 0)return i}return r}function TK(t,e,r){let n=oi(t,"type");if(!Array.isArray(t.widgetParams)||t.widgetParams.length===0)return;let i=t.widgetParams,a={bar:[5,6],line:[5,6],linebar:[5,6],pie:[5,6],funnel:[3,4]};for(let l of a[n]??[]){let u=se(i[l]);if(!Object.keys(u).length||u.value===void 0||u.value==="")continue;let p=pK(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 o=se(i[0]),s={rows:3,...se(o.typeOptions)},c=s.dataJson;if(["statistic","pie","funnel","progress"].includes(n))if(Array.isArray(c))s.dataJson={data:c,searchData:sa([])},r.push(`${e}.widgetParams[0].typeOptions.dataJson array was wrapped as {data, searchData}.`);else{let l=se(c);s.dataJson={...l,data:Array.isArray(l.data)?l.data:[],searchData:sa(l.searchData)}}if(["bar","line","linebar"].includes(n)){let l=se(s.dataJson);s.dataJson={...l,xAxis:Array.isArray(l.xAxis)?l.xAxis:[],series:Array.isArray(l.series)?l.series:[],searchData:sa(l.searchData)}}if(n==="tabel")if(Array.isArray(c))s.dataJson={headerData:[],bodyData:c,total:c.length,searchData:sa([])},r.push(`${e}.widgetParams[0].typeOptions.dataJson array was wrapped as table bodyData.`);else{let l=se(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:sa(l.searchData)}}hK(n,i),o.typeOptions=s,i[0]=o,t.widgetParams=i}function Sn(t){let e=oa(t),r=Po(e);if(!r.ok)return{ok:!1,errors:[`JsonObj is not valid JSON: ${r.error}`],warnings:[]};let n=se(r.value),i=[],a=[];Object.keys(n).length||i.push("JsonObj must be an object."),n.formConfig!==void 0&&Object.keys(se(n.formConfig)).length===0&&a.push("formConfig is empty; defaults were applied."),n.wrapperList!==void 0&&!Array.isArray(n.wrapperList)&&i.push("JsonObj.wrapperList must be an array.");let o=Array.isArray(n.wrapperList)?n.wrapperList.map((c,l)=>{let u=se(c);oi(u,"type")||(u.type="pannel"),oi(u,"label")||(u.label="Card"),u.hidden===void 0&&(u.hidden=!1),u.icon=u.icon??"",u.img=u.img??"",u.wrapperOption=qI({number:pd(),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((d,h)=>{let m=se(d);oi(m,"type")||i.push(`wrapperList[${l}].widgetList[${h}].type is required.`),m.label=m.label??m.type??"Widget",m.category=m.category??0,m.show=m.show??1,m.icon=m.icon??"",m.img=m.img??"",m.widgetOption=qI({number:pd(),wrapperNumber:se(u.wrapperOption).number,span:24,offset:0,push:0,pull:0,height:260,marginTop:0,dynamicStyle:{padding:"8px",backgroundColor:""}},m.widgetOption),Array.isArray(m.widgetParams)||(m.widgetParams=[D(0,"Data source","textarea","",{rows:3,dataJson:{}})],a.push(`wrapperList[${l}].widgetList[${h}].widgetParams was missing and a safe data param was added.`));let g=`wrapperList[${l}].widgetList[${h}]`;return TK(m,g,a),p=Math.max(p,bK(m,g,a)),m}):(u.widgetList=[],a.push(`wrapperList[${l}].widgetList was missing and was set to an empty array.`)),p>0){let d=se(u.wrapperOption),h=p+16;ux(d.height,0)<h&&(d.height=h,u.wrapperOption=d,a.push(`wrapperList[${l}].wrapperOption.height was raised to ${h} to fit content widgets.`))}return u}):[];Array.isArray(n.wrapperList)||a.push("wrapperList was missing and was set to an empty array.");let s={formConfig:{...ud,...se(n.formConfig),dynamicStyle:{...se(ud.dynamicStyle),...se(se(n.formConfig).dynamicStyle)},watermarkStyle:{...se(ud.watermarkStyle),...se(se(n.formConfig).watermarkStyle)}},wrapperList:o};return{ok:i.length===0,value:s,json:JSON.stringify(s),errors:i,warnings:a}}function CK(t){let e=Po(t);if(!e.ok)return t;let r=e.value,n=se(r);return n.PageObj!==void 0?r=n.PageObj:n.pageObj!==void 0&&(r=n.pageObj),r}function ca(t){let e=CK(t),r=Po(e);if(!r.ok)return{ok:!1,errors:[`PageObj is not valid JSON: ${r.error}`],warnings:[]};let n=se(r.value),i=[],a=[];Array.isArray(n.panels)||i.push("PageObj.panels must be an array.");let o=Array.isArray(n.panels)?n.panels.map((s,c)=>{let l=se(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=[],a.push(`panels[${c}].printElements was missing and was set to an empty array.`)),l.printElements=l.printElements.map((u,p)=>{let d=se(u);return oi(se(d.printElementType),"type")||i.push(`panels[${c}].printElements[${p}].printElementType.type is required.`),d.options=se(d.options),d}),l}):[];return o.length===0&&i.push("PageObj.panels must contain at least one panel."),{ok:i.length===0,value:{...n,panels:o},json:JSON.stringify({...n,panels:o}),errors:i,warnings:a}}function la(t){if(t==null||t==="")return{ok:!0,value:{},json:"{}",errors:[],warnings:[]};let e=Po(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 oi(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 HI(t){let e=JI(px(t.prompt||"",t.theme)),r=t.title||e.title,n=_K({...t,title:r});return{title:r,number:t.number||dK(r),desc:t.desc||e.subtitle||oi(se(n.formConfig),"title")||"",jsonObj:n,jsonStr:JSON.stringify(n)}}function KI(t){let e=kK(t),r=Array.isArray(e.pageObj.panels)?e.pageObj.panels:[],n=t.title||oi(se(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 WI="/* MICROI_WF_LINE_CONDITION_JSON",PK="MICROI_WF_LINE_CONDITION_JSON */",$t=f.record(f.unknown());function W(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}function ee(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function fd(t){return Array.isArray(t)?t.map(ee).filter(e=>Object.keys(e).length>0):[]}function ce(t,...e){for(let r of e){let n=t[r];if(Array.isArray(n))return fd(n)}return[]}function _(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 ie(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 Ro(t,...e){for(let r of e){let n=t[r];if(Array.isArray(n))return n.map(i=>typeof i=="string"?i:_(ee(i),"name","Name","id","Id")).filter(Boolean);if(typeof n=="string"&&n.trim())return n.split(/[,,;;]/).map(i=>i.trim()).filter(Boolean)}return[]}function Gt(t,...e){for(let r of e)if(Object.prototype.hasOwnProperty.call(t,r))return t[r]}function Ie(t){return t.trim().toLowerCase()}function lR(t,e){return`${Ie(t)}::${Ie(e)}`}function Ex(t){return["Id","CreateTime","UpdateTime","CreateUserId","CreateUserName","UpdateUserId","UpdateUserName","OsClient","IsDeleted"].some(e=>e.toLowerCase()===t.toLowerCase())}function AK(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=Gt(t,r);if(n==null||n==="")continue;return(Array.isArray(n)?n:typeof n=="string"?AK(n):[n]).map(a=>{if(typeof a=="string"||typeof a=="number"||typeof a=="boolean")return{ref:String(a).trim()};let o=ee(a);return{ref:_(o,"field","Field","fieldName","FieldName","name","Name","id","Id","fieldId","FieldId"),asName:_(o,"asName","AsName","alias","Alias")||void 0,type:_(o,"type","Type")||void 0,displayType:_(o,"displayType","DisplayType")||void 0,displaySelect:typeof o.displaySelect=="boolean"?o.displaySelect:typeof o.DisplaySelect=="boolean"?o.DisplaySelect:void 0,equal:typeof o.equal=="boolean"?o.equal:typeof o.Equal=="boolean"?o.Equal:void 0}}).filter(a=>a.ref)}return[]}function IK(){return{byTableAndRef:new Map,fieldsByTable:new Map}}function uR(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(lR(i,s),e);let a=Ie(i),o=t.fieldsByTable.get(a)||[];o.some(s=>s.id===e.id||Ie(s.name)===Ie(e.name))||(o.push(e),t.fieldsByTable.set(a,o))}}function GI(t,e,r){if(!(!e||!r))return t.byTableAndRef.get(lR(e,r))}function $o(t,e){return t.fieldsByTable.get(Ie(e))||[]}function pR(t,e,r){return{id:r,name:r,label:r,tableId:t,tableName:e,tableDescription:e,component:"Text",type:"varchar(255)"}}function Dr(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!=null&&e!==""))}function hx(){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 gt(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(`
|
|
129
|
-
`),e.Code!==1)}function zc(t){if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function RK(t){let e=ee(t),r=ee(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=[],i=ie(r,"ExpectedSeconds","expectedSeconds")??0,a=ie(r,"ExpectedItems","expectedItems","EstimatedRows","estimatedRows")??0,o=ie(r,"FanOutOperations","fanOutOperations","FanOut","fanOut")??0,s=ie(r,"ExternalCalls","externalCalls")??0;i>=120&&n.push(`\u9884\u8BA1\u8017\u65F6 ${i}s >= 120s`),a>=500&&n.push(`\u9884\u8BA1\u5904\u7406 ${a} \u6761 >= 500 \u6761`),o>=1e3&&n.push(`\u9884\u8BA1\u6247\u51FA ${o} \u4E2A\u5B50\u64CD\u4F5C >= 1000`),s>=100&&n.push(`\u9884\u8BA1\u5916\u90E8\u8C03\u7528 ${s} \u6B21 >= 100 \u6B21`),xr(r,"UnknownTotal","unknownTotal")===!0&&n.push("\u603B\u5DE5\u4F5C\u91CF\u672A\u77E5\u4E14\u53EF\u80FD\u957F\u65F6\u95F4\u8FD0\u884C");let c=_(e,"V8Code","v8Code"),l=[_(e,"Name","name"),_(e,"ApiEngineKey","apiEngineKey"),c].join(" ");return!(/\bV8\.OpenAppDialog\s*\(/i.test(c)&&!/\bV8\.(?:ApiEngine\.RunBackground|Method\.QueueBackgroundTask)\s*\(/i.test(c))&&/(批量.{0,4}(导入|生成|修复|处理)|安装|初始化|全量同步|数据迁移|数据库备份|批量任务)/i.test(l)&&n.push("\u52A8\u4F5C\u8BED\u4E49\u5C5E\u4E8E\u5178\u578B\u957F\u4EFB\u52A1"),{required:n.length>0,reasons:n}}function $K(t){let e=ee(t),r=ee(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=_(r,"ExecutionMode","executionMode").trim().toLowerCase(),i=xr(r,"ClientChunked","clientChunked")===!0||n==="clientchunked"||n==="clientsequential",a=ie(r,"MaxItemsPerChunk","maxItemsPerChunk")??0,o=xr(r,"Resumable","resumable")===!0;return{declared:i,valid:i&&a>0&&o,maxItemsPerChunk:a,resumable:o}}var dd="https://api.itdos.com",dx="iTdos";function OK(t){let e=String(t.storeId||"").trim(),r=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(r))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");let n=String(t.storeApiBase||dd).trim(),i;try{i=new URL(n)}catch{throw new Error("storeApiBase \u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP/HTTPS \u670D\u52A1\u6839\u5730\u5740\u3002")}if(i.protocol!=="https:"||i.username||i.password||i.pathname&&i.pathname!=="/"||i.search||i.hash||i.origin!==dd)throw new Error(`storeApiBase \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE ${dd}\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=dd,o=String(t.storeOsClient||dx).trim();if(o.toLowerCase()!==dx.toLowerCase())throw new Error(`storeOsClient \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE\u79DF\u6237 ${dx}\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:Dr({StoreId:e,AppId:t.appId,AppName:t.appName,AppVersion:t.appVersion,StoreApiBase:a,StoreOsClient:o,InstallParentSysMenuId:t.installParentSysMenuId,ResumeInstall:t.resumeInstall!==!1,InstallAction:t.operation==="update"?"Update":"Install",InstallOperationId:r}),Options:{IdempotencyKey:`mcp:store:${t.operation}:${e}:${r}`,ConcurrencyKey:"import-microi-store-package",MaxAttempts:3,RetryOnFailure:!0}}}function NK(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 a=new Set,o=i.map((s,c)=>{let l=ee(s),u=_(l,"Name","name");u||r.push(`${t}[${c}].Name \u4E0D\u80FD\u4E3A\u7A7A`);let p=RK(l),d=$K(l),h=l.RunBackground??l.runBackground??l.BackgroundTask??l.backgroundTask??l.IsBackgroundTask??l.isBackgroundTask,m=_(l,"ApiEngineKey","apiEngineKey");p.required&&h!==!0&&(d.declared&&!d.valid?r.push(`${t}[${c}] \u58F0\u660E\u5BA2\u6237\u7AEF\u5206\u7247\u65F6\u5FC5\u987B\u8BBE\u7F6E Workload.MaxItemsPerChunk > 0 \u4E14 Workload.Resumable=true`):d.valid?n.push(`${t}[${c}] \u5DF2\u58F0\u660E\u5BA2\u6237\u7AEF\u53EF\u6062\u590D\u5206\u7247\uFF0C\u5355\u7247\u6700\u591A ${d.maxItemsPerChunk} \u6761\uFF1B\u4FDD\u7559\u524D\u7AEF\u5206\u7247\u6267\u884C\uFF1A${p.reasons.join("\uFF1B")}`):m?(h=!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=ee(l.BackgroundTaskOptions??l.backgroundTaskOptions);h===!0&&(!_(g,"IdempotencyKey","idempotencyKey")&&!Ro(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`),_(g,"BusinessTable","businessTable")&&(!_(g,"BusinessStatusField","businessStatusField")||!_(g,"BusinessTaskIdField","businessTaskIdField"))&&n.push(`${t}[${c}] \u5DF2\u5173\u8054\u4E1A\u52A1\u8868\uFF0C\u4F46\u7F3A\u5C11 BusinessStatusField/BusinessTaskIdField`));let y=_(l,"TargetSysMenuId","targetSysMenuId"),v=t==="PageTabs"&&!!y;!_(l,"V8Code","v8Code")&&!_(l,"Url","url")&&!(h&&m)&&!v&&r.push(`${t}[${c}] \u5FC5\u987B\u914D\u7F6E V8Code\u3001Url\u3001\u5173\u8054\u6A21\u5757 TargetSysMenuId\uFF0C\u6216\u540E\u53F0\u4EFB\u52A1 ApiEngineKey`);let x=_(l,"Id","id")||hx();_(l,"Id","id")||n.push(`${t}[${c}] \u672A\u4F20 Id\uFF0C\u5DF2\u81EA\u52A8\u751F\u6210 ${x}`),a.has(x)&&r.push(`${t} \u4E2D\u5B58\u5728\u91CD\u590D Id\uFF1A${x}`),a.add(x);let b=_(l,"V8CodeShow","v8CodeShow");return b&&!b.includes("V8.Result")&&n.push(`${t}[${c}].V8CodeShow \u5EFA\u8BAE\u663E\u5F0F\u8D4B\u503C V8.Result=true/false`),Dr({...l,Id:x,Sort:ie(l,"Sort","sort")??c*10,Name:u,Icon:_(l,"Icon","icon")||void 0,BtnStyle:_(l,"BtnStyle","btnStyle")||void 0,IsVisible:l.IsVisible??l.isVisible??!0,ShowRow:t==="MoreBtns"?l.ShowRow??l.showRow??!0:l.ShowRow??l.showRow,V8CodeShow:b||void 0,V8Code:_(l,"V8Code","v8Code")||void 0,Url:_(l,"Url","url")||void 0,RunBackground:h===void 0?void 0:!!h,BackgroundTask:l.BackgroundTask??l.backgroundTask??void 0,IsBackgroundTask:l.IsBackgroundTask??l.isBackgroundTask??void 0,ApiEngineKey:m||void 0,Workload:Object.keys(ee(l.Workload??l.workload)).length?ee(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(o),errors:r,warnings:n}}function Oo(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[c,l]of Object.entries(i)){let u=l.find(d=>t[d]!==void 0);if(!u)continue;let p=NK(c,t[u]);r.push(...p.errors),n.push(...p.warnings),p.ok&&p.value!==void 0&&(e[c]=p.value)}let a=[["MenuBadgeEnabled","menuBadgeEnabled"],["EnableViewSchema","enableViewSchema"],["ViewConfigVersion","viewConfigVersion"]];for(let[c,l]of a){if(t[c]===void 0&&t[l]===void 0)continue;let u=ie(t,c,l);u!==void 0&&(e[c]=c.endsWith("Enabled")?u===1?1:0:u),delete e[l]}let o=[["MenuBadgeApiEngineKey","menuBadgeApiEngineKey"],["ViewSchemaVersion","viewSchemaVersion"]];for(let[c,l]of o)t[c]===void 0&&t[l]===void 0||(e[c]=_(t,c,l),delete e[l]);let s=["ViewSchema","viewSchema"].find(c=>t[c]!==void 0);if(s){let c=hd(t[s]);r.push(...c.errors),n.push(...c.warnings),delete e.viewSchema,c.value!==void 0&&(e.ViewSchema=c.value)}return{data:e,errors:r,warnings:n}}function xr(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 MK(t,e,r,n){let i=Gt(t,"v8Unlimited","V8Unlimited");if(i==null||i==="")return;let a=xr(t,"v8Unlimited","V8Unlimited");if(a===void 0){r.push(`${e}.v8Unlimited \u5FC5\u987B\u662F boolean \u6216 0/1`);return}return a&&n.push(`${e}.v8Unlimited=true \u4F1A\u53D6\u6D88\u8BE5\u8868\u540E\u7AEF V8 \u4E8B\u4EF6\u7684\u5355\u6B21 Jint \u8D85\u65F6\u3001\u8BED\u53E5\u3001\u9012\u5F52\u548C\u7D2F\u8BA1\u5206\u914D\u9884\u7B97\uFF1B\u4EC5\u5728\u4E1A\u52A1\u660E\u786E\u8981\u6C42\u5355\u4E8B\u52A1\u4E14\u5DF2\u8BC4\u4F30\u6570\u636E\u5E93\u9501\u3001\u56DE\u6EDA\u3001\u8FDE\u63A5\u8D85\u65F6\u4E0E\u8FDB\u7A0B\u5185\u5B58\u98CE\u9669\u65F6\u5F00\u542F\u3002\u8FDB\u7A0B\u5E38\u9A7B\u5185\u5B58\u4FDD\u62A4\u4ECD\u751F\u6548\uFF0C\u4E14\u4E0D\u4F1A\u5411\u5D4C\u5957\u63A5\u53E3\u7EE7\u627F\u3002`),a}function dR(t){let e=xr(t,"v8Limit","V8Limit");if(e!==void 0)return e;let r=xr(t,"v8Unlimited","V8Unlimited");return r===void 0?void 0:!r}function DK(t,e,r,n){let i=Gt(t,"v8Limit","V8Limit"),a=Gt(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(a==null||a===""))return;let o=i!=null&&i!=="",s=o?xr(t,"v8Limit","V8Limit"):dR(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(o&&a!==void 0){let c=xr(t,"v8Unlimited","V8Unlimited");c!==void 0&&s!==!c&&r.push(`${e}.v8Limit \u4E0E\u517C\u5BB9\u5B57\u6BB5 v8Unlimited \u7684\u8BED\u4E49\u51B2\u7A81`)}else a!==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 zK=["Detail","Edit","List","Card"],FK=["PC","Mobile","All"],jK=["ApiEngine","OpenDetail","OpenList","OpenForm","Navigate","Dial","Scan","Map","Refresh","Back","Copy"],LK=new Set(["v8code","v8codeshow","script","javascript","eval","onclick","function"]);function gx(t,e){let r=String(t??"").trim().toLowerCase();return e.find(n=>n.toLowerCase()===r)||""}function kn(t,...e){let r=new Set(e.map(i=>i.toLowerCase()));return Object.entries(t).find(([i])=>r.has(i.toLowerCase()))?.[1]}function yx(t,e="ViewSchema"){if(Array.isArray(t)){for(let r=0;r<t.length;r+=1){let n=yx(t[r],`${e}[${r}]`);if(n)return n}return""}if(!t||typeof t!="object")return"";for(let[r,n]of Object.entries(t)){if(LK.has(r.toLowerCase()))return`${e}.${r}`;let i=yx(n,`${e}.${r}`);if(i)return i}return""}function bx(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,a)=>{let o=ee(i);if(!Object.keys(o).length){n.push(`${e}[${a}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}let s=gx(kn(o,"ActionType","Type"),jK);if(!s){n.push(`${e}[${a}].ActionType \u4E0D\u53D7\u652F\u6301`);return}s==="ApiEngine"&&!_(o,"ApiEngineKey","apiEngineKey")&&n.push(`${e}[${a}] \u4F7F\u7528 ApiEngine \u65F6\u5FC5\u987B\u914D\u7F6E ApiEngineKey`);let c=kn(o,"SuccessActions");n.push(...bx(c,`${e}[${a}].SuccessActions`,r+1))}),n}function hd(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=yx(n);i&&e.push(`ViewSchema \u4E0D\u5141\u8BB8\u5305\u542B\u53EF\u6267\u884C\u524D\u7AEF\u811A\u672C\u5B57\u6BB5\uFF1A${i}`);let o=kn(n,"Views");o!==void 0&&!Array.isArray(o)?e.push("ViewSchema.Views \u5FC5\u987B\u662F JSON \u6570\u7EC4"):Array.isArray(o)?(o.length>100&&e.push("ViewSchema.Views \u6700\u591A\u5141\u8BB8 100 \u4E2A\u89C6\u56FE"),o.forEach((c,l)=>{let u=ee(c);if(!Object.keys(u).length){e.push(`ViewSchema.Views[${l}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}gx(kn(u,"Scene"),zK)||e.push(`ViewSchema.Views[${l}].Scene \u4E0D\u53D7\u652F\u6301`);let p=kn(u,"Device");p!==void 0&&!gx(p,FK)&&e.push(`ViewSchema.Views[${l}].Device \u4E0D\u53D7\u652F\u6301`);let d=kn(u,"Layout","LayoutJson");if(typeof d=="string")try{d=JSON.parse(d)}catch{e.push(`ViewSchema.Views[${l}].Layout \u4E0D\u662F\u5408\u6CD5 JSON`);return}if(d==null)return;let h=ee(d);if(!Object.keys(h).length&&(typeof d!="object"||Array.isArray(d))){e.push(`ViewSchema.Views[${l}].Layout \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}e.push(...bx(kn(h,"Actions","ActionSchema"),`ViewSchema.Views[${l}].Layout.Actions`));let m=kn(h,"Blocks","Sections");m!==void 0&&!Array.isArray(m)?e.push(`ViewSchema.Views[${l}].Layout.Blocks \u5FC5\u987B\u662F JSON \u6570\u7EC4`):Array.isArray(m)&&(m.length>100&&e.push(`ViewSchema.Views[${l}].Layout.Blocks \u6700\u591A\u5141\u8BB8 100 \u4E2A\u533A\u5757`),m.forEach((g,y)=>{let v=ee(g);e.push(...bx(kn(v,"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 fR(t,e){let r=[],n=t.toLowerCase();if(n==="keyvalue"){let i=_(e,"data","options"),a=i?i.split(/[,,;;\n]/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c]=o.split("|");return{Key:(s||"").trim(),Value:(c||s||"").trim()}}):fd(e.items).map(o=>({Key:_(o,"Key","key"),Value:_(o,"Value","label","name")}));return{data:JSON.stringify(a),config:{DataSource:"KeyValue",SelectLabel:"Value",SelectSaveField:"Key",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="data"){let i=_(e,"data","options"),a=i?i.split(/[,,;;\n]/).map(o=>o.trim()).filter(Boolean):Array.isArray(e.items)?e.items:[];return{data:JSON.stringify(a),config:{DataSource:"Data",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="sql"){let i=_(e,"sql","Sql");return i||r.push("SQL \u6570\u636E\u6E90\u7F3A\u5C11 sql"),{config:{DataSource:"Sql",Sql:i,SelectLabel:_(e,"selectLabel","SelectLabel")||"Name",SelectSaveField:_(e,"selectSaveField","SelectSaveField")||"Id",DataSourceSqlRemote:e.dataSourceSqlRemote??e.DataSourceSqlRemote??!0,EnableSearch:e.enableSearch??e.EnableSearch??!0},warnings:r}}if(n==="apiengine"){let i=_(e,"apiEngineKey","DataSourceApiEngineKey");return i||r.push("\u63A5\u53E3\u5F15\u64CE\u6570\u636E\u6E90\u7F3A\u5C11 apiEngineKey"),{config:{DataSource:"ApiEngine",DataSourceApiEngineKey:i,SelectLabel:_(e,"selectLabel")||"name",SelectSaveField:_(e,"selectSaveField")||"id"},warnings:r}}if(n==="datasource"){let i=_(e,"dataSourceId","DataSourceId");return i||r.push("\u6570\u636E\u6E90\u5F15\u64CE\u914D\u7F6E\u7F3A\u5C11 dataSourceId"),{config:{DataSource:"DataSource",DataSourceId:i,SelectLabel:_(e,"selectLabel")||"Name",SelectSaveField:_(e,"selectSaveField")||"Id"},warnings:r}}if(n==="autonumber")return{config:{AutoNumberFixed:_(e,"prefix","AutoNumberFixed"),AutoNumberLength:ie(e,"length","AutoNumberLength")??4},warnings:r};if(n==="datetime")return{config:{DateTimeType:_(e,"dateTimeType","DateTimeType")||"datetime"},warnings:r};if(n==="joinform"){let i=_(e,"tableId"),a=_(e,"tableName"),o=_(e,"joinFieldName");return!i&&!a&&r.push("JoinForm \u7F3A\u5C11 tableId/tableName\uFF0C\u7981\u6B62\u4FDD\u5B58\u672A\u89E3\u6790\u76EE\u6807\u8868\u7684\u914D\u7F6E"),o||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:Dr({TableId:i,TableName:a,JoinFieldName:o})},warnings:r}}return r.push(`\u672A\u77E5 sourceType: ${t}\uFF0C\u5DF2\u8FD4\u56DE\u7A7A\u914D\u7F6E`),{config:{},warnings:r}}function fx(t,e){let r=Sr(t);return Dr({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||(md.has(r)||_r(t)||r==="numbertext"?"In":"Out"),DisplaySelect:e?.displaySelect??["opentable","joinform","department","selecttree"].includes(r),Equal:e?.equal??(md.has(r)||r==="numbertext"?!0:void 0),IsVisible:!0})}function Ao(t,e,r,n,i){return n.map(a=>{let o=GI(t,e,a.ref)||GI(t,r,a.ref)||(Ex(a.ref)?pR(e,r,a.ref):void 0);if(!o)throw new Error(`${i}: unknown field "${a.ref}" on table "${r||e}"`);return{meta:o,ref:a}})}function nt(t,...e){for(let r of e){let n=Gt(t,r);if(!(n==null||n===""))return typeof n=="string"?n:JSON.stringify(n)}return""}var VK=new Set(["id","osclient","isdeleted","createuserid","updateuserid","deleteuserid","tenantid","storeid","userid","userids","roleid","roleids","parentid","parentids","class","code","enname","endescription"]),kx=new Set(["button","divider","collapsegroup","tabs","alert","statictext","html","devcomponent"]),qK=new Set(["textarea","richtext","codeeditor","jsontable","imgupload","fileupload","tablechild","map","maparea","jointable","opentable","treecheckbox","transfer"]),BK=new Set(["text","textarea","select","multipleselect","radio","checkbox","datetime","date","numbertext","autonumber","switch","department","address","cascader","selecttree","opentable","joinform","autocomplete","taginput"]),md=new Set(["select","multipleselect","radio","checkbox","switch","department","selecttree","opentable","joinform","cascader"]);function Wt(t){return(t||"").trim().toLowerCase()}function st(t){return`${t.name||""} ${t.label||""} ${t.component||""} ${t.type||""}`.toLowerCase()}function ge(t,e){return e.some(r=>t.includes(r.toLowerCase()))}function Sr(t){return Wt(t.component||"Text")}function UK(t){return kx.has(Sr(t))}function ZK(t){return qK.has(Sr(t))}function JK(t){let e=t.name||"",r=Wt(e).replace(/[_\-\s]+/g,"");return!!(VK.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 Fc(t){return Ex(t.name)&&!["CreateTime","UpdateTime","UserName"].some(e=>e.toLowerCase()===t.name.toLowerCase())||JK(t)||UK(t)||ZK(t)?!0:Sr(t).includes("hidden")}function si(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 wr(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 gd(t){let e=Wt(t.type);return Sr(t)==="numbertext"||e.startsWith("decimal")||e==="int"||e==="bigint"}function _r(t){let e=st(t);return Sr(t)==="datetime"||ge(e,["time","date","\u65E5\u671F","\u65F6\u95F4"])}function HK(t){let e=Sr(t),r=md.has(e)||e==="numbertext"||e==="rate"||e==="progress";return{ref:t.name,displayType:r||_r(t)?"In":"Out",displaySelect:["opentable","joinform","department","selecttree"].includes(e),equal:r?!0:void 0}}function XI(t){let e=st(t),r=0;return ge(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),ge(e,["status","state","type","category","level","class","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])&&(r+=45),ge(e,["customer","member","user","owner","\u8D1F\u8D23\u4EBA","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8054\u7CFB\u4EBA"])&&(r+=35),_r(t)&&(r+=25),gd(t)&&!ge(e,["phone","mobile","tel","\u7535\u8BDD","\u624B\u673A"])&&(r+=15),Sr(t)==="textarea"&&(r-=25),r}function vx(t){let e=st(t),r=0;return ge(e,["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])&&(r+=70),ge(e,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])&&(r+=45),ge(e,["customer","member","user","owner","phone","mobile","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u7535\u8BDD","\u624B\u673A"])&&(r+=35),ge(e,["amount","money","price","total","count","qty","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D"])&&(r+=30),_r(t)&&(r+=15),Sr(t)==="autonumber"&&(r+=55),r}function KK(t){return si(t.filter(Fc))}function jc(t){let e=t.filter(n=>!Fc(n)),r=e.length?e:t;return si(wr(r,vx)).slice(0,Math.min(12,r.length))}function WK(t){let e=t.filter(n=>!Fc(n)&&BK.has(Sr(n))),r=wr(e,XI).filter(n=>XI(n)>0);return si(r.length?r:e).slice(0,Math.min(8,e.length))}function GK(t){let e=t.filter(r=>!Fc(r)&&(_r(r)||gd(r)||Wt(r.name)==="sort"));return si(wr(e,r=>{let n=st(r);return ge(n,["update","\u4FEE\u6539"])?80:ge(n,["create","\u521B\u5EFA"])?75:Wt(r.name)==="sort"?70:ge(n,["amount","money","price","total","count","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?60:20})).slice(0,Math.min(8,e.length))}function mR(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=st(n);return!Fc(n)&&gd(n)&&!ge(i,e)&&ge(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 si(wr(r,n=>ge(st(n),["amount","money","price","total","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D"])?80:40)).slice(0,6)}function XK(t){let e=jc(t),r=wr(e,a=>ge(st(a),["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])?100:0)[0],n=wr(e.filter(a=>a!==r),a=>ge(st(a),["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?80:0),i=e.filter(a=>a!==r&&!n.slice(0,1).includes(a));return si([r,...n.slice(0,1),...i].filter(Boolean)).slice(0,4)}function YK(t){return wr(jc(t),e=>ge(st(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])?100:0).filter(e=>ge(st(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])).slice(0,2)}function QK(t){return wr(jc(t),e=>{let r=st(e);return ge(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?90:_r(e)?60:0}).filter(e=>{let r=st(e);return _r(e)||ge(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])}).slice(0,3)}function hR(t,e=0){let r=ee(t),n=_(r,"name","Name");return n?{id:_(r,"id","Id")||n,name:n,label:_(r,"label","Label")||n,tableId:_(r,"tableId","TableId"),tableName:_(r,"tableName","TableName"),tableDescription:_(r,"tableDescription","TableDescription"),component:_(r,"component","Component")||"Text",type:_(r,"type","Type")||"varchar(500)"}:null}function yd(t){let e=hR(t);if(!e)return 150;let r=st(e),n=Sr(e);return["richtext","textarea","address","map","maparea","fileupload","imgupload"].includes(n)||ge(r,["address","remark","description","content","\u5730\u5740","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247"])?240:ge(r,["name","title","subject","customer","company","\u540D\u79F0","\u6807\u9898","\u4E3B\u9898","\u5BA2\u6237","\u4F01\u4E1A"])?200:_r(e)?170:gd(e)?140:n==="autonumber"||ge(r,["phone","mobile","email","code","number","\u7F16\u53F7","\u5355\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])?160:md.has(n)||ge(r,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?130:150}function En(t,e={}){return{Name:t.name,Label:t.label||t.name,...e}}function ua(t,e,r){let n=[];for(let i of t)if(!(!i?.name||r.has(Wt(i.name)))&&(r.add(Wt(i.name)),n.push(i),n.length>=e))break;return n}function Tx(t,e,r=""){let n=e.map(hR).filter(Boolean),i=jc(n),a=String(t||r||n[0]?.tableDescription||n[0]?.tableName||"\u4E1A\u52A1\u6A21\u5757").trim(),o=String(r||n[0]?.tableDescription||"").trim(),s=o&&o!==a?o:`${a}\u7684\u4E1A\u52A1\u6570\u636E\u3001\u8FDB\u5EA6\u4E0E\u5173\u952E\u6307\u6807`,c=wr(i,A=>{let U=st(A);return ge(U,["title","subject","\u6807\u9898","\u4E3B\u9898"])?150:ge(U,["name","\u540D\u79F0"])?130:Sr(A)==="autonumber"||ge(U,["no","code","number","\u7F16\u53F7","\u5355\u53F7","\u7F16\u7801"])?110:vx(A)})[0]||i[0],l=wr(i.filter(A=>A!==c),A=>ge(st(A),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])?100:0).filter(A=>ge(st(A),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])),u=mR(n).filter(A=>A!==c),p=wr(n.filter(_r),A=>ge(st(A),["create","\u521B\u5EFA"])?100:50),d=wr(i.filter(A=>A!==c&&!l.includes(A)&&!u.includes(A)),A=>{let U=st(A);return ge(U,["customer","member","user","owner","contact","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u8054\u7CFB\u4EBA"])?90:_r(A)?70:vx(A)}).slice(0,2),h=si([...l.slice(0,1),...u.slice(0,1)]),m=si([c,...d,...h].filter(Boolean)).map(A=>A.name),g=c?Math.min(520,Math.max(340,yd(c)+d.length*28+h.length*70)):0,y=[{Icon:"fas fa-chart-column",Tone:"primary"},{Icon:"fas fa-calculator",Tone:"success"}],v=u.slice(0,2).map((A,U)=>({Key:`Aggregate:${A.name}`,Label:`${A.label||A.name}\u5408\u8BA1`,Source:"Field",Field:A.name,...y[U]}));v.push({Key:"DataCount",Label:"\u7B5B\u9009\u7ED3\u679C",Source:"DataCount",Icon:"fas fa-layer-group",Tone:"info"}),v.length<3&&v.push({Key:"PageCount",Label:"\u672C\u9875\u5C55\u793A",Source:"PageCount",Icon:"fas fa-list-check",Tone:"warning"});let x=new Set(c?[Wt(c.name)]:[]),b=ua(d,1,x),S=ua(l,1,x),k=ua(l,1,x),w=ua(u,1,x),T=ua(p,2,x),C=ua(i,2,x),$=ua([...u,...p],2,x),P={Title:a,Description:s,Metrics:v};return{Views:[{Key:"auto-list-pc",Scene:"List",Device:"PC",Priority:100,Layout:{Hero:P,List:{Density:"Compact",Columns:c?[{Key:`composite:${c.name}`,Field:c.name,Lines:d.map(A=>En(A,{Icon:_r(A)?"fas fa-clock":"fas fa-circle-info",Tone:"info"})),TrailingFields:h.map(A=>En(A,{Icon:l.includes(A)?"fas fa-circle-check":"fas fa-coins",Tone:l.includes(A)?"success":"warning",DisplayStyle:l.includes(A)?"Tag":"Text"})),RequiredFields:m,Align:"Left",MinWidth:g}]:[]}}},{Key:"auto-card-mobile",Scene:"Card",Device:"Mobile",Priority:100,Layout:{Hero:{...P,Metrics:v.map(A=>({...A}))},Card:{Preset:"Business",AvatarTextField:c?.name||"",TitleField:c?.name||"",SubtitleFields:b.map(A=>En(A,{Icon:"fas fa-circle-info",Tone:"info"})),StatusFields:S.map(A=>En(A,{DisplayStyle:"Tag",Icon:"fas fa-circle-check",Tone:"success"})),TopFields:k.map(A=>En(A,{DisplayStyle:"Tag",Icon:"fas fa-tag",Tone:"primary"})),RightFields:w.map(A=>En(A,{Icon:"fas fa-coins",Tone:"danger",FontWeight:"700"})),Fields:C.map(A=>En(A)),MetaFields:T.map(A=>En(A,{Icon:"fas fa-clock",Tone:"info"})),BottomFields:$.map(A=>En(A,{Icon:_r(A)?"fas fa-calendar":"fas fa-chart-simple",Tone:"warning"})),HideIndex:!0,ShowCreateTime:T.length===0,ShowUpdateTime:!1}}}]}}function eW(t,e,r){let n=t.length?t:[pR(e,r,"CreateTime")],i=n.find(a=>Wt(a.name)==="createtime")||n.find(a=>Wt(a.name)==="updatetime")||n.find(a=>Wt(a.name)==="sort");if(i)return JSON.stringify([{Id:i.id,Name:i.name,Type:Wt(i.name)==="sort"?"ASC":"DESC",Sort:0}])}function tW(t,e,r,n){let i=Gt(t,"DefaultOrderBy");if(i!=null&&i!=="")return typeof i=="string"?i:JSON.stringify(i);let a=Gt(t,"defaultOrderBy");if(a!=null&&a!==""){let s=Array.isArray(a)||typeof a=="string"&&a.trim().startsWith("[")?vr({value:a},"value"):[{ref:String(a).trim(),type:"DESC"}];return JSON.stringify(Ao(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 o=vr(t,"orderBy","OrderBy","defaultSort","DefaultSort","sortBy","SortBy");if(o.length)return JSON.stringify(Ao(e,r,n,o,"module.defaultOrderBy").map(({meta:s,ref:c},l)=>({Id:s.id,Name:s.name,Type:c.type||"DESC",Sort:l})))}function rW(t,e,r,n){if(!r&&!n)return{};let i=$o(e,r).length?$o(e,r):$o(e,n),a={},o=vr(t,"searchFields","SearchFields","searchFieldNames","SearchFieldNames"),s=o.length?Ao(e,r,n,o,"module.searchFields"):WK(i).map(h=>({meta:h,ref:HK(h)}));!nt(t,"searchFieldIds","SearchFieldIds")&&s.length&&(a.SearchFieldIds=JSON.stringify(s.map(({meta:h,ref:m})=>fx(h,m))));let c=vr(t,"listFields","ListFields","tableFields","TableFields","columns","Columns"),l=c.length?Ao(e,r,n,c,"module.listFields"):jc(i).map(h=>({meta:h,ref:{ref:h.name}}));!nt(t,"tableDiyFieldIds","TableDiyFieldIds")&&l.length&&(a.TableDiyFieldIds=JSON.stringify(l.map(({meta:h})=>h.id))),!nt(t,"selectFields","SelectFields")&&l.length&&(a.SelectFields=JSON.stringify(l.map(({meta:h,ref:m})=>fx(h,m))));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 h of u){if(nt(t,...h.explicitKeys))continue;let m=vr(t,...h.refKeys),g={SortFieldIds:GK(i),NotShowFields:KK(i),MobileListFields:XK(i),CardTitleTagFields:YK(i),CardBottomTagFields:QK(i),InTableEditFields:[]};if(!m.length&&!g[h.canonical]?.length)continue;let y=m.length?Ao(e,r,n,m,`module.${h.canonical}`):g[h.canonical].map(v=>({meta:v,ref:{ref:v.name}}));a[h.canonical]=JSON.stringify(h.objectArray?y.map(({meta:v,ref:x})=>fx(v,x)):y.map(({meta:v})=>v.id))}let p=vr(t,"statisticsFieldNames","StatisticsFieldNames","statFields","StatFields");if(!nt(t,"statisticsFields","StatisticsFields")){let h=p.length?Ao(e,r,n,p,"module.statisticsFields"):mR(i).map(m=>({meta:m,ref:{ref:m.name,type:"Sum"}}));h.length&&(a.StatisticsFields=JSON.stringify(h.map(({meta:m,ref:g})=>({Id:m.id,Type:g.type||"Sum"}))))}let d=tW(t,e,r,n)||(nt(t,"DefaultOrderBy","defaultOrderBy")?void 0:eW(i,r,n));return d&&(a.DefaultOrderBy=d),a}function YI(t,e,r){let n=fd(ee(e).Tables);for(let i of n){let a=_(i,"Id","id"),o=_(i,"Name","name");if(!a||!o)continue;r?.set(o.toLowerCase(),a);let s=Gt(i,"_Fields","Fields","fields"),c=Array.isArray(s)?fd(s):[];for(let l of c){let u=_(l,"Id","id"),p=_(l,"Name","name");!u||!p||uR(t,{id:u,name:p,label:_(l,"Label","label")||p,tableId:a,tableName:o,tableDescription:_(i,"Description","description")||o,component:_(l,"Component","component")||"Text",type:_(l,"Type","type")||"varchar(255)"})}}}function Dc(t){return Wt(_(t,"component","Component")||"Text")}function nW(t){return`${_(t,"name","Name")} ${_(t,"label","Label")} ${_(t,"component","Component")}`.toLowerCase()}function iW(t,e){let r=nW(t),n=Dc(t);return["imgupload","fileupload","richtext","codeeditor","jsontable","tablechild","map","maparea","textarea"].includes(n)||ge(r,["remark","note","content","file","image","attach","map","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247","\u5730\u56FE"])?"attachment":ge(r,["phone","mobile","email","address","city","contact","\u8054\u7CFB\u4EBA","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1","\u5730\u5740","\u57CE\u5E02"])?"contact":ge(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 xx(t){let e=ce(t,"fields","Fields"),r=Gt(t,"tabs","Tabs"),n=new Map,i=ie(t,"column","Column")??(e.length>6?2:void 0);if(r!=null&&r!=="")return{fieldTabs:n,column:i};let a=e.filter(l=>!kx.has(Dc(l)));if(a.length<=12)return{fieldTabs:n,column:i};let o={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 a.forEach((l,u)=>{let p=_(l,"name","Name");if(!p||_(l,"tab","Tab"))return;let d=iW(l,u);n.set(p,d),s.add(d)}),{tabs:["basic","contact","business","attachment","extra"].filter(l=>s.has(l)).map(l=>({Id:l,Name:o[l].Name,Icon:o[l].Icon,Sort:o[l].Sort})),fieldTabs:n,column:i}}function mx(t){let e=[],r=[],n=[],i=ce(t,"roles","Roles"),a=ce(t,"tables","Tables"),o=ce(t,"engines","Engines"),s=ce(t,"modules","Modules"),c=ce(t,"events","Events"),l=ce(t,"dataSources","DataSources"),u=ce(t,"pages","Pages"),p=ce(t,"printTemplates","PrintTemplates"),d=ce(t,"workflows","Workflows"),h=ce(t,"jobs","Jobs"),m=ce(t,"permissions","Permissions"),g=new Map;!a.length&&!o.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 y=fW(t);return e.push(...y.errors),r.push(...y.warnings),i.forEach(v=>n.push(`save_role ${_(v,"name","Name")}`)),a.forEach((v,x)=>{let b=_(v,"name","Name");b||e.push(`tables[${x}].name \u4E0D\u80FD\u4E3A\u7A7A`),MK(v,`tables[${x}]`,e,r),n.push(`create_table ${b||`(index ${x})`}`),xx(v).tabs?.length&&r.push(`table ${b||`(index ${x})`} has many fields; generator will create diy_table.Tabs and assign empty field Tab values automatically`),b&&g.set(b.toLowerCase(),new Set),ce(v,"fields","Fields").forEach((w,T)=>{let C=_(w,"name","Name"),$=_(w,"label","Label");C||e.push(`tables[${x}].fields[${T}].name \u4E0D\u80FD\u4E3A\u7A7A`),$||e.push(`tables[${x}].fields[${T}].label \u4E0D\u80FD\u4E3A\u7A7A`),b&&C&&g.get(b.toLowerCase())?.add(C.toLowerCase()),b&&$&&g.get(b.toLowerCase())?.add($.toLowerCase()),n.push(`add_field ${b}.${C}`)});let k=new Set(ce(v,"fields","Fields").map(w=>_(w,"name","Name").toLowerCase()).filter(Boolean));["id","createtime","updatetime","createuser","osclient"].forEach(w=>k.add(w)),ce(v,"indexes","Indexes").forEach((w,T)=>{let C=Ro(w,"columns","Columns");C.length||e.push(`tables[${x}].indexes[${T}].columns \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5`);for(let $ of C)k.has($.toLowerCase())||e.push(`tables[${x}].indexes[${T}] references unknown physical field "${$}" on table "${b}"`);C.some(($,P)=>C.findIndex(A=>A.toLowerCase()===$.toLowerCase())!==P)&&e.push(`tables[${x}].indexes[${T}] \u5305\u542B\u91CD\u590D\u5B57\u6BB5`),n.push(`create_index ${b}.${_(w,"name","Name")||C.join("_")}`)})}),l.forEach(v=>n.push(`save_data_source ${_(v,"dataSourceKey","DataSourceKey")}`)),o.forEach((v,x)=>{let b=_(v,"apiEngineKey","ApiEngineKey");b||e.push(`engines[${x}].apiEngineKey \u4E0D\u80FD\u4E3A\u7A7A`),DK(v,`engines[${x}]`,e,r),n.push(`upsert_engine ${b}`)}),c.forEach(v=>n.push(`save_event ${_(v,"formEngineKey","FormEngineKey")}/${_(v,"eventType","EventType")}`)),s.forEach(v=>{let x=Oo(v);e.push(...x.errors),r.push(...x.warnings);let b=_(v,"table","tableName","diyTableName","DiyTableName"),S=_(v,"name","Name"),k=_(v,"openType","OpenType"),w=_(v,"microServiceKey","MicroServiceKey"),T=_(v,"microServiceRoutePath","MicroServiceRoutePath");if(k.toLowerCase()==="microservice"||!!(ie(v,"isMicroiService","IsMicroiService")===1||w||T||_(v,"microServiceId","MicroServiceId")||_(v,"microServicePageId","MicroServicePageId"))){if(w||e.push(`modules.${S||"(unnamed)"}.microServiceKey \u4E0D\u80FD\u4E3A\u7A7A`),T||e.push(`modules.${S||"(unnamed)"}.microServiceRoutePath \u4E0D\u80FD\u4E3A\u7A7A`),T)try{Sx(T)}catch($){e.push(`modules.${S||"(unnamed)"}.microServiceRoutePath ${$ instanceof Error?$.message:String($)}`)}n.push(`resolve_microservice_binding ${w||"(missing)"}${T||"/(missing)"}`)}if(b&&g.has(b.toLowerCase())){let $=g.get(b.toLowerCase())||new Set,P=[["listFields",vr(v,"listFields","ListFields","tableFields","TableFields","columns","Columns")],["searchFields",vr(v,"searchFields","SearchFields","searchFieldNames","SearchFieldNames")],["sortFields",vr(v,"sortFields","SortFields")],["hiddenFields",vr(v,"hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName")],["mobileFields",vr(v,"mobileFields","MobileFields")]];for(let[A,U]of P)for(let Y of U)!$.has(Y.ref.toLowerCase())&&!Ex(Y.ref)&&e.push(`modules.${S||b}.${A} references unknown field "${Y.ref}" on table "${b}"`)}b&&!vr(v,"listFields","ListFields","tableFields","TableFields","columns","Columns").length&&!nt(v,"TableDiyFieldIds","SelectFields")&&r.push(`module ${S||b} has no listFields; generator will use the first business fields from ${b}`),n.push(`create_or_update_module ${_(v,"name","Name")}`)}),m.forEach(v=>n.push(`set_permission ${_(v,"roleId","RoleId")||"admin"}`)),u.forEach((v,x)=>{let b=Sn(v.json??v.JsonObj??v.JsonStr??v);e.push(...b.errors.map(S=>`pages[${x}]: ${S}`)),r.push(...b.warnings.map(S=>`pages[${x}]: ${S}`)),n.push(`save_page ${_(v,"title","Title")}`)}),p.forEach((v,x)=>{let b=ca(v.PageObj??v.pageObj),S=la(v.PrintObj??v.printObj);e.push(...b.errors.map(k=>`printTemplates[${x}].PageObj: ${k}`)),r.push(...b.warnings.map(k=>`printTemplates[${x}].PageObj: ${k}`)),e.push(...S.errors.map(k=>`printTemplates[${x}].PrintObj: ${k}`)),r.push(...S.warnings.map(k=>`printTemplates[${x}].PrintObj: ${k}`)),n.push(`save_print_template ${_(v,"title","Title")}`)}),d.forEach((v,x)=>{let b=_x(v);e.push(...b.errors.map(S=>`workflows[${x}]: ${S}`)),r.push(...b.warnings.map(S=>`workflows[${x}]: ${S}`)),n.push(`save_workflow ${_(ee(v.FlowDesign??v.flowDesign??v),"FlowName","flowName","name")}`)}),h.forEach(v=>n.push(`save_job ${_(v,"jobName","JobName")}`)),{plan:n,errors:e,warnings:r}}function Cx(t){return{flow:ee(t.FlowDesign??t.flowDesign??t),nodes:ce(t,"Nodes","nodes"),lines:ce(t,"Lines","lines")}}function Io(t){return _(t,"Id","id","NodeId","nodeId")}function pa(t){return _(t,"NodeName","nodeName","Name","name")}function gR(t){return _(t,"NodeType","nodeType","Type","type")}function wx(t){let e=`${gR(t)} ${pa(t)}`.toLowerCase();return e.includes("start")||e.includes("begin")||e.includes("\u5F00\u59CB")||e.includes("\u53D1\u8D77")}function QI(t){let e=`${gR(t)} ${pa(t)}`.toLowerCase();return e.includes("end")||e.includes("finish")||e.includes("\u7ED3\u675F")||e.includes("\u5B8C\u6210")}function _x(t){let e=[],r=[],{flow:n,nodes:i,lines:a}=Cx(t),o=_(n,"FlowName","flowName","Name","name"),s=_(n,"TableId","tableId"),c=_(n,"table","tableName","TableName","diyTableName","DiyTableName"),l=new Map,u=new Map,p=new Map;o||e.push("FlowDesign.FlowName \u4E0D\u80FD\u4E3A\u7A7A"),i.length||e.push("Nodes \u81F3\u5C11\u9700\u8981\u5305\u542B\u5F00\u59CB\u3001\u5BA1\u6279/\u4E1A\u52A1\u3001\u7ED3\u675F\u8282\u70B9"),a.length||e.push("Lines \u81F3\u5C11\u9700\u8981\u8FDE\u63A5\u5F00\u59CB\u5230\u4E0B\u4E00\u8282\u70B9"),!s&&!c&&r.push("FlowDesign.TableId \u4E3A\u7A7A\uFF1B\u666E\u901A\u5BA1\u6279\u6D41\u5EFA\u8BAE\u7ED1\u5B9A\u4E1A\u52A1 diy_table"),i.forEach((m,g)=>{let y=Io(m),v=pa(m);y||e.push(`Nodes[${g}].Id/NodeId \u4E0D\u80FD\u4E3A\u7A7A`),v||e.push(`Nodes[${g}].NodeName \u4E0D\u80FD\u4E3A\u7A7A`),y&&(l.has(y)&&e.push(`\u8282\u70B9 Id \u91CD\u590D\uFF1A${y}`),l.set(y,m))}),a.forEach((m,g)=>{let y=_(m,"Id","id","LineId","lineId")||`(index ${g})`,v=_(m,"FromNodeId","fromNodeId"),x=_(m,"ToNodeId","toNodeId");v||e.push(`Lines[${g}].FromNodeId \u4E0D\u80FD\u4E3A\u7A7A`),x||e.push(`Lines[${g}].ToNodeId \u4E0D\u80FD\u4E3A\u7A7A`),v&&!l.has(v)&&e.push(`\u8FDE\u7EBF ${y} \u7684 FromNodeId \u4E0D\u5B58\u5728\uFF1A${v}`),x&&!l.has(x)&&e.push(`\u8FDE\u7EBF ${y} \u7684 ToNodeId \u4E0D\u5B58\u5728\uFF1A${x}`),v===x&&v&&r.push(`\u8FDE\u7EBF ${y} \u6307\u5411\u81EA\u8EAB\uFF0C\u8BF7\u786E\u8BA4\u662F\u5426\u4E3A\u6709\u610F\u5FAA\u73AF`),v&&u.set(v,[...u.get(v)||[],m]),x&&p.set(x,[...p.get(x)||[],m])});let d=i.filter(wx),h=i.filter(QI);return d.length!==1&&e.push(`\u9700\u8981\u4E14\u4EC5\u9700\u8981 1 \u4E2A\u5F00\u59CB\u8282\u70B9\uFF0C\u5F53\u524D ${d.length} \u4E2A`),h.length<1&&e.push("\u81F3\u5C11\u9700\u8981 1 \u4E2A\u7ED3\u675F\u8282\u70B9"),i.forEach(m=>{let g=Io(m),y=pa(m)||g;if(!g)return;let v=u.get(g)||[],x=p.get(g)||[];!wx(m)&&x.length===0&&r.push(`\u8282\u70B9 ${y} \u6CA1\u6709\u5165\u7EBF`),!QI(m)&&v.length===0&&r.push(`\u8282\u70B9 ${y} \u6CA1\u6709\u51FA\u7EBF`),v.length>1&&(_(m,"LineValueV8","lineValueV8","V8Code","v8Code")||r.push(`\u8282\u70B9 ${y} \u6709 ${v.length} \u6761\u51FA\u7EBF\uFF0C\u5EFA\u8BAE\u914D\u7F6E LineValueV8\uFF0C\u5E76\u4F18\u5148\u7528 V8.NextNodeId \u6307\u5B9A\u4E0B\u4E00\u8282\u70B9`))}),{ok:e.length===0,errors:e,warnings:r,summary:{flowName:o,tableId:s,table:c,nodeCount:i.length,lineCount:a.length,startNodes:d.map(m=>({id:Io(m),name:pa(m)})),endNodes:h.map(m=>({id:Io(m),name:pa(m)}))}}}function aW(t){let e=t.indexOf(WI);if(e<0)return null;let r=e+WI.length,n=t.indexOf(PK,r);if(n<0)return null;try{return ee(JSON.parse(t.slice(r,n).trim()))}catch{return null}}function eR(t){return t==null||String(t).trim()===""}function tR(t,e){let r=_(t,"field","Field"),n=_(t,"operator","Operator")||"eq",i=Gt(t,"value","Value"),a=r?e[r]:void 0,o=a==null?"":String(a),s=i==null?"":String(i);if(n==="empty")return eR(a);if(n==="notEmpty")return!eR(a);if(n==="contains")return o.includes(s);if(n==="notContains")return!o.includes(s);if(n==="startsWith")return o.startsWith(s);if(n==="endsWith")return s===""||o.endsWith(s);if(["gt","gte","lt","lte"].includes(n)){let c=Number(a),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"?o!==s:o===s}function oW(t){let e=ee(t.workflow),r=ee(t.formData),n=_(t,"lineValueV8Code","LineValueV8","code");if(!n&&Object.keys(e).length>0){let{nodes:s}=Cx(e),c=_(t,"nodeId","NodeId"),l=(c?s.find(u=>Io(u)===c):s.find(wx)||s[0])||{};n=_(l,"LineValueV8","lineValueV8","V8Code","v8Code")}let i=aW(n),a=ce(i||{},"routes","Routes");if(!i||a.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 o=a.find(s=>!!Gt(s,"isDefault","IsDefault"))||null;for(let s of a){if(s===o)continue;let c=ce(s,"rules","Rules").filter(u=>_(u,"field","Field"));if(c.length===0)continue;if(_(s,"match","Match")==="any"?c.some(u=>tR(u,r)):c.every(u=>tR(u,r)))return{ok:!0,selectedRoute:s,assignment:rR(s),source:"matched"}}return{ok:!!o,selectedRoute:o,assignment:o?rR(o):null,source:o?"default":"none"}}function rR(t){let e=_(t,"lineValue","LineValue"),r=_(t,"toNodeId","ToNodeId");return e?{LineValue:e}:{NextNodeId:r}}function sW(t,e){let{flow:r,nodes:n,lines:i}=Cx(t),a={...r},o=_(r,"table","tableName","TableName","diyTableName","DiyTableName");if(!_(a,"TableId","tableId")&&o){let u=e.get(o.toLowerCase());u&&(a.TableId=u)}let s=new Map,c=n.map((u,p)=>{let d=Io(u)||`wf_node_${p+1}_${hx().slice(0,8)}`,h={...u,Id:d},m=pa(h);return m&&s.set(d,m),h}),l=i.map((u,p)=>{let d=_(u,"FromNodeId","fromNodeId"),h=_(u,"ToNodeId","toNodeId"),m=_(u,"LineName","lineName")||`${s.get(d)||d||"\u5F53\u524D\u8282\u70B9"} \u5230 ${s.get(h)||h||"\u4E0B\u4E00\u8282\u70B9"}`;return{...u,Id:_(u,"Id","id","LineId","lineId")||`wf_line_${p+1}_${hx().slice(0,8)}`,LineName:m}});return{FlowDesign:a,Nodes:c,Lines:l}}async function br(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 nR(t,e){let r=_(e,"apiEngineKey","ApiEngineKey"),n=_(e,"apiName","ApiName","name","Name")||r,i=_(e,"category","Category")||"AI\u751F\u6210",a=Gt(e,"code","Code","ApiV8Code"),o=typeof a=="string",s=o?String(a):"",c=dR(e),l=await t.getEngineCode(r);return l.Code===1?!o&&c!==void 0?t.updateEngineRuntimeLimit(r,c):o?t.saveEngineCode(r,s,{functionDescription:_(e,"functionDescription","FunctionDescription")||void 0,changeSummary:_(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:_(e,"functionDescription","FunctionDescription")||void 0,changeSummary:_(e,"changeSummary","ChangeSummary")||void 0})}function cW(t,e,r,n){let i=_(t,"table","tableName","diyTableName","DiyTableName"),a=Oo(t);if(a.errors.length)throw new Error(a.errors.join(`
|
|
129
|
+
`),e.Code!==1)}function zc(t){if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function RK(t){let e=ee(t),r=ee(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=[],i=ie(r,"ExpectedSeconds","expectedSeconds")??0,a=ie(r,"ExpectedItems","expectedItems","EstimatedRows","estimatedRows")??0,o=ie(r,"FanOutOperations","fanOutOperations","FanOut","fanOut")??0,s=ie(r,"ExternalCalls","externalCalls")??0;i>=120&&n.push(`\u9884\u8BA1\u8017\u65F6 ${i}s >= 120s`),a>=500&&n.push(`\u9884\u8BA1\u5904\u7406 ${a} \u6761 >= 500 \u6761`),o>=1e3&&n.push(`\u9884\u8BA1\u6247\u51FA ${o} \u4E2A\u5B50\u64CD\u4F5C >= 1000`),s>=100&&n.push(`\u9884\u8BA1\u5916\u90E8\u8C03\u7528 ${s} \u6B21 >= 100 \u6B21`),xr(r,"UnknownTotal","unknownTotal")===!0&&n.push("\u603B\u5DE5\u4F5C\u91CF\u672A\u77E5\u4E14\u53EF\u80FD\u957F\u65F6\u95F4\u8FD0\u884C");let c=_(e,"V8Code","v8Code"),l=[_(e,"Name","name"),_(e,"ApiEngineKey","apiEngineKey"),c].join(" ");return!(/\bV8\.OpenAppDialog\s*\(/i.test(c)&&!/\bV8\.(?:ApiEngine\.RunBackground|Method\.QueueBackgroundTask)\s*\(/i.test(c))&&/(批量.{0,4}(导入|生成|修复|处理)|安装|初始化|全量同步|数据迁移|数据库备份|批量任务)/i.test(l)&&n.push("\u52A8\u4F5C\u8BED\u4E49\u5C5E\u4E8E\u5178\u578B\u957F\u4EFB\u52A1"),{required:n.length>0,reasons:n}}function $K(t){let e=ee(t),r=ee(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=_(r,"ExecutionMode","executionMode").trim().toLowerCase(),i=xr(r,"ClientChunked","clientChunked")===!0||n==="clientchunked"||n==="clientsequential",a=ie(r,"MaxItemsPerChunk","maxItemsPerChunk")??0,o=xr(r,"Resumable","resumable")===!0;return{declared:i,valid:i&&a>0&&o,maxItemsPerChunk:a,resumable:o}}var dd="https://api.itdos.com",dx="iTdos";function OK(t){let e=String(t.storeId||"").trim(),r=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(r))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");let n=String(t.storeApiBase||dd).trim(),i;try{i=new URL(n)}catch{throw new Error("storeApiBase \u5FC5\u987B\u662F\u6709\u6548\u7684 HTTP/HTTPS \u670D\u52A1\u6839\u5730\u5740\u3002")}if(i.protocol!=="https:"||i.username||i.password||i.pathname&&i.pathname!=="/"||i.search||i.hash||i.origin!==dd)throw new Error(`storeApiBase \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE ${dd}\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=dd,o=String(t.storeOsClient||dx).trim();if(o.toLowerCase()!==dx.toLowerCase())throw new Error(`storeOsClient \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE\u79DF\u6237 ${dx}\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:Dr({StoreId:e,AppId:t.appId,AppName:t.appName,AppVersion:t.appVersion,StoreApiBase:a,StoreOsClient:o,InstallParentSysMenuId:t.installParentSysMenuId,ResumeInstall:t.resumeInstall!==!1,InstallAction:t.operation==="update"?"Update":"Install",InstallOperationId:r}),Options:{IdempotencyKey:`mcp:store:${t.operation}:${e}:${r}`,ConcurrencyKey:"import-microi-store-package",MaxAttempts:3,RetryOnFailure:!0}}}function NK(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 a=new Set,o=i.map((s,c)=>{let l=ee(s),u=_(l,"Name","name");u||r.push(`${t}[${c}].Name \u4E0D\u80FD\u4E3A\u7A7A`);let p=RK(l),d=$K(l),h=l.RunBackground??l.runBackground??l.BackgroundTask??l.backgroundTask??l.IsBackgroundTask??l.isBackgroundTask,m=_(l,"ApiEngineKey","apiEngineKey");p.required&&h!==!0&&(d.declared&&!d.valid?r.push(`${t}[${c}] \u58F0\u660E\u5BA2\u6237\u7AEF\u5206\u7247\u65F6\u5FC5\u987B\u8BBE\u7F6E Workload.MaxItemsPerChunk > 0 \u4E14 Workload.Resumable=true`):d.valid?n.push(`${t}[${c}] \u5DF2\u58F0\u660E\u5BA2\u6237\u7AEF\u53EF\u6062\u590D\u5206\u7247\uFF0C\u5355\u7247\u6700\u591A ${d.maxItemsPerChunk} \u6761\uFF1B\u4FDD\u7559\u524D\u7AEF\u5206\u7247\u6267\u884C\uFF1A${p.reasons.join("\uFF1B")}`):m?(h=!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=ee(l.BackgroundTaskOptions??l.backgroundTaskOptions);h===!0&&(!_(g,"IdempotencyKey","idempotencyKey")&&!Ro(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`),_(g,"BusinessTable","businessTable")&&(!_(g,"BusinessStatusField","businessStatusField")||!_(g,"BusinessTaskIdField","businessTaskIdField"))&&n.push(`${t}[${c}] \u5DF2\u5173\u8054\u4E1A\u52A1\u8868\uFF0C\u4F46\u7F3A\u5C11 BusinessStatusField/BusinessTaskIdField`));let y=_(l,"TargetSysMenuId","targetSysMenuId"),v=t==="PageTabs"&&!!y;!_(l,"V8Code","v8Code")&&!_(l,"Url","url")&&!(h&&m)&&!v&&r.push(`${t}[${c}] \u5FC5\u987B\u914D\u7F6E V8Code\u3001Url\u3001\u5173\u8054\u6A21\u5757 TargetSysMenuId\uFF0C\u6216\u540E\u53F0\u4EFB\u52A1 ApiEngineKey`);let x=_(l,"Id","id")||hx();_(l,"Id","id")||n.push(`${t}[${c}] \u672A\u4F20 Id\uFF0C\u5DF2\u81EA\u52A8\u751F\u6210 ${x}`),a.has(x)&&r.push(`${t} \u4E2D\u5B58\u5728\u91CD\u590D Id\uFF1A${x}`),a.add(x);let b=_(l,"V8CodeShow","v8CodeShow");return b&&!b.includes("V8.Result")&&n.push(`${t}[${c}].V8CodeShow \u5EFA\u8BAE\u663E\u5F0F\u8D4B\u503C V8.Result=true/false`),Dr({...l,Id:x,Sort:ie(l,"Sort","sort")??c*10,Name:u,Icon:_(l,"Icon","icon")||void 0,BtnStyle:_(l,"BtnStyle","btnStyle")||void 0,IsVisible:l.IsVisible??l.isVisible??!0,ShowRow:t==="MoreBtns"?l.ShowRow??l.showRow??!0:l.ShowRow??l.showRow,V8CodeShow:b||void 0,V8Code:_(l,"V8Code","v8Code")||void 0,Url:_(l,"Url","url")||void 0,RunBackground:h===void 0?void 0:!!h,BackgroundTask:l.BackgroundTask??l.backgroundTask??void 0,IsBackgroundTask:l.IsBackgroundTask??l.isBackgroundTask??void 0,ApiEngineKey:m||void 0,Workload:Object.keys(ee(l.Workload??l.workload)).length?ee(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(o),errors:r,warnings:n}}function Oo(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[c,l]of Object.entries(i)){let u=l.find(d=>t[d]!==void 0);if(!u)continue;let p=NK(c,t[u]);r.push(...p.errors),n.push(...p.warnings),p.ok&&p.value!==void 0&&(e[c]=p.value)}let a=[["MenuBadgeEnabled","menuBadgeEnabled"],["EnableViewSchema","enableViewSchema"],["ViewConfigVersion","viewConfigVersion"]];for(let[c,l]of a){if(t[c]===void 0&&t[l]===void 0)continue;let u=ie(t,c,l);u!==void 0&&(e[c]=c.endsWith("Enabled")?u===1?1:0:u),delete e[l]}let o=[["MenuBadgeApiEngineKey","menuBadgeApiEngineKey"],["ViewSchemaVersion","viewSchemaVersion"]];for(let[c,l]of o)t[c]===void 0&&t[l]===void 0||(e[c]=_(t,c,l),delete e[l]);let s=["ViewSchema","viewSchema"].find(c=>t[c]!==void 0);if(s){let c=hd(t[s]);r.push(...c.errors),n.push(...c.warnings),delete e.viewSchema,c.value!==void 0&&(e.ViewSchema=c.value)}return{data:e,errors:r,warnings:n}}function xr(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 MK(t,e,r,n){let i=Gt(t,"v8Unlimited","V8Unlimited");if(i==null||i==="")return;let a=xr(t,"v8Unlimited","V8Unlimited");if(a===void 0){r.push(`${e}.v8Unlimited \u5FC5\u987B\u662F boolean \u6216 0/1`);return}return a&&n.push(`${e}.v8Unlimited=true \u4F1A\u53D6\u6D88\u8BE5\u8868\u540E\u7AEF V8 \u4E8B\u4EF6\u7684\u5355\u6B21 Jint \u8D85\u65F6\u3001\u8BED\u53E5\u3001\u9012\u5F52\u548C\u7D2F\u8BA1\u5206\u914D\u9884\u7B97\uFF1B\u4EC5\u5728\u4E1A\u52A1\u660E\u786E\u8981\u6C42\u5355\u4E8B\u52A1\u4E14\u5DF2\u8BC4\u4F30\u6570\u636E\u5E93\u9501\u3001\u56DE\u6EDA\u3001\u8FDE\u63A5\u8D85\u65F6\u4E0E\u8FDB\u7A0B\u5185\u5B58\u98CE\u9669\u65F6\u5F00\u542F\u3002\u8FDB\u7A0B\u5E38\u9A7B\u5185\u5B58\u4FDD\u62A4\u4ECD\u751F\u6548\uFF0C\u4E14\u4E0D\u4F1A\u5411\u5D4C\u5957\u63A5\u53E3\u7EE7\u627F\u3002`),a}function dR(t){let e=xr(t,"v8Limit","V8Limit");if(e!==void 0)return e;let r=xr(t,"v8Unlimited","V8Unlimited");return r===void 0?void 0:!r}function DK(t,e,r,n){let i=Gt(t,"v8Limit","V8Limit"),a=Gt(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(a==null||a===""))return;let o=i!=null&&i!=="",s=o?xr(t,"v8Limit","V8Limit"):dR(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(o&&a!==void 0){let c=xr(t,"v8Unlimited","V8Unlimited");c!==void 0&&s!==!c&&r.push(`${e}.v8Limit \u4E0E\u517C\u5BB9\u5B57\u6BB5 v8Unlimited \u7684\u8BED\u4E49\u51B2\u7A81`)}else a!==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 zK=["Detail","Edit","List","Card"],FK=["PC","Mobile","All"],jK=["ApiEngine","OpenDetail","OpenList","OpenForm","Navigate","Dial","Scan","Map","Refresh","Back","Copy"],LK=new Set(["v8code","v8codeshow","script","javascript","eval","onclick","function"]);function gx(t,e){let r=String(t??"").trim().toLowerCase();return e.find(n=>n.toLowerCase()===r)||""}function kn(t,...e){let r=new Set(e.map(i=>i.toLowerCase()));return Object.entries(t).find(([i])=>r.has(i.toLowerCase()))?.[1]}function yx(t,e="ViewSchema"){if(Array.isArray(t)){for(let r=0;r<t.length;r+=1){let n=yx(t[r],`${e}[${r}]`);if(n)return n}return""}if(!t||typeof t!="object")return"";for(let[r,n]of Object.entries(t)){if(LK.has(r.toLowerCase()))return`${e}.${r}`;let i=yx(n,`${e}.${r}`);if(i)return i}return""}function bx(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,a)=>{let o=ee(i);if(!Object.keys(o).length){n.push(`${e}[${a}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}let s=gx(kn(o,"ActionType","Type"),jK);if(!s){n.push(`${e}[${a}].ActionType \u4E0D\u53D7\u652F\u6301`);return}s==="ApiEngine"&&!_(o,"ApiEngineKey","apiEngineKey")&&n.push(`${e}[${a}] \u4F7F\u7528 ApiEngine \u65F6\u5FC5\u987B\u914D\u7F6E ApiEngineKey`);let c=kn(o,"SuccessActions");n.push(...bx(c,`${e}[${a}].SuccessActions`,r+1))}),n}function hd(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=yx(n);i&&e.push(`ViewSchema \u4E0D\u5141\u8BB8\u5305\u542B\u53EF\u6267\u884C\u524D\u7AEF\u811A\u672C\u5B57\u6BB5\uFF1A${i}`);let o=kn(n,"Views");o!==void 0&&!Array.isArray(o)?e.push("ViewSchema.Views \u5FC5\u987B\u662F JSON \u6570\u7EC4"):Array.isArray(o)?(o.length>100&&e.push("ViewSchema.Views \u6700\u591A\u5141\u8BB8 100 \u4E2A\u89C6\u56FE"),o.forEach((c,l)=>{let u=ee(c);if(!Object.keys(u).length){e.push(`ViewSchema.Views[${l}] \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}gx(kn(u,"Scene"),zK)||e.push(`ViewSchema.Views[${l}].Scene \u4E0D\u53D7\u652F\u6301`);let p=kn(u,"Device");p!==void 0&&!gx(p,FK)&&e.push(`ViewSchema.Views[${l}].Device \u4E0D\u53D7\u652F\u6301`);let d=kn(u,"Layout","LayoutJson");if(typeof d=="string")try{d=JSON.parse(d)}catch{e.push(`ViewSchema.Views[${l}].Layout \u4E0D\u662F\u5408\u6CD5 JSON`);return}if(d==null)return;let h=ee(d);if(!Object.keys(h).length&&(typeof d!="object"||Array.isArray(d))){e.push(`ViewSchema.Views[${l}].Layout \u5FC5\u987B\u662F JSON \u5BF9\u8C61`);return}e.push(...bx(kn(h,"Actions","ActionSchema"),`ViewSchema.Views[${l}].Layout.Actions`));let m=kn(h,"Blocks","Sections");m!==void 0&&!Array.isArray(m)?e.push(`ViewSchema.Views[${l}].Layout.Blocks \u5FC5\u987B\u662F JSON \u6570\u7EC4`):Array.isArray(m)&&(m.length>100&&e.push(`ViewSchema.Views[${l}].Layout.Blocks \u6700\u591A\u5141\u8BB8 100 \u4E2A\u533A\u5757`),m.forEach((g,y)=>{let v=ee(g);e.push(...bx(kn(v,"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 fR(t,e){let r=[],n=t.toLowerCase();if(n==="keyvalue"){let i=_(e,"data","options"),a=i?i.split(/[,,;;\n]/).map(o=>o.trim()).filter(Boolean).map(o=>{let[s,c]=o.split("|");return{Key:(s||"").trim(),Value:(c||s||"").trim()}}):fd(e.items).map(o=>({Key:_(o,"Key","key"),Value:_(o,"Value","label","name")}));return{data:JSON.stringify(a),config:{DataSource:"KeyValue",SelectLabel:"Value",SelectSaveField:"Key",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="data"){let i=_(e,"data","options"),a=i?i.split(/[,,;;\n]/).map(o=>o.trim()).filter(Boolean):Array.isArray(e.items)?e.items:[];return{data:JSON.stringify(a),config:{DataSource:"Data",SelectSaveFormat:"Text",EnableSearch:!1,DataSourceSqlRemote:!1},warnings:r}}if(n==="sql"){let i=_(e,"sql","Sql");return i||r.push("SQL \u6570\u636E\u6E90\u7F3A\u5C11 sql"),{config:{DataSource:"Sql",Sql:i,SelectLabel:_(e,"selectLabel","SelectLabel")||"Name",SelectSaveField:_(e,"selectSaveField","SelectSaveField")||"Id",DataSourceSqlRemote:e.dataSourceSqlRemote??e.DataSourceSqlRemote??!0,EnableSearch:e.enableSearch??e.EnableSearch??!0},warnings:r}}if(n==="apiengine"){let i=_(e,"apiEngineKey","DataSourceApiEngineKey");return i||r.push("\u63A5\u53E3\u5F15\u64CE\u6570\u636E\u6E90\u7F3A\u5C11 apiEngineKey"),{config:{DataSource:"ApiEngine",DataSourceApiEngineKey:i,SelectLabel:_(e,"selectLabel")||"name",SelectSaveField:_(e,"selectSaveField")||"id"},warnings:r}}if(n==="datasource"){let i=_(e,"dataSourceId","DataSourceId");return i||r.push("\u6570\u636E\u6E90\u5F15\u64CE\u914D\u7F6E\u7F3A\u5C11 dataSourceId"),{config:{DataSource:"DataSource",DataSourceId:i,SelectLabel:_(e,"selectLabel")||"Name",SelectSaveField:_(e,"selectSaveField")||"Id"},warnings:r}}if(n==="autonumber")return{config:{AutoNumberFixed:_(e,"prefix","AutoNumberFixed"),AutoNumberLength:ie(e,"length","AutoNumberLength")??4},warnings:r};if(n==="datetime")return{config:{DateTimeType:_(e,"dateTimeType","DateTimeType")||"datetime"},warnings:r};if(n==="joinform"){let i=_(e,"tableId"),a=_(e,"tableName"),o=_(e,"joinFieldName");return!i&&!a&&r.push("JoinForm \u7F3A\u5C11 tableId/tableName\uFF0C\u7981\u6B62\u4FDD\u5B58\u672A\u89E3\u6790\u76EE\u6807\u8868\u7684\u914D\u7F6E"),o||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:Dr({TableId:i,TableName:a,JoinFieldName:o})},warnings:r}}return r.push(`\u672A\u77E5 sourceType: ${t}\uFF0C\u5DF2\u8FD4\u56DE\u7A7A\u914D\u7F6E`),{config:{},warnings:r}}function fx(t,e){let r=Sr(t);return Dr({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||(md.has(r)||_r(t)||r==="numbertext"?"In":"Out"),DisplaySelect:e?.displaySelect??["opentable","joinform","department","selecttree"].includes(r),Equal:e?.equal??(md.has(r)||r==="numbertext"?!0:void 0),IsVisible:!0})}function Ao(t,e,r,n,i){return n.map(a=>{let o=GI(t,e,a.ref)||GI(t,r,a.ref)||(Ex(a.ref)?pR(e,r,a.ref):void 0);if(!o)throw new Error(`${i}: unknown field "${a.ref}" on table "${r||e}"`);return{meta:o,ref:a}})}function nt(t,...e){for(let r of e){let n=Gt(t,r);if(!(n==null||n===""))return typeof n=="string"?n:JSON.stringify(n)}return""}var VK=new Set(["id","osclient","isdeleted","createuserid","updateuserid","deleteuserid","tenantid","storeid","userid","userids","roleid","roleids","parentid","parentids","class","code","enname","endescription"]),kx=new Set(["button","divider","collapsegroup","tabs","alert","statictext","html","devcomponent"]),qK=new Set(["textarea","richtext","codeeditor","jsontable","imgupload","fileupload","tablechild","map","maparea","jointable","opentable","treecheckbox","transfer"]),BK=new Set(["text","textarea","select","multipleselect","radio","checkbox","datetime","date","numbertext","autonumber","switch","department","address","cascader","selecttree","opentable","joinform","autocomplete","taginput"]),md=new Set(["select","multipleselect","radio","checkbox","switch","department","selecttree","opentable","joinform","cascader"]);function Wt(t){return(t||"").trim().toLowerCase()}function st(t){return`${t.name||""} ${t.label||""} ${t.component||""} ${t.type||""}`.toLowerCase()}function ge(t,e){return e.some(r=>t.includes(r.toLowerCase()))}function Sr(t){return Wt(t.component||"Text")}function UK(t){return kx.has(Sr(t))}function ZK(t){return qK.has(Sr(t))}function JK(t){let e=t.name||"",r=Wt(e).replace(/[_\-\s]+/g,"");return!!(VK.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 Fc(t){return Ex(t.name)&&!["CreateTime","UpdateTime","UserName"].some(e=>e.toLowerCase()===t.name.toLowerCase())||JK(t)||UK(t)||ZK(t)?!0:Sr(t).includes("hidden")}function si(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 wr(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 gd(t){let e=Wt(t.type);return Sr(t)==="numbertext"||e.startsWith("decimal")||e==="int"||e==="bigint"}function _r(t){let e=st(t);return Sr(t)==="datetime"||ge(e,["time","date","\u65E5\u671F","\u65F6\u95F4"])}function HK(t){let e=Sr(t),r=md.has(e)||e==="numbertext"||e==="rate"||e==="progress";return{ref:t.name,displayType:r||_r(t)?"In":"Out",displaySelect:["opentable","joinform","department","selecttree"].includes(e),equal:r?!0:void 0}}function XI(t){let e=st(t),r=0;return ge(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),ge(e,["status","state","type","category","level","class","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])&&(r+=45),ge(e,["customer","member","user","owner","\u8D1F\u8D23\u4EBA","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8054\u7CFB\u4EBA"])&&(r+=35),_r(t)&&(r+=25),gd(t)&&!ge(e,["phone","mobile","tel","\u7535\u8BDD","\u624B\u673A"])&&(r+=15),Sr(t)==="textarea"&&(r-=25),r}function vx(t){let e=st(t),r=0;return ge(e,["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])&&(r+=70),ge(e,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])&&(r+=45),ge(e,["customer","member","user","owner","phone","mobile","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u7535\u8BDD","\u624B\u673A"])&&(r+=35),ge(e,["amount","money","price","total","count","qty","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D"])&&(r+=30),_r(t)&&(r+=15),Sr(t)==="autonumber"&&(r+=55),r}function KK(t){return si(t.filter(Fc))}function jc(t){let e=t.filter(n=>!Fc(n)),r=e.length?e:t;return si(wr(r,vx)).slice(0,Math.min(12,r.length))}function WK(t){let e=t.filter(n=>!Fc(n)&&BK.has(Sr(n))),r=wr(e,XI).filter(n=>XI(n)>0);return si(r.length?r:e).slice(0,Math.min(8,e.length))}function GK(t){let e=t.filter(r=>!Fc(r)&&(_r(r)||gd(r)||Wt(r.name)==="sort"));return si(wr(e,r=>{let n=st(r);return ge(n,["update","\u4FEE\u6539"])?80:ge(n,["create","\u521B\u5EFA"])?75:Wt(r.name)==="sort"?70:ge(n,["amount","money","price","total","count","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?60:20})).slice(0,Math.min(8,e.length))}function mR(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=st(n);return!Fc(n)&&gd(n)&&!ge(i,e)&&ge(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 si(wr(r,n=>ge(st(n),["amount","money","price","total","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D"])?80:40)).slice(0,6)}function XK(t){let e=jc(t),r=wr(e,a=>ge(st(a),["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])?100:0)[0],n=wr(e.filter(a=>a!==r),a=>ge(st(a),["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?80:0),i=e.filter(a=>a!==r&&!n.slice(0,1).includes(a));return si([r,...n.slice(0,1),...i].filter(Boolean)).slice(0,4)}function YK(t){return wr(jc(t),e=>ge(st(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])?100:0).filter(e=>ge(st(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])).slice(0,2)}function QK(t){return wr(jc(t),e=>{let r=st(e);return ge(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?90:_r(e)?60:0}).filter(e=>{let r=st(e);return _r(e)||ge(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])}).slice(0,3)}function hR(t,e=0){let r=ee(t),n=_(r,"name","Name");return n?{id:_(r,"id","Id")||n,name:n,label:_(r,"label","Label")||n,tableId:_(r,"tableId","TableId"),tableName:_(r,"tableName","TableName"),tableDescription:_(r,"tableDescription","TableDescription"),component:_(r,"component","Component")||"Text",type:_(r,"type","Type")||"varchar(500)"}:null}function yd(t){let e=hR(t);if(!e)return 150;let r=st(e),n=Sr(e);return["richtext","textarea","address","map","maparea","fileupload","imgupload"].includes(n)||ge(r,["address","remark","description","content","\u5730\u5740","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247"])?240:ge(r,["name","title","subject","customer","company","\u540D\u79F0","\u6807\u9898","\u4E3B\u9898","\u5BA2\u6237","\u4F01\u4E1A"])?200:_r(e)?170:gd(e)?140:n==="autonumber"||ge(r,["phone","mobile","email","code","number","\u7F16\u53F7","\u5355\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])?160:md.has(n)||ge(r,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?130:150}function En(t,e={}){return{Name:t.name,Label:t.label||t.name,...e}}function ua(t,e,r){let n=[];for(let i of t)if(!(!i?.name||r.has(Wt(i.name)))&&(r.add(Wt(i.name)),n.push(i),n.length>=e))break;return n}function Tx(t,e,r=""){let n=e.map(hR).filter(Boolean),i=jc(n),a=String(t||r||n[0]?.tableDescription||n[0]?.tableName||"\u4E1A\u52A1\u6A21\u5757").trim(),o=String(r||n[0]?.tableDescription||"").trim(),s=o&&o!==a?o:`${a}\u7684\u4E1A\u52A1\u6570\u636E\u3001\u8FDB\u5EA6\u4E0E\u5173\u952E\u6307\u6807`,c=wr(i,A=>{let U=st(A);return ge(U,["title","subject","\u6807\u9898","\u4E3B\u9898"])?150:ge(U,["name","\u540D\u79F0"])?130:Sr(A)==="autonumber"||ge(U,["no","code","number","\u7F16\u53F7","\u5355\u53F7","\u7F16\u7801"])?110:vx(A)})[0]||i[0],l=wr(i.filter(A=>A!==c),A=>ge(st(A),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])?100:0).filter(A=>ge(st(A),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])),u=mR(n).filter(A=>A!==c),p=wr(n.filter(_r),A=>ge(st(A),["create","\u521B\u5EFA"])?100:50),d=wr(i.filter(A=>A!==c&&!l.includes(A)&&!u.includes(A)),A=>{let U=st(A);return ge(U,["customer","member","user","owner","contact","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u8054\u7CFB\u4EBA"])?90:_r(A)?70:vx(A)}).slice(0,1),h=si([...l.slice(0,1),...u.slice(0,1)]),m=si([c,...d,...h].filter(Boolean)).map(A=>A.name),g=c?Math.min(520,Math.max(340,yd(c)+d.length*28+h.length*70)):0,y=[{Icon:"fas fa-chart-column",Tone:"primary"},{Icon:"fas fa-calculator",Tone:"success"}],v=u.slice(0,2).map((A,U)=>({Key:`Aggregate:${A.name}`,Label:`${A.label||A.name}\u5408\u8BA1`,Source:"Field",Field:A.name,...y[U]}));v.push({Key:"DataCount",Label:"\u7B5B\u9009\u7ED3\u679C",Source:"DataCount",Icon:"fas fa-layer-group",Tone:"info"}),v.length<3&&v.push({Key:"PageCount",Label:"\u672C\u9875\u5C55\u793A",Source:"PageCount",Icon:"fas fa-list-check",Tone:"warning"});let x=new Set(c?[Wt(c.name)]:[]),b=ua(d,1,x),S=ua(l,1,x),k=ua(l,1,x),w=ua(u,1,x),T=ua(p,2,x),C=ua(i,2,x),$=ua([...u,...p],2,x),P={Title:a,Description:s,Metrics:v};return{Views:[{Key:"auto-list-pc",Scene:"List",Device:"PC",Priority:100,Layout:{Hero:P,List:{Density:"Compact",Columns:c?[{Key:`composite:${c.name}`,Field:c.name,Lines:d.map(A=>En(A,{Icon:_r(A)?"fas fa-clock":"fas fa-circle-info",Tone:"info"})),TrailingFields:h.map(A=>En(A,{Icon:l.includes(A)?"fas fa-circle-check":"fas fa-coins",Tone:l.includes(A)?"success":"warning",DisplayStyle:l.includes(A)?"Tag":"Text"})),RequiredFields:m,Align:"Left",MinWidth:g}]:[]}}},{Key:"auto-card-mobile",Scene:"Card",Device:"Mobile",Priority:100,Layout:{Hero:{...P,Metrics:v.map(A=>({...A}))},Card:{Preset:"Business",AvatarTextField:c?.name||"",TitleField:c?.name||"",SubtitleFields:b.map(A=>En(A,{Icon:"fas fa-circle-info",Tone:"info"})),StatusFields:S.map(A=>En(A,{DisplayStyle:"Tag",Icon:"fas fa-circle-check",Tone:"success"})),TopFields:k.map(A=>En(A,{DisplayStyle:"Tag",Icon:"fas fa-tag",Tone:"primary"})),RightFields:w.map(A=>En(A,{Icon:"fas fa-coins",Tone:"danger",FontWeight:"700"})),Fields:C.map(A=>En(A)),MetaFields:T.map(A=>En(A,{Icon:"fas fa-clock",Tone:"info"})),BottomFields:$.map(A=>En(A,{Icon:_r(A)?"fas fa-calendar":"fas fa-chart-simple",Tone:"warning"})),HideIndex:!0,ShowCreateTime:T.length===0,ShowUpdateTime:!1}}}]}}function eW(t,e,r){let n=t.length?t:[pR(e,r,"CreateTime")],i=n.find(a=>Wt(a.name)==="createtime")||n.find(a=>Wt(a.name)==="updatetime")||n.find(a=>Wt(a.name)==="sort");if(i)return JSON.stringify([{Id:i.id,Name:i.name,Type:Wt(i.name)==="sort"?"ASC":"DESC",Sort:0}])}function tW(t,e,r,n){let i=Gt(t,"DefaultOrderBy");if(i!=null&&i!=="")return typeof i=="string"?i:JSON.stringify(i);let a=Gt(t,"defaultOrderBy");if(a!=null&&a!==""){let s=Array.isArray(a)||typeof a=="string"&&a.trim().startsWith("[")?vr({value:a},"value"):[{ref:String(a).trim(),type:"DESC"}];return JSON.stringify(Ao(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 o=vr(t,"orderBy","OrderBy","defaultSort","DefaultSort","sortBy","SortBy");if(o.length)return JSON.stringify(Ao(e,r,n,o,"module.defaultOrderBy").map(({meta:s,ref:c},l)=>({Id:s.id,Name:s.name,Type:c.type||"DESC",Sort:l})))}function rW(t,e,r,n){if(!r&&!n)return{};let i=$o(e,r).length?$o(e,r):$o(e,n),a={},o=vr(t,"searchFields","SearchFields","searchFieldNames","SearchFieldNames"),s=o.length?Ao(e,r,n,o,"module.searchFields"):WK(i).map(h=>({meta:h,ref:HK(h)}));!nt(t,"searchFieldIds","SearchFieldIds")&&s.length&&(a.SearchFieldIds=JSON.stringify(s.map(({meta:h,ref:m})=>fx(h,m))));let c=vr(t,"listFields","ListFields","tableFields","TableFields","columns","Columns"),l=c.length?Ao(e,r,n,c,"module.listFields"):jc(i).map(h=>({meta:h,ref:{ref:h.name}}));!nt(t,"tableDiyFieldIds","TableDiyFieldIds")&&l.length&&(a.TableDiyFieldIds=JSON.stringify(l.map(({meta:h})=>h.id))),!nt(t,"selectFields","SelectFields")&&l.length&&(a.SelectFields=JSON.stringify(l.map(({meta:h,ref:m})=>fx(h,m))));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 h of u){if(nt(t,...h.explicitKeys))continue;let m=vr(t,...h.refKeys),g={SortFieldIds:GK(i),NotShowFields:KK(i),MobileListFields:XK(i),CardTitleTagFields:YK(i),CardBottomTagFields:QK(i),InTableEditFields:[]};if(!m.length&&!g[h.canonical]?.length)continue;let y=m.length?Ao(e,r,n,m,`module.${h.canonical}`):g[h.canonical].map(v=>({meta:v,ref:{ref:v.name}}));a[h.canonical]=JSON.stringify(h.objectArray?y.map(({meta:v,ref:x})=>fx(v,x)):y.map(({meta:v})=>v.id))}let p=vr(t,"statisticsFieldNames","StatisticsFieldNames","statFields","StatFields");if(!nt(t,"statisticsFields","StatisticsFields")){let h=p.length?Ao(e,r,n,p,"module.statisticsFields"):mR(i).map(m=>({meta:m,ref:{ref:m.name,type:"Sum"}}));h.length&&(a.StatisticsFields=JSON.stringify(h.map(({meta:m,ref:g})=>({Id:m.id,Type:g.type||"Sum"}))))}let d=tW(t,e,r,n)||(nt(t,"DefaultOrderBy","defaultOrderBy")?void 0:eW(i,r,n));return d&&(a.DefaultOrderBy=d),a}function YI(t,e,r){let n=fd(ee(e).Tables);for(let i of n){let a=_(i,"Id","id"),o=_(i,"Name","name");if(!a||!o)continue;r?.set(o.toLowerCase(),a);let s=Gt(i,"_Fields","Fields","fields"),c=Array.isArray(s)?fd(s):[];for(let l of c){let u=_(l,"Id","id"),p=_(l,"Name","name");!u||!p||uR(t,{id:u,name:p,label:_(l,"Label","label")||p,tableId:a,tableName:o,tableDescription:_(i,"Description","description")||o,component:_(l,"Component","component")||"Text",type:_(l,"Type","type")||"varchar(255)"})}}}function Dc(t){return Wt(_(t,"component","Component")||"Text")}function nW(t){return`${_(t,"name","Name")} ${_(t,"label","Label")} ${_(t,"component","Component")}`.toLowerCase()}function iW(t,e){let r=nW(t),n=Dc(t);return["imgupload","fileupload","richtext","codeeditor","jsontable","tablechild","map","maparea","textarea"].includes(n)||ge(r,["remark","note","content","file","image","attach","map","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247","\u5730\u56FE"])?"attachment":ge(r,["phone","mobile","email","address","city","contact","\u8054\u7CFB\u4EBA","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1","\u5730\u5740","\u57CE\u5E02"])?"contact":ge(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 xx(t){let e=ce(t,"fields","Fields"),r=Gt(t,"tabs","Tabs"),n=new Map,i=ie(t,"column","Column")??(e.length>6?2:void 0);if(r!=null&&r!=="")return{fieldTabs:n,column:i};let a=e.filter(l=>!kx.has(Dc(l)));if(a.length<=12)return{fieldTabs:n,column:i};let o={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 a.forEach((l,u)=>{let p=_(l,"name","Name");if(!p||_(l,"tab","Tab"))return;let d=iW(l,u);n.set(p,d),s.add(d)}),{tabs:["basic","contact","business","attachment","extra"].filter(l=>s.has(l)).map(l=>({Id:l,Name:o[l].Name,Icon:o[l].Icon,Sort:o[l].Sort})),fieldTabs:n,column:i}}function mx(t){let e=[],r=[],n=[],i=ce(t,"roles","Roles"),a=ce(t,"tables","Tables"),o=ce(t,"engines","Engines"),s=ce(t,"modules","Modules"),c=ce(t,"events","Events"),l=ce(t,"dataSources","DataSources"),u=ce(t,"pages","Pages"),p=ce(t,"printTemplates","PrintTemplates"),d=ce(t,"workflows","Workflows"),h=ce(t,"jobs","Jobs"),m=ce(t,"permissions","Permissions"),g=new Map;!a.length&&!o.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 y=fW(t);return e.push(...y.errors),r.push(...y.warnings),i.forEach(v=>n.push(`save_role ${_(v,"name","Name")}`)),a.forEach((v,x)=>{let b=_(v,"name","Name");b||e.push(`tables[${x}].name \u4E0D\u80FD\u4E3A\u7A7A`),MK(v,`tables[${x}]`,e,r),n.push(`create_table ${b||`(index ${x})`}`),xx(v).tabs?.length&&r.push(`table ${b||`(index ${x})`} has many fields; generator will create diy_table.Tabs and assign empty field Tab values automatically`),b&&g.set(b.toLowerCase(),new Set),ce(v,"fields","Fields").forEach((w,T)=>{let C=_(w,"name","Name"),$=_(w,"label","Label");C||e.push(`tables[${x}].fields[${T}].name \u4E0D\u80FD\u4E3A\u7A7A`),$||e.push(`tables[${x}].fields[${T}].label \u4E0D\u80FD\u4E3A\u7A7A`),b&&C&&g.get(b.toLowerCase())?.add(C.toLowerCase()),b&&$&&g.get(b.toLowerCase())?.add($.toLowerCase()),n.push(`add_field ${b}.${C}`)});let k=new Set(ce(v,"fields","Fields").map(w=>_(w,"name","Name").toLowerCase()).filter(Boolean));["id","createtime","updatetime","createuser","osclient"].forEach(w=>k.add(w)),ce(v,"indexes","Indexes").forEach((w,T)=>{let C=Ro(w,"columns","Columns");C.length||e.push(`tables[${x}].indexes[${T}].columns \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5`);for(let $ of C)k.has($.toLowerCase())||e.push(`tables[${x}].indexes[${T}] references unknown physical field "${$}" on table "${b}"`);C.some(($,P)=>C.findIndex(A=>A.toLowerCase()===$.toLowerCase())!==P)&&e.push(`tables[${x}].indexes[${T}] \u5305\u542B\u91CD\u590D\u5B57\u6BB5`),n.push(`create_index ${b}.${_(w,"name","Name")||C.join("_")}`)})}),l.forEach(v=>n.push(`save_data_source ${_(v,"dataSourceKey","DataSourceKey")}`)),o.forEach((v,x)=>{let b=_(v,"apiEngineKey","ApiEngineKey");b||e.push(`engines[${x}].apiEngineKey \u4E0D\u80FD\u4E3A\u7A7A`),DK(v,`engines[${x}]`,e,r),n.push(`upsert_engine ${b}`)}),c.forEach(v=>n.push(`save_event ${_(v,"formEngineKey","FormEngineKey")}/${_(v,"eventType","EventType")}`)),s.forEach(v=>{let x=Oo(v);e.push(...x.errors),r.push(...x.warnings);let b=_(v,"table","tableName","diyTableName","DiyTableName"),S=_(v,"name","Name"),k=_(v,"openType","OpenType"),w=_(v,"microServiceKey","MicroServiceKey"),T=_(v,"microServiceRoutePath","MicroServiceRoutePath");if(k.toLowerCase()==="microservice"||!!(ie(v,"isMicroiService","IsMicroiService")===1||w||T||_(v,"microServiceId","MicroServiceId")||_(v,"microServicePageId","MicroServicePageId"))){if(w||e.push(`modules.${S||"(unnamed)"}.microServiceKey \u4E0D\u80FD\u4E3A\u7A7A`),T||e.push(`modules.${S||"(unnamed)"}.microServiceRoutePath \u4E0D\u80FD\u4E3A\u7A7A`),T)try{Sx(T)}catch($){e.push(`modules.${S||"(unnamed)"}.microServiceRoutePath ${$ instanceof Error?$.message:String($)}`)}n.push(`resolve_microservice_binding ${w||"(missing)"}${T||"/(missing)"}`)}if(b&&g.has(b.toLowerCase())){let $=g.get(b.toLowerCase())||new Set,P=[["listFields",vr(v,"listFields","ListFields","tableFields","TableFields","columns","Columns")],["searchFields",vr(v,"searchFields","SearchFields","searchFieldNames","SearchFieldNames")],["sortFields",vr(v,"sortFields","SortFields")],["hiddenFields",vr(v,"hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName")],["mobileFields",vr(v,"mobileFields","MobileFields")]];for(let[A,U]of P)for(let Y of U)!$.has(Y.ref.toLowerCase())&&!Ex(Y.ref)&&e.push(`modules.${S||b}.${A} references unknown field "${Y.ref}" on table "${b}"`)}b&&!vr(v,"listFields","ListFields","tableFields","TableFields","columns","Columns").length&&!nt(v,"TableDiyFieldIds","SelectFields")&&r.push(`module ${S||b} has no listFields; generator will use the first business fields from ${b}`),n.push(`create_or_update_module ${_(v,"name","Name")}`)}),m.forEach(v=>n.push(`set_permission ${_(v,"roleId","RoleId")||"admin"}`)),u.forEach((v,x)=>{let b=Sn(v.json??v.JsonObj??v.JsonStr??v);e.push(...b.errors.map(S=>`pages[${x}]: ${S}`)),r.push(...b.warnings.map(S=>`pages[${x}]: ${S}`)),n.push(`save_page ${_(v,"title","Title")}`)}),p.forEach((v,x)=>{let b=ca(v.PageObj??v.pageObj),S=la(v.PrintObj??v.printObj);e.push(...b.errors.map(k=>`printTemplates[${x}].PageObj: ${k}`)),r.push(...b.warnings.map(k=>`printTemplates[${x}].PageObj: ${k}`)),e.push(...S.errors.map(k=>`printTemplates[${x}].PrintObj: ${k}`)),r.push(...S.warnings.map(k=>`printTemplates[${x}].PrintObj: ${k}`)),n.push(`save_print_template ${_(v,"title","Title")}`)}),d.forEach((v,x)=>{let b=_x(v);e.push(...b.errors.map(S=>`workflows[${x}]: ${S}`)),r.push(...b.warnings.map(S=>`workflows[${x}]: ${S}`)),n.push(`save_workflow ${_(ee(v.FlowDesign??v.flowDesign??v),"FlowName","flowName","name")}`)}),h.forEach(v=>n.push(`save_job ${_(v,"jobName","JobName")}`)),{plan:n,errors:e,warnings:r}}function Cx(t){return{flow:ee(t.FlowDesign??t.flowDesign??t),nodes:ce(t,"Nodes","nodes"),lines:ce(t,"Lines","lines")}}function Io(t){return _(t,"Id","id","NodeId","nodeId")}function pa(t){return _(t,"NodeName","nodeName","Name","name")}function gR(t){return _(t,"NodeType","nodeType","Type","type")}function wx(t){let e=`${gR(t)} ${pa(t)}`.toLowerCase();return e.includes("start")||e.includes("begin")||e.includes("\u5F00\u59CB")||e.includes("\u53D1\u8D77")}function QI(t){let e=`${gR(t)} ${pa(t)}`.toLowerCase();return e.includes("end")||e.includes("finish")||e.includes("\u7ED3\u675F")||e.includes("\u5B8C\u6210")}function _x(t){let e=[],r=[],{flow:n,nodes:i,lines:a}=Cx(t),o=_(n,"FlowName","flowName","Name","name"),s=_(n,"TableId","tableId"),c=_(n,"table","tableName","TableName","diyTableName","DiyTableName"),l=new Map,u=new Map,p=new Map;o||e.push("FlowDesign.FlowName \u4E0D\u80FD\u4E3A\u7A7A"),i.length||e.push("Nodes \u81F3\u5C11\u9700\u8981\u5305\u542B\u5F00\u59CB\u3001\u5BA1\u6279/\u4E1A\u52A1\u3001\u7ED3\u675F\u8282\u70B9"),a.length||e.push("Lines \u81F3\u5C11\u9700\u8981\u8FDE\u63A5\u5F00\u59CB\u5230\u4E0B\u4E00\u8282\u70B9"),!s&&!c&&r.push("FlowDesign.TableId \u4E3A\u7A7A\uFF1B\u666E\u901A\u5BA1\u6279\u6D41\u5EFA\u8BAE\u7ED1\u5B9A\u4E1A\u52A1 diy_table"),i.forEach((m,g)=>{let y=Io(m),v=pa(m);y||e.push(`Nodes[${g}].Id/NodeId \u4E0D\u80FD\u4E3A\u7A7A`),v||e.push(`Nodes[${g}].NodeName \u4E0D\u80FD\u4E3A\u7A7A`),y&&(l.has(y)&&e.push(`\u8282\u70B9 Id \u91CD\u590D\uFF1A${y}`),l.set(y,m))}),a.forEach((m,g)=>{let y=_(m,"Id","id","LineId","lineId")||`(index ${g})`,v=_(m,"FromNodeId","fromNodeId"),x=_(m,"ToNodeId","toNodeId");v||e.push(`Lines[${g}].FromNodeId \u4E0D\u80FD\u4E3A\u7A7A`),x||e.push(`Lines[${g}].ToNodeId \u4E0D\u80FD\u4E3A\u7A7A`),v&&!l.has(v)&&e.push(`\u8FDE\u7EBF ${y} \u7684 FromNodeId \u4E0D\u5B58\u5728\uFF1A${v}`),x&&!l.has(x)&&e.push(`\u8FDE\u7EBF ${y} \u7684 ToNodeId \u4E0D\u5B58\u5728\uFF1A${x}`),v===x&&v&&r.push(`\u8FDE\u7EBF ${y} \u6307\u5411\u81EA\u8EAB\uFF0C\u8BF7\u786E\u8BA4\u662F\u5426\u4E3A\u6709\u610F\u5FAA\u73AF`),v&&u.set(v,[...u.get(v)||[],m]),x&&p.set(x,[...p.get(x)||[],m])});let d=i.filter(wx),h=i.filter(QI);return d.length!==1&&e.push(`\u9700\u8981\u4E14\u4EC5\u9700\u8981 1 \u4E2A\u5F00\u59CB\u8282\u70B9\uFF0C\u5F53\u524D ${d.length} \u4E2A`),h.length<1&&e.push("\u81F3\u5C11\u9700\u8981 1 \u4E2A\u7ED3\u675F\u8282\u70B9"),i.forEach(m=>{let g=Io(m),y=pa(m)||g;if(!g)return;let v=u.get(g)||[],x=p.get(g)||[];!wx(m)&&x.length===0&&r.push(`\u8282\u70B9 ${y} \u6CA1\u6709\u5165\u7EBF`),!QI(m)&&v.length===0&&r.push(`\u8282\u70B9 ${y} \u6CA1\u6709\u51FA\u7EBF`),v.length>1&&(_(m,"LineValueV8","lineValueV8","V8Code","v8Code")||r.push(`\u8282\u70B9 ${y} \u6709 ${v.length} \u6761\u51FA\u7EBF\uFF0C\u5EFA\u8BAE\u914D\u7F6E LineValueV8\uFF0C\u5E76\u4F18\u5148\u7528 V8.NextNodeId \u6307\u5B9A\u4E0B\u4E00\u8282\u70B9`))}),{ok:e.length===0,errors:e,warnings:r,summary:{flowName:o,tableId:s,table:c,nodeCount:i.length,lineCount:a.length,startNodes:d.map(m=>({id:Io(m),name:pa(m)})),endNodes:h.map(m=>({id:Io(m),name:pa(m)}))}}}function aW(t){let e=t.indexOf(WI);if(e<0)return null;let r=e+WI.length,n=t.indexOf(PK,r);if(n<0)return null;try{return ee(JSON.parse(t.slice(r,n).trim()))}catch{return null}}function eR(t){return t==null||String(t).trim()===""}function tR(t,e){let r=_(t,"field","Field"),n=_(t,"operator","Operator")||"eq",i=Gt(t,"value","Value"),a=r?e[r]:void 0,o=a==null?"":String(a),s=i==null?"":String(i);if(n==="empty")return eR(a);if(n==="notEmpty")return!eR(a);if(n==="contains")return o.includes(s);if(n==="notContains")return!o.includes(s);if(n==="startsWith")return o.startsWith(s);if(n==="endsWith")return s===""||o.endsWith(s);if(["gt","gte","lt","lte"].includes(n)){let c=Number(a),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"?o!==s:o===s}function oW(t){let e=ee(t.workflow),r=ee(t.formData),n=_(t,"lineValueV8Code","LineValueV8","code");if(!n&&Object.keys(e).length>0){let{nodes:s}=Cx(e),c=_(t,"nodeId","NodeId"),l=(c?s.find(u=>Io(u)===c):s.find(wx)||s[0])||{};n=_(l,"LineValueV8","lineValueV8","V8Code","v8Code")}let i=aW(n),a=ce(i||{},"routes","Routes");if(!i||a.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 o=a.find(s=>!!Gt(s,"isDefault","IsDefault"))||null;for(let s of a){if(s===o)continue;let c=ce(s,"rules","Rules").filter(u=>_(u,"field","Field"));if(c.length===0)continue;if(_(s,"match","Match")==="any"?c.some(u=>tR(u,r)):c.every(u=>tR(u,r)))return{ok:!0,selectedRoute:s,assignment:rR(s),source:"matched"}}return{ok:!!o,selectedRoute:o,assignment:o?rR(o):null,source:o?"default":"none"}}function rR(t){let e=_(t,"lineValue","LineValue"),r=_(t,"toNodeId","ToNodeId");return e?{LineValue:e}:{NextNodeId:r}}function sW(t,e){let{flow:r,nodes:n,lines:i}=Cx(t),a={...r},o=_(r,"table","tableName","TableName","diyTableName","DiyTableName");if(!_(a,"TableId","tableId")&&o){let u=e.get(o.toLowerCase());u&&(a.TableId=u)}let s=new Map,c=n.map((u,p)=>{let d=Io(u)||`wf_node_${p+1}_${hx().slice(0,8)}`,h={...u,Id:d},m=pa(h);return m&&s.set(d,m),h}),l=i.map((u,p)=>{let d=_(u,"FromNodeId","fromNodeId"),h=_(u,"ToNodeId","toNodeId"),m=_(u,"LineName","lineName")||`${s.get(d)||d||"\u5F53\u524D\u8282\u70B9"} \u5230 ${s.get(h)||h||"\u4E0B\u4E00\u8282\u70B9"}`;return{...u,Id:_(u,"Id","id","LineId","lineId")||`wf_line_${p+1}_${hx().slice(0,8)}`,LineName:m}});return{FlowDesign:a,Nodes:c,Lines:l}}async function br(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 nR(t,e){let r=_(e,"apiEngineKey","ApiEngineKey"),n=_(e,"apiName","ApiName","name","Name")||r,i=_(e,"category","Category")||"AI\u751F\u6210",a=Gt(e,"code","Code","ApiV8Code"),o=typeof a=="string",s=o?String(a):"",c=dR(e),l=await t.getEngineCode(r);return l.Code===1?!o&&c!==void 0?t.updateEngineRuntimeLimit(r,c):o?t.saveEngineCode(r,s,{functionDescription:_(e,"functionDescription","FunctionDescription")||void 0,changeSummary:_(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:_(e,"functionDescription","FunctionDescription")||void 0,changeSummary:_(e,"changeSummary","ChangeSummary")||void 0})}function cW(t,e,r,n){let i=_(t,"table","tableName","diyTableName","DiyTableName"),a=Oo(t);if(a.errors.length)throw new Error(a.errors.join(`
|
|
130
130
|
`));let o=_(t,"diyTableId","DiyTableId")||(i?e.get(i.toLowerCase()):""),s=i||_(t,"DiyTableName","diyTableName"),c=n?rW(t,n,o||"",s):{},l=ie(t,"display","Display")??1,u=ie(t,"appDisplay","AppDisplay")??1,p=_(t,"openType","OpenType")||"Diy",d=a.data.ViewSchema;if(!d&&n&&o&&(l===1||u===1)&&Wt(p)==="diy"){let m=$o(n,o).length?$o(n,o):$o(n,s);if(m.length){let g=Tx(_(t,"name","Name"),m,m[0]?.tableDescription||s),y=hd(g);if(!y.ok)throw new Error(y.errors.join(`
|
|
131
131
|
`));d=y.value}}return Dr({...a.data,...c,Name:_(t,"name","Name"),DiyTableId:o,ParentId:_(t,"parentId","ParentId")||(r?r.get(_(t,"parentName","ParentName").toLowerCase()):void 0),ComponentName:_(t,"componentName","ComponentName"),ComponentPath:_(t,"componentPath","ComponentPath"),Display:l,AppDisplay:u,HasChild:ie(t,"hasChild","HasChild"),OpenType:p,Url:_(t,"url","Url"),Sort:ie(t,"sort","Sort"),Icon:_(t,"icon","Icon"),SearchFieldIds:nt(t,"searchFieldIds","SearchFieldIds")||c.SearchFieldIds,TableDiyFieldIds:nt(t,"tableDiyFieldIds","TableDiyFieldIds")||c.TableDiyFieldIds,SelectFields:nt(t,"selectFields","SelectFields")||c.SelectFields,DefaultOrderBy:nt(t,"DefaultOrderBy")||c.DefaultOrderBy,SqlWhere:_(t,"sqlWhere","SqlWhere"),SqlJoin:_(t,"sqlJoin","SqlJoin"),JoinTables:nt(t,"joinTables","JoinTables"),SortFieldIds:nt(t,"sortFieldIds","SortFieldIds")||c.SortFieldIds,NotShowFields:nt(t,"notShowFields","NotShowFields")||c.NotShowFields,StatisticsFields:nt(t,"statisticsFields","StatisticsFields")||c.StatisticsFields,InTableEdit:ie(t,"inTableEdit","InTableEdit"),InTableEditFields:nt(t,"inTableEditFields","InTableEditFields")||c.InTableEditFields,MobileListFields:nt(t,"mobileListFields","MobileListFields")||c.MobileListFields,CardTitleTagFields:nt(t,"cardTitleTagFields","CardTitleTagFields")||c.CardTitleTagFields,CardBottomTagFields:nt(t,"cardBottomTagFields","CardBottomTagFields")||c.CardBottomTagFields,MenuBadgeEnabled:ie(t,"menuBadgeEnabled","MenuBadgeEnabled"),MenuBadgeApiEngineKey:_(t,"menuBadgeApiEngineKey","MenuBadgeApiEngineKey"),EnableViewSchema:ie(t,"enableViewSchema","EnableViewSchema")??0,ViewSchemaVersion:_(t,"viewSchemaVersion","ViewSchemaVersion")||(d?"1.0":void 0),ViewConfigVersion:ie(t,"viewConfigVersion","ViewConfigVersion")??(d?1:void 0),ViewSchema:d,IsMicroiService:ie(t,"isMicroiService","IsMicroiService"),MicroServiceId:_(t,"microServiceId","MicroServiceId"),MicroServicePageId:_(t,"microServicePageId","MicroServicePageId"),MicroServiceRoutePath:_(t,"microServiceRoutePath","MicroServiceRoutePath"),MicroServiceKey:_(t,"microServiceKey","MicroServiceKey")})}function lW(t){let e=_(t,"formOpenType","FormOpenType"),r=_(t,"formOpenWidth","FormOpenWidth");if(e)return{type:e,width:r||"80%"};let i=ce(t,"fields","Fields").filter(c=>!kx.has(Dc(c))),a=i.filter(c=>Dc(c)==="tablechild").length,o=i.filter(c=>["tablechild","richtext","codeeditor","jsontable","imgupload","fileupload","map","maparea","devcomponent"].includes(Dc(c))).length;return{type:i.length>=36||a>=2||i.length>=28&&a>=1||o>=7?"Drawer":"Dialog",width:r||"80%"}}function uW(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 yR(t){let e=Gt(t,"relation","Relation");if(!e||typeof e!="object"||Array.isArray(e))return;let r=ee(e);return{cardinality:uW(_(r,"cardinality","Cardinality")),targetTable:_(r,"targetTable","TargetTable","table","Table"),joinFieldName:_(r,"joinFieldName","JoinFieldName","foreignKey","ForeignKey"),childForeignKey:_(r,"childForeignKey","ChildForeignKey","foreignKey","ForeignKey"),childModule:_(r,"childModule","ChildModule","module","Module"),primaryTableFieldName:_(r,"primaryTableFieldName","PrimaryTableFieldName")||"Id"}}function pW(t){if(typeof t=="string"){if(!t.trim())return{};try{return ee(JSON.parse(t))}catch{return{}}}return ee(t)}function dW(t){return _(t,"table","tableName","diyTableName","DiyTableName")}function fW(t){let e=[],r=[],n=ce(t,"tables","Tables"),i=ce(t,"modules","Modules"),a=new Map,o=new Map;for(let s of n){let c=_(s,"name","Name");c&&a.set(Ie(c),s)}for(let s of i){let c=_(s,"name","Name");c&&o.set(Ie(c),s)}return n.forEach((s,c)=>{let l=_(s,"name","Name"),u=ce(s,"fields","Fields"),p=new Set(u.map(d=>Ie(_(d,"name","Name"))).filter(Boolean));u.forEach((d,h)=>{let m=Ie(_(d,"component","Component"));if(m!=="joinform"&&m!=="tablechild")return;let g=`tables[${c}].fields[${h}]`,y=_(d,"name","Name"),v=yR(d);if(!v){e.push(`${g} (${l}.${y}) \u4F7F\u7528 ${m==="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(v.cardinality||e.push(`${g}.relation.cardinality \u4EC5\u5141\u8BB8 1:1\u3001N:1 \u6216 1:N`),!v.targetTable){e.push(`${g}.relation.targetTable \u4E0D\u80FD\u4E3A\u7A7A`);return}Ie(v.targetTable)===Ie(l)&&e.push(`${g} \u5173\u8054\u76EE\u6807 ${v.targetTable} \u4E0E\u5F53\u524D\u8868\u76F8\u540C\uFF1BJoinForm/TableChild \u7981\u6B62\u81EA\u5173\u8054`);let x=a.get(Ie(v.targetTable));if(!x){e.push(`${g}.relation.targetTable \u5F15\u7528\u672A\u5728 Manifest tables \u4E2D\u58F0\u660E\u7684\u8868 "${v.targetTable}"\uFF1B\u5B8C\u6574\u7CFB\u7EDF\u751F\u6210\u5FC5\u987B\u58F0\u660E\u76EE\u6807\u8868\u4EE5\u5B8C\u6210\u524D\u7F6E\u6821\u9A8C`);return}if(m==="joinform"){v.cardinality!=="1:1"&&v.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`),v.joinFieldName?p.has(Ie(v.joinFieldName))?Ie(v.joinFieldName)===Ie(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 "${v.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}v.cardinality!=="1:N"&&e.push(`${g} \u7684 TableChild \u53EA\u5141\u8BB8 1:N\uFF1B1:1/N:1 \u5E94\u4F7F\u7528 JoinForm`);let b=ce(x,"fields","Fields"),S=new Set(b.map(w=>Ie(_(w,"name","Name"))).filter(Boolean));if(v.childForeignKey?S.has(Ie(v.childForeignKey))||e.push(`${g}.relation.childForeignKey \u5F15\u7528\u5B50\u8868 ${v.targetTable} \u4E0D\u5B58\u5728\u7684\u5B57\u6BB5 "${v.childForeignKey}"`):e.push(`${g}.relation.childForeignKey \u4E0D\u80FD\u4E3A\u7A7A`),!v.childModule)e.push(`${g}.relation.childModule \u4E0D\u80FD\u4E3A\u7A7A`);else{let w=o.get(Ie(v.childModule));w?(Ie(dW(w))!==Ie(v.targetTable)&&e.push(`${g}.relation.childModule \u5FC5\u987B\u7ED1\u5B9A\u5B50\u8868 ${v.targetTable}`),(ie(w,"display","Display")!==0||ie(w,"appDisplay","AppDisplay")!==0||ie(w,"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 "${v.childModule}"`)}let k=ce(x,"indexes","Indexes").some(w=>{let T=Ro(w,"columns","Columns").map(Ie);return T.length>=2&&T[0]==="osclient"&&T[1]===Ie(v.childForeignKey)});v.childForeignKey&&!k&&e.push(`${g} \u7684\u5B50\u8868 ${v.targetTable} \u5FC5\u987B\u58F0\u660E\u4EE5 (OsClient, ${v.childForeignKey}) \u5F00\u5934\u7684\u7EC4\u5408\u7D22\u5F15`)})}),{errors:e,warnings:r}}function mW(t,e,r,n){let i=Ie(_(t,"component","Component")),a=yR(t);if(!a||i!=="joinform"&&i!=="tablechild")throw new Error(`${e}.${_(t,"name","Name")} \u7F3A\u5C11\u6709\u6548 relation`);let o=r.get(Ie(a.targetTable));if(!o)throw new Error(`\u65E0\u6CD5\u89E3\u6790\u5173\u8054\u76EE\u6807\u8868 ${a.targetTable} \u7684\u5F53\u524D\u79DF\u6237 diy_table.Id`);let s=pW(Gt(t,"config","Config"));if(i==="joinform")return{...s,JoinForm:{...ee(s.JoinForm),TableId:o,TableName:a.targetTable,JoinFieldName:a.joinFieldName}};let c=n.get(Ie(a.childModule));if(!c)throw new Error(`\u65E0\u6CD5\u89E3\u6790\u9690\u85CF\u5B50\u8868\u6A21\u5757 ${a.childModule} \u7684\u5F53\u524D\u79DF\u6237 sys_menu.Id`);return{...s,TableChildTableId:o,TableChildSysMenuId:c,TableChildSysMenuName:a.childModule,TableChildFkFieldName:a.childForeignKey,TableChild:{...ee(s.TableChild),PrimaryTableFieldName:a.primaryTableFieldName}}}function Sx(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 hW(t,e){let r=_(e,"openType","OpenType"),n=_(e,"microServiceKey","MicroServiceKey"),i=_(e,"microServiceRoutePath","MicroServiceRoutePath"),a=_(e,"microServiceId","MicroServiceId"),o=_(e,"microServicePageId","MicroServicePageId");if(!(r.toLowerCase()==="microservice"||!!(ie(e,"isMicroiService","IsMicroiService")===1||n||i||a||o)))return;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=Sx(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=ee(l.Data),p=ee(u.Service),d=_(p,"Id","id"),h=_(p,"MsKey","MicroServiceKey","AppKey");if(!d||h.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(a&&a!==d)throw new Error(`MicroServiceId \u5DF2\u8FC7\u671F\uFF1AManifest=${a}\uFF0C\u5F53\u524D\u79DF\u6237=${d}`);let g=(Array.isArray(u.Pages)?u.Pages.map(ee):[]).find(x=>{let b=_(x,"RoutePath","routePath","Path","path");if(!b)return!1;try{return Sx(b)===c}catch{return!1}}),y=g?_(g,"Id","id"):"";if(!y)throw new Error(`\u5FAE\u670D\u52A1 ${n} \u4E0D\u5B58\u5728\u53EF\u7528\u9875\u9762 ${c}`);if(o&&o!==y)throw new Error(`MicroServicePageId \u5DF2\u8FC7\u671F\uFF1AManifest=${o}\uFF0C\u5F53\u524D\u79DF\u6237=${y}`);let v=c==="/"?"":`/${c.slice(1).split("/").map(x=>encodeURIComponent(x)).join("/")}`;return{IsMicroiService:1,OpenType:"MicroService",ComponentName:_(e,"componentName","ComponentName")||"MicroService",ComponentPath:_(e,"componentPath","ComponentPath")||"/micro-app/host",Url:_(e,"url","Url")||`/micro-app/${encodeURIComponent(n)}${v}`,MicroServiceId:d,MicroServicePageId:y,MicroServiceRoutePath:c,MicroServiceKey:n}}function iR(t){return Dr({...t,Id:_(t,"Id","roleId","RoleId")||void 0,Name:_(t,"Name","name"),Level:ie(t,"Level","level"),Sort:ie(t,"Sort","sort"),Remark:_(t,"Remark","remark","description"),DeptIds:_(t,"DeptIds","deptIds"),BaseLimit:_(t,"BaseLimit","baseLimit")})}function aR(t){return Dr({...t,Id:_(t,"Id","dataSourceId","DataSourceId")||void 0,DataSourceName:_(t,"DataSourceName","dataSourceName","name","Name"),DataSourceKey:_(t,"DataSourceKey","dataSourceKey"),DataSourceType:_(t,"DataSourceType","dataSourceType")||"V8",SqlDataSource:_(t,"SqlDataSource","sqlDataSource","sql"),V8DataSource:_(t,"V8DataSource","v8DataSource","code"),JsonDataSource:zc(t.JsonDataSource??t.jsonDataSource??t.json),TestParam:zc(t.TestParam??t.testParam),DataSourceRole:_(t,"DataSourceRole","dataSourceRole"),AllowAnonymous:ie(t,"AllowAnonymous","allowAnonymous"),IsEnable:ie(t,"IsEnable","isEnable")??1})}function oR(t){let e=ca(t.PageObj??t.pageObj);if(!e.ok||!e.json)throw new Error(`printTemplates.${_(t,"Title","title")||"(untitled)"} PageObj invalid: ${e.errors.join("; ")}`);let r=la(t.PrintObj??t.printObj);if(!r.ok||!r.json)throw new Error(`printTemplates.${_(t,"Title","title")||"(untitled)"} PrintObj invalid: ${r.errors.join("; ")}`);return Dr({...t,Id:_(t,"Id","printId","PrintId")||void 0,Title:_(t,"Title","title"),Number:_(t,"Number","number"),Desc:_(t,"Desc","desc","description"),DataApi:_(t,"DataApi","dataApi"),PageObj:e.json,PrintObj:r.json})}function sR(t){return Dr({...t,Id:_(t,"Id","jobId","JobId")||void 0,JobName:_(t,"JobName","jobName","name","Name"),CronExpression:_(t,"CronExpression","cronExpression","cron"),JobType:_(t,"JobType","jobType")||"1",ApiEngineKey:_(t,"ApiEngineKey","apiEngineKey"),JobParam:zc(t.JobParam??t.jobParam??t.params),JobDesc:_(t,"JobDesc","jobDesc","description"),CronDesc:_(t,"CronDesc","cronDesc"),DllName:_(t,"DllName","dllName"),JobPath:_(t,"JobPath","jobPath")})}function bR(t){let e=Ie(_(t,"component","Component"));return e==="joinform"||e==="tablechild"}function cR(t,e,r,n,i){let a=ee(e.configSource??e.ConfigSource),o=_(a,"sourceType")?fR(_(a,"sourceType"),a):void 0;return Dr({TableId:r,Name:_(e,"name","Name"),Label:_(e,"label","Label"),Type:_(e,"type","Type")||(bR(e)?"mediumtext":""),Component:_(e,"component","Component"),Visible:ie(e,"visible","Visible")??1,AppVisible:ie(e,"appVisible","AppVisible")??1,Tab:_(e,"tab","Tab")||n.fieldTabs.get(_(e,"name","Name")),TableWidth:ie(e,"tableWidth","TableWidth")??yd(e),Sort:ie(e,"sort","Sort"),Readonly:ie(e,"readonly","Readonly"),NotEmpty:ie(e,"notEmpty","NotEmpty"),Unique:ie(e,"unique","Unique"),DefaultValue:_(e,"defaultValue","DefaultValue"),Placeholder:_(e,"placeholder","Placeholder"),FormWidth:ie(e,"formWidth","FormWidth"),Data:o?.data??_(e,"data","Data"),Config:i!==void 0?JSON.stringify(i):o?JSON.stringify(o.config):zc(e.config??e.Config),Description:_(e,"description","Description"),Encrypt:ie(e,"encrypt","Encrypt"),InTableEdit:ie(e,"inTableEdit","InTableEdit")})}function gW(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",v8Unlimited:!1,tabs:[{Id:"basic",Name:"Basic Info",Sort:10},{Id:"business",Name:"Business Info",Sort:20}],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_osclient_orderno",columns:["OsClient","OrderNo"],unique:!0,purpose:"Tenant-scoped order number invariant"},{name:"idx_biz_order_osclient_status_createtime",columns:["OsClient","Status","CreateTime"],unique:!1,purpose:"Status list ordered by creation time"}]}],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(`
|
|
132
132
|
`)}],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:80,PositionTop:160,LineValueV8:""},{Id:"manager",NodeName:"\u90E8\u95E8\u7ECF\u7406\u5BA1\u6279",NodeType:"Approve",Roles:"Manager",AllowSelectUsers:1,PositionLeft:320,PositionTop:160},{Id:"end",NodeName:"\u7ED3\u675F",NodeType:"End",PositionLeft:560,PositionTop:160}],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:[]},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:"idx_biz_orderitem_osclient_orderid",columns:["OsClient","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.",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:"Physical database indexes. Declare ordered columns and unique. Required indexes must be created by microi_create_table_index or manifest generation, never by ad-hoc SQL. Tenant tables should usually lead with OsClient.",v8Unlimited:"Default false. Set true only when this table's backend V8 events must keep one database transaction and the user explicitly accepts unbounded Jint per-execution budgets. Process resident-memory protection remains active."},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:{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. 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.",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.","JoinForm is only for 1:1/N:1 and must target a different table through a real parent Id field. Use TableChild for every 1:N collection; declare its child table, child foreign key, hidden child module and (OsClient, foreignKey) index. The generator rejects raw or unresolved relation Config.","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.","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 vR(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(gW(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:f.unknown().optional(),formBtns:f.unknown().optional(),batchSelectMoreBtns:f.unknown().optional(),pageTabs:f.unknown().optional(),exportMoreBtns:f.unknown().optional(),pageBtns:f.unknown().optional()},async s=>{let c=Oo(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:f.enum(["Data","KeyValue","Sql","ApiEngine","DataSource","AutoNumber","JoinForm","DateTime"]).describe("Config source type"),options:$t.optional().describe("Source options, such as data/options, sql, apiEngineKey, dataSourceId, tableId, prefix, length")},async({sourceType:s,options:c})=>{let l=fR(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:$t.describe("System manifest with tables, engines, modules, permissions, pages, dataSources, printTemplates, workflows, jobs")},async({manifest:s})=>{let c=mx(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","Validate a wf_flowdesign + wf_node + wf_line workflow package locally before saving. Checks topology, node ids, line endpoints, start/end nodes and multi-route condition setup.",{workflow:$t.describe("Workflow package with FlowDesign, Nodes and Lines")},async({workflow:s})=>{let c=_x(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:$t.optional().describe("Optional workflow package; when provided the tool reads the selected node LineValueV8"),nodeId:f.string().optional().describe("Node Id whose LineValueV8 should be tested. If omitted, uses the start node or first node."),lineValueV8Code:f.string().optional().describe("Direct LineValueV8 JavaScript code containing MICROI_WF_LINE_CONDITION_JSON marker"),formData:$t.optional().describe("Sample business form data used for rule evaluation")},async s=>W(JSON.stringify(oW(s),null,2))),t.tool("microi_validate_system",`Validate that a generated low-code system exists on Microi server after generation. OsClient: ${n}`,{manifest:$t.describe("The same manifest used by microi_generate_system")},async({manifest:s})=>{try{let c=mx(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 e.validateLowCodeSystem(s);return gt("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:$t.describe("System manifest with tables, fields, dataSources, engines, events, modules, permissions, pages, printTemplates, workflows and jobs"),dryRun:f.boolean().optional().describe("Default true. When true, only returns an execution plan."),confirmExecution:f.string().optional().describe(`Required when dryRun=false. Must equal "${i}".`)},async({manifest:s,dryRun:c=!0,confirmExecution:l})=>{let u=mx(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
|
|
@@ -320,6 +320,7 @@ BOUNDARY RULES:
|
|
|
320
320
|
- \u7ED1\u5B9A diyTableId \u521B\u5EFA\u83DC\u5355\u65F6\uFF0C\u4E0D\u8981\u53EA\u5199 Name/DiyTableId\u3002\u5E94\u914D\u7F6E\u6216\u5141\u8BB8 MCP/\u540E\u7AEF\u81EA\u52A8\u63A8\u65AD\uFF1ATableDiyFieldIds\u3001SelectFields\u3001SearchFieldIds\u3001SortFieldIds\u3001NotShowFields\u3001StatisticsFields\u3001MobileListFields\u3001CardTitleTagFields\u3001CardBottomTagFields\u3001DefaultOrderBy\u3002
|
|
321
321
|
- NotShowFields \u9ED8\u8BA4\u9690\u85CF Id/\u5916\u952E/\u7CFB\u7EDF\u5B57\u6BB5/\u5E03\u5C40\u63A7\u4EF6/\u4E0A\u4F20\u5BCC\u6587\u672C\u5730\u56FE\u5B50\u8868\u7B49\u91CD\u5B57\u6BB5\uFF1BSearchFieldIds \u9ED8\u8BA4\u9009\u62E9\u6807\u9898\u3001\u540D\u79F0\u3001\u7F16\u53F7\u3001\u72B6\u6001\u3001\u7C7B\u578B\u3001\u5206\u7C7B\u3001\u8D1F\u8D23\u4EBA\u3001\u65F6\u95F4\u7B49\u5E38\u7528\u7B5B\u9009\uFF1BStatisticsFields \u9ED8\u8BA4\u9009\u62E9\u91D1\u989D\u3001\u4EF7\u683C\u3001\u6570\u91CF\u3001\u79EF\u5206\u3001\u4F59\u989D\u7B49\u6570\u503C\u5B57\u6BB5\uFF1BMobileListFields \u9ED8\u8BA4\u9009\u62E9 3-4 \u4E2A\u5361\u7247\u53EF\u8BFB\u5B57\u6BB5\u3002
|
|
322
322
|
- \u6BCF\u4E2A\u53EF\u89C1\u4E14\u7ED1\u5B9A\u8868\u7684 Diy \u6A21\u5757\u5FC5\u987B\u6709\uFF1A\u7D27\u51D1 Hero \u6807\u9898\u3001\u4E1A\u52A1\u526F\u6807\u9898\u30012-4 \u4E2A\u771F\u5B9E\u52A8\u6001\u6307\u6807\u3001\u5408\u7406\u5217\u5BBD\u3001\u81F3\u5C11\u4E00\u4E2A\u6709\u5408\u7406 MinWidth \u7684 PC \u590D\u5408\u5217\uFF0C\u4EE5\u53CA\u4E0D\u91CD\u590D\u5B57\u6BB5\u7684\u79FB\u52A8\u7AEF\u6807\u9898/\u526F\u6807\u9898/\u9876\u90E8\u6807\u7B7E/\u72B6\u6001/\u53F3\u4FA7\u91D1\u989D/\u6B63\u6587/Meta/\u5E95\u90E8\u533A\u57DF\u3002\u7528\u6237\u672A\u914D\u7F6E ViewSchema \u65F6\uFF0Cmicroi_generate_system\u3001microi_create_module \u548C\u540E\u7AEF CreateModule \u4F1A\u6309\u771F\u5B9E diy_field \u5143\u6570\u636E\u8865\u9F50 List/Card \u6700\u4F4E\u9ED8\u8BA4\u503C\u3002
|
|
323
|
+
- PC \u590D\u5408\u5217\u4E00\u822C\u6700\u591A\u663E\u793A\u4E24\u884C\uFF0C\u5373\u4E00\u4E2A\u4E3B\u5B57\u6BB5\u52A0\u4E00\u4E2A Lines \u6B21\u8981\u5B57\u6BB5\u3002\u53EF\u4EE5\u6309\u4E1A\u52A1\u62C6\u6210\u591A\u4E2A\u5404\u81EA\u4E24\u884C\u7684\u590D\u5408\u5217\uFF1B\u4E0D\u8981\u628A\u4E24\u4E2A Lines \u5806\u5728\u540C\u4E00\u5217\u5F62\u6210\u4E09\u884C\u9AD8\u8868\u683C\u3002\u53EA\u6709\u786E\u6709\u5C42\u7EA7\u4EF7\u503C\u5E76\u5B8C\u6210\u684C\u9762\u89C6\u89C9\u9A8C\u6536\u7684\u7279\u6B8A\u573A\u666F\u624D\u5141\u8BB8\u4E09\u884C\u3002
|
|
323
324
|
- \u81EA\u52A8\u9ED8\u8BA4\u503C\u4E0D\u662F AI \u7701\u7565\u8BBE\u8BA1\u7684\u7406\u7531\u3002\u5E94\u6309\u5F53\u524D\u8868\u548C\u72B6\u6001\u6D41\u628A\u6307\u6807\u6539\u4E3A\u5F85\u5904\u7406\u3001\u903E\u671F\u3001\u91D1\u989D\u3001\u5BB9\u91CF\u3001\u98CE\u9669\u7B49\u6709\u4E1A\u52A1\u542B\u4E49\u7684\u771F\u5B9E\u805A\u5408\uFF1BDataCount/PageCount \u53EA\u662F\u65E0\u53EF\u63A8\u65AD\u6307\u6807\u65F6\u7684\u771F\u5B9E\u515C\u5E95\u3002\u7981\u6B62\u968F\u673A\u6570\u3001\u4F2A\u7EDF\u8BA1\u548C\u65E0\u6765\u6E90\u6570\u5B57\u3002
|
|
324
325
|
- \u590D\u5408\u5217 Lines/TrailingFields \u4F7F\u7528\u7684\u5B57\u6BB5\u4E0D\u518D\u4F5C\u4E3A\u666E\u901A\u5217\u91CD\u590D\u5C55\u793A\uFF1B\u590D\u5408\u5217\u5FC5\u987B\u7ED9\u8DB3 MinWidth\u3002\u6BCF\u4E2A diy_field \u672A\u663E\u5F0F\u8BBE\u7F6E TableWidth \u65F6\u6309\u6807\u9898/\u5730\u5740\u3001\u65E5\u671F/\u7F16\u7801\u3001\u6570\u503C\u3001\u72B6\u6001\u7B49\u8BED\u4E49\u81EA\u52A8\u63A8\u65AD\u3002
|
|
325
326
|
- MenuBadge \u53EA\u6311\u5C11\u91CF\u6709\u884C\u52A8\u610F\u4E49\u7684\u91CD\u8981\u83DC\u5355\uFF1BPageTabs\u3001MoreBtns\u3001PageBtns\u3001FormBtns\u3001BatchSelectMoreBtns\u3001ExportMoreBtns \u5728\u6570\u91CF\u6709\u52A9\u4E8E\u51B3\u7B56\u65F6\u914D\u7F6E\u89D2\u6807\u3002\u76F8\u540C\u9875\u9762\u7684\u7EDF\u8BA1\u5FC5\u987B\u6279\u91CF\u8FD4\u56DE\uFF0C\u7981\u6B62\u9010\u884C\u6216\u9010\u6307\u6807 N+1\u3002
|
|
@@ -567,7 +568,7 @@ if (V8.ThisValue && typeof V8.ThisValue === 'object') {
|
|
|
567
568
|
V8.Form.${x} = '';
|
|
568
569
|
}`,A={DataSource:"Sql",Sql:$,SelectLabel:k,SelectSaveField:k,DataSourceSqlRemote:!0,EnableSearch:!0,V8Code:P},U=await t.addField({TableId:o,Name:b,Label:c,Type:"varchar(200)",Component:"Select",Visible:1,AppVisible:1,Tab:h,Sort:w,TableWidth:y??120,NotEmpty:g??0,Placeholder:v||`\u8BF7\u9009\u62E9${c}`,Config:JSON.stringify(A)});return U.Code!==1?{content:[{type:"text",text:`Created ${x} but failed ${b}: ${U.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 Join field pair created: ${x} (hidden) + ${b} (Select from ${l}.${k}, V8Code copies ${S} to ${x}).`}]}}catch(x){return{content:[{type:"text",text:`Error: ${x instanceof Error?x.message:String(x)}`}],isError:!0}}}),i.tool("microi_fix_join_field",`Retrofit an existing FK-only field to the proper Id+Name pair design for OsClient "${r}". For a table that has only "{baseName}Id" but no "{baseName}Name", this tool delegates to the helper API engine "_mcp_fix_join_field" to: (1) flip {baseName}Id field to hidden; (2) create {baseName}Name varchar(200) Select with SQL DataSource and FieldValueChange V8Code (does ALTER TABLE + diy_field insert); (3) backfill {baseName}Name from join table for existing rows. Use this to fix tables produced before microi_add_join_field was available. \u26A0\uFE0F Requires the helper engine "_mcp_fix_join_field" to exist on the server (auto-installed by the MCP team).`,{tableName:f.string().describe('Physical table name to fix, e.g. "mall_product"'),baseName:f.string().describe('Base name of the FK, e.g. "Category" \u2014 looks for {baseName}Id and creates {baseName}Name'),label:f.string().describe('Chinese label for the visible Name field, e.g. "\u5206\u7C7B"'),joinTableName:f.string().describe('Related table to query, e.g. "mall_category"'),joinIdField:f.string().optional().describe('Default: "Id"'),joinNameField:f.string().optional().describe('Default: "Name"'),joinWhere:f.string().optional().describe("Extra WHERE clause for the lookup"),tab:f.string().optional(),sort:f.number().optional(),backfill:f.boolean().optional().describe("Backfill existing rows. Default: true."),confirmExecution:f.string().optional().describe('Pass "EXECUTE" to apply changes; otherwise dry-run.')},async({tableName:o,baseName:s,label:c,joinTableName:l,joinIdField:u,joinNameField:p,joinWhere:d,tab:h,sort:m,backfill:g,confirmExecution:y})=>{try{let v=y!=="EXECUTE",x=await t.executeEngine("_mcp_fix_join_field",{tableName:o,baseName:s,label:c,joinTableName:l,joinIdField:u||"Id",joinNameField:p||"Name",joinWhere:d||"",tab:h||"",sort:m??100,backfill:g!==!1,dryRun:v});if(!x||x.Code!==1)return{content:[{type:"text",text:`Error: ${x?.Msg||"helper engine _mcp_fix_join_field call failed"}`}],isError:!0};let b=x.Data||x,S=typeof b=="string"?b:JSON.stringify(b,null,2);return{content:[{type:"text",text:(v?`[DRY-RUN]
|
|
569
570
|
`:"\u2705 ")+S}]}}catch(v){return{content:[{type:"text",text:`Error: ${v instanceof Error?v.message:String(v)}`}],isError:!0}}}),i.tool("microi_get_field_list",`List diy_field rows for a table on OsClient "${r}". Use before changing existing field Data/Config so the update targets the real FieldId and can be verified after writing.`,{tableName:f.string().optional().describe("TableName, e.g. mall_product"),tableId:f.string().optional().describe("TableId alternative locator")},async({tableName:o,tableId:s})=>{try{if(!o&&!s)return{content:[{type:"text",text:"Error: tableName or tableId is required."}],isError:!0};let c=await t.getFieldList(o,s);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_update_field",`Update a single diy_field for OsClient "${r}". Calls FormEngine.UptDiyField on the backend, which automatically clears the diy_table_field_list Redis cache so the frontend immediately sees the change. Locate the field by either Id or (TableId/TableName + Name). Only fields included in the patch are updated.`,{id:f.string().optional().describe("FieldId (preferred). If absent, must provide TableId/TableName + Name."),tableId:f.string().optional().describe("TableId (alternative locator). Use with name."),tableName:f.string().optional().describe("TableName (alternative locator). Use with name."),name:f.string().optional().describe("Field Name (FK locator with TableId/TableName)."),label:f.string().optional(),type:f.string().optional(),component:f.string().optional(),visible:f.number().optional(),appVisible:f.number().optional(),readonly:f.number().optional(),notEmpty:f.number().optional(),unique:f.number().optional(),sort:f.number().optional(),formWidth:f.number().nullable().optional(),tableWidth:f.number().optional(),placeholder:f.string().optional(),defaultValue:f.string().optional(),tab:f.string().optional(),data:f.string().optional(),config:f.string().optional(),description:f.string().optional(),inTableEdit:f.number().optional(),v8Code:f.string().optional().describe("Field value-change V8 JavaScript code."),keyupV8Code:f.string().optional().describe("Field keyup V8 JavaScript code."),v8TmpEngineTable:f.string().optional().describe("Table-cell template V8 JavaScript code."),v8TmpEngineForm:f.string().optional().describe("Form template V8 JavaScript code.")},async o=>{try{let s={},c={id:"Id",tableId:"TableId",tableName:"TableName",name:"Name",label:"Label",type:"Type",component:"Component",visible:"Visible",appVisible:"AppVisible",readonly:"Readonly",notEmpty:"NotEmpty",unique:"Unique",sort:"Sort",formWidth:"FormWidth",tableWidth:"TableWidth",placeholder:"Placeholder",defaultValue:"DefaultValue",tab:"Tab",data:"Data",config:"Config",description:"Description",inTableEdit:"InTableEdit",v8Code:"V8Code",keyupV8Code:"KeyupV8Code",v8TmpEngineTable:"V8TmpEngineTable",v8TmpEngineForm:"V8TmpEngineForm"};for(let[u,p]of Object.entries(o))p!==void 0&&c[u]&&(s[c[u]]=p);let l=await t.updateField(s);if(l.Code!==1&&BR(l)&&typeof s.Id=="string"&&s.Id){let u=await t.getTableData("diy_field",{_Where:[["Id","=",s.Id]],_PageIndex:1,_PageSize:2}),p=zr(u.Data);if(u.Code!==1||p.length!==1)return{content:[{type:"text",text:`Error: legacy JValue.Val fallback could not resolve field ${s.Id}.`}],isError:!0};let d=p[0],h=String(d.TableId||"");if(s.TableId&&String(s.TableId)!==h)return{content:[{type:"text",text:"Error: legacy JValue.Val fallback rejected a mismatched TableId."}],isError:!0};let m={...s,Id:s.Id};delete m.TableName;let g=await t.updateFormData("diy_field",m);if(g.Code!==1)return{content:[{type:"text",text:`Error: legacy JValue.Val fallback failed: ${g.Msg||""}`}],isError:!0};h&&await t.refreshSchemaCache([h]);let y=await t.getTableData("diy_field",{_Where:[["Id","=",s.Id]],_PageIndex:1,_PageSize:2}),v=zr(y.Data);if(!(y.Code===1&&v.length===1&&Object.entries(m).every(([b,S])=>String(v[0][b]??"")===String(S??""))))return{content:[{type:"text",text:"Error: legacy JValue.Val fallback write could not be verified by readback."}],isError:!0};l={Code:1,Data:{Id:s.Id,TableId:h,LegacyJValueFallback:!0},Msg:"Legacy JValue.Val fallback applied and verified."}}return l.Code!==1?{content:[{type:"text",text:`Error: ${l.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 Field updated. ${JSON.stringify(l.Data)}`}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}),i.tool("microi_update_field_list",`Batch update multiple diy_field records for OsClient "${r}" in a single transaction. Calls FormEngine.UptDiyFieldList on the backend, which automatically clears the diy_table_field_list Redis cache. Use this for bulk operations like assigning Tab values to many fields at once, batch updating Sort/Visible/Component, or any operation that would otherwise require many microi_update_field calls.`,{tableId:f.string().describe("TableId (required). The fields must belong to this table."),fieldList:f.array(f.object({id:f.string().describe("FieldId (required)."),tab:f.string().optional().describe("Form tab group name."),sort:f.number().optional().describe("Field display order."),visible:f.number().optional().describe("Visible in PC form (1=yes, 0=no)."),appVisible:f.number().optional().describe("Visible in mobile app."),component:f.string().optional(),label:f.string().optional(),formWidth:f.number().nullable().optional(),tableWidth:f.number().optional(),notEmpty:f.number().optional(),readonly:f.number().optional(),placeholder:f.string().optional(),defaultValue:f.string().optional(),data:f.string().optional(),config:f.string().optional(),description:f.string().optional(),inTableEdit:f.number().optional(),unique:f.number().optional()})).describe("Array of field patches. Each item must include id; other fields are optional and only applied when present.")},async o=>{try{let s=(o.fieldList||[]).map(l=>{let u={};return l.id!==void 0&&(u.Id=l.id),l.tab!==void 0&&(u.Tab=l.tab),l.sort!==void 0&&(u.Sort=l.sort),l.visible!==void 0&&(u.Visible=l.visible),l.appVisible!==void 0&&(u.AppVisible=l.appVisible),l.component!==void 0&&(u.Component=l.component),l.label!==void 0&&(u.Label=l.label),l.formWidth!==void 0&&(u.FormWidth=l.formWidth),l.tableWidth!==void 0&&(u.TableWidth=l.tableWidth),l.notEmpty!==void 0&&(u.NotEmpty=l.notEmpty),l.readonly!==void 0&&(u.Readonly=l.readonly),l.placeholder!==void 0&&(u.Placeholder=l.placeholder),l.defaultValue!==void 0&&(u.DefaultValue=l.defaultValue),l.data!==void 0&&(u.Data=l.data),l.config!==void 0&&(u.Config=l.config),l.description!==void 0&&(u.Description=l.description),l.inTableEdit!==void 0&&(u.InTableEdit=l.inTableEdit),l.unique!==void 0&&(u.Unique=l.unique),u}),c=await t.updateFieldList({TableId:o.tableId,FieldList:s});return c.Code!==1?{content:[{type:"text",text:`Error: ${c.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 ${s.length} fields updated. ${JSON.stringify(c.Data)}`}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}),i.tool("microi_update_table",`Update a diy_table record for OsClient "${r}" (for example form layout, V8Unlimited, data log/comment/version switches, Description or IsTree). Only provided fields are patched. Automatically clears diy_table + diy_table_field_list Redis caches.`,{id:f.string().optional().describe("TableId (preferred locator)"),name:f.string().optional().describe("Table Name (alternative locator)"),column:f.number().optional().describe("Form columns: 1, 2 or 3"),description:f.string().optional(),isTree:f.number().optional(),tabs:f.string().optional(),formOpenType:f.string().optional(),formOpenWidth:f.string().optional(),enableDataLog:f.number().optional().describe("1 enables per-row data change logs; 0 disables."),enableDataComment:f.number().optional().describe("1 enables per-row comments; 0 disables."),enableDataVersion:f.number().optional().describe("1 enables data versions; 0 disables."),v8Unlimited:f.boolean().optional().describe("Explicit high-risk switch for this table's backend V8 events. Omit to preserve; false writes 0 and true writes 1.")},async o=>{try{let s={};o.id&&(s.Id=o.id),o.name&&(s.Name=o.name),o.column!==void 0&&(s.Column=o.column),o.description!==void 0&&(s.Description=o.description),o.isTree!==void 0&&(s.IsTree=o.isTree),o.tabs!==void 0&&(s.Tabs=o.tabs),o.formOpenType!==void 0&&(s.FormOpenType=o.formOpenType),o.formOpenWidth!==void 0&&(s.FormOpenWidth=o.formOpenWidth),o.enableDataLog!==void 0&&(s.EnableDataLog=o.enableDataLog===1?1:0),o.enableDataComment!==void 0&&(s.EnableDataComment=o.enableDataComment===1?1:0),o.enableDataVersion!==void 0&&(s.EnableDataVersion=o.enableDataVersion===1?1:0),o.v8Unlimited!==void 0&&(s.V8Unlimited=o.v8Unlimited?1:0);let c=await t.updateTable(s);return c.Code!==1?{content:[{type:"text",text:`Error: ${c.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 Table updated. ${JSON.stringify(c.Data)}`}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}),i.tool("microi_bulk_update_table_features",`Plan or apply data-log, data-comment and data-version switches to many diy_table records for OsClient "${r}". Each table is read immediately before writing, patched independently through UpdateTable, and verified by readback. Existing V8 events, Tabs and unrelated table metadata are never sent or overwritten. Re-running the same batch is safe and resumes by skipping already-matched rows.`,{tables:f.array(f.object({id:f.string().optional(),name:f.string().optional()}).refine(o=>!!(o.id||o.name),"Each table needs id or name")).min(1).max(1e3),enableDataLog:f.number().optional().describe("Desired value, default 1."),enableDataComment:f.number().optional().describe("Desired value, default 1."),enableDataVersion:f.number().optional().describe("Desired value, default 1."),dryRun:f.boolean().optional().describe("Default true. Set false for real writes."),confirmExecution:f.string().optional().describe("Required when dryRun=false; must be EXECUTE.")},async({tables:o,enableDataLog:s,enableDataComment:c,enableDataVersion:l,dryRun:u,confirmExecution:p})=>{let d={EnableDataLog:s===void 0||s===1?1:0,EnableDataComment:c===void 0||c===1?1:0,EnableDataVersion:l===void 0||l===1?1:0},h=u!==!1;if(!h&&p!=="EXECUTE")return{content:[{type:"text",text:'Error: real bulk writes require dryRun=false and confirmExecution="EXECUTE".'}],isError:!0};let m={ok:!0,dryRun:h,requested:o.length,matched:0,alreadyCorrect:0,planned:0,updated:0,verified:0,failures:[]},g=async y=>{let v=y.id?[["Id","=",y.id]]:[["Name","=",y.name]],x=await t.getTableData("diy_table",{_Where:v,_SelectFields:["Id","Name","EnableDataLog","EnableDataComment","EnableDataVersion","UpdateTime"],_PageIndex:1,_PageSize:2});if(x.Code!==1)throw new Error(x.Msg||"\u8BFB\u53D6 diy_table \u5931\u8D25");let b=zr(x.Data);if(b.length!==1)throw new Error(b.length?"\u5B9A\u4F4D\u5230\u591A\u5F20\u540C\u540D\u8868\uFF0C\u8BF7\u6539\u7528 TableId":"\u672A\u627E\u5230\u8868");return b[0]};for(let y of o)try{let v=await g(y);if(m.matched++,!Object.entries(d).some(([T,C])=>Number(v[T]??0)!==C)){m.alreadyCorrect++;continue}if(m.planned++,h)continue;let b=String(v.Id||""),S=await t.updateTable({Id:b,...d});if(S.Code!==1)throw new Error(S.Msg||"UpdateTable \u8FD4\u56DE\u5931\u8D25");m.updated++;let k=await g({id:b}),w=Object.entries(d).filter(([T,C])=>Number(k[T]??0)!==C).map(([T])=>T);if(w.length)throw new Error(`\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${w.join(", ")}`);m.verified++}catch(v){m.ok=!1,m.failures.push({id:y.id,name:y.name,error:v instanceof Error?v.message:String(v)})}return{content:[{type:"text",text:JSON.stringify(m,null,2)}],isError:!m.ok}}),i.tool("microi_bulk_apply_module_presentation",`Read, plan or apply presentation-only sys_menu changes for OsClient "${r}". The tool supports ViewSchema Hero/List/Card, statistics/mobile/card fields, menu badges and badge-only changes to existing buttons/PageTabs. It fingerprints the complete current module before writing, rejects stale snapshots, and proves routes, table binding, SQL/data permissions, API replacements and button V8/business actions remain unchanged. New PageTabs require an explicit per-plan opt-in.`,{plans:f.array(f.object({moduleId:f.string().min(1),expectedFingerprint:f.string().regex(/^[a-fA-F0-9]{64}$/u).optional(),allowCreatePageTabs:f.boolean().optional(),patch:f.object({EnableViewSchema:f.number().optional(),ViewSchemaVersion:f.string().optional(),ViewConfigVersion:f.number().int().min(0).optional(),ViewSchema:f.union([f.string(),nr]).optional(),StatisticsFields:f.string().optional(),MobileListFields:f.string().optional(),CardTitleTagFields:f.string().optional(),CardBottomTagFields:f.string().optional(),MenuBadgeEnabled:f.number().optional(),MenuBadgeApiEngineKey:f.string().optional(),MoreBtns:f.string().optional(),FormBtns:f.string().optional(),BatchSelectMoreBtns:f.string().optional(),PageTabs:f.string().optional(),ExportMoreBtns:f.string().optional(),PageBtns:f.string().optional()}).strict()})).min(1).max(50),dryRun:f.boolean().optional().describe("Default true. Dry-run returns the current full-module fingerprint and presentation projection."),confirmExecution:f.string().optional().describe("Required when dryRun=false; must be EXECUTE.")},async({plans:o,dryRun:s,confirmExecution:c})=>{let l=s!==!1;if(!l&&c!=="EXECUTE")return{content:[{type:"text",text:'Error: real module presentation writes require dryRun=false and confirmExecution="EXECUTE".'}],isError:!0};let u=new Set(["EnableViewSchema","ViewSchemaVersion","ViewConfigVersion","ViewSchema","StatisticsFields","MobileListFields","CardTitleTagFields","CardBottomTagFields","MenuBadgeEnabled","MenuBadgeApiEngineKey","MoreBtns","FormBtns","BatchSelectMoreBtns","PageTabs","ExportMoreBtns","PageBtns"]),p=["MoreBtns","FormBtns","BatchSelectMoreBtns","PageTabs","ExportMoreBtns","PageBtns"],d=T=>{let C=T;for(let $=0;$<2&&typeof C=="string";$++){let P=C.trim();if(!P||!P.startsWith("[")&&!P.startsWith("{")&&!P.startsWith('"'))break;try{C=JSON.parse(P)}catch{break}}return C},h=T=>{let C=d(T);return Array.isArray(C)?C.map(h):!C||typeof C!="object"?C??null:Object.fromEntries(Object.entries(C).filter(([$])=>!$.startsWith("_")).sort(([$],[P])=>$.localeCompare(P)).map(([$,P])=>[$,h(P)]))},m=T=>JSON.stringify(h(T)),g=(T,C=!1)=>Object.fromEntries(Object.entries(T).filter(([$])=>!$.startsWith("_")).filter(([$])=>!C||!u.has($)&&$!=="UpdateTime").sort(([$],[P])=>$.localeCompare(P)).map(([$,P])=>[$,h(P)])),y=T=>Qe.default.createHash("sha256").update(JSON.stringify(g(T)),"utf8").digest("hex"),v=T=>Object.fromEntries([...u].filter(C=>T[C]!==void 0).map(C=>[C,T[C]])),x=T=>{let C=d(T);return typeof C=="string"?C.replace(/\r\n/gu,`
|
|
570
|
-
`).trim():Array.isArray(C)?C.map(x):!C||typeof C!="object"?C??null:Object.fromEntries(Object.entries(C).filter(([$])=>!$.startsWith("_")).sort(([$],[P])=>$.localeCompare(P)).map(([$,P])=>[$,x(P)]))},b=(T,C)=>{let $=d(T);if(!Array.isArray($))return m([]);let P=$.map((A,U)=>{if(!A||typeof A!="object"||Array.isArray(A))return A;let le=Object.fromEntries(Object.entries(A).filter(([ze,He])=>!ze.startsWith("_")&&!/^Badge/iu.test(ze)&&He!==""&&He!==null&&He!==void 0).sort(([ze],[He])=>ze.localeCompare(He)).map(([ze,He])=>[ze,ze==="Sort"&&Number.isFinite(Number(He))?Number(He):x(He)]));return le.Sort===void 0&&(le.Sort=U*10),le.IsVisible===void 0&&(le.IsVisible=!0),C==="MoreBtns"&&le.ShowRow===void 0&&(le.ShowRow=!0),le});return JSON.stringify(P.map(x))},S=T=>{let C=d(T);return!Array.isArray(C)||C.length===0},k=async T=>{let C=await t.getModule(T);if(C.Code!==1||!C.Data||typeof C.Data!="object")throw new Error(C.Msg||"\u8BFB\u53D6 sys_menu \u5931\u8D25");return C.Data},w={ok:!0,dryRun:l,requested:o.length,matched:0,planned:0,updated:0,verified:0,stale:0,states:[],failures:[]};for(let T of o){let C="";try{let $=await k(T.moduleId);C=String($.Name||"");let P=y($),A=w.states.length;if(w.states.push({moduleId:T.moduleId,name:C,diyTableId:$.DiyTableId,updateTime:$.UpdateTime,fingerprint:P,presentation:v($)}),T.expectedFingerprint&&P.toLowerCase()!==T.expectedFingerprint.toLowerCase())throw w.stale++,new Error(`STALE_MODULE_FINGERPRINT\uFF1A\u5F53\u524D ${P}\uFF0C\u8BA1\u5212 ${T.expectedFingerprint}`);if(!l&&!T.expectedFingerprint)throw new Error("\u771F\u5B9E\u5199\u5165\u5FC5\u987B\u63D0\u4F9B dry-run \u8FD4\u56DE\u7684 expectedFingerprint");w.matched++;let U=Oo({ModuleId:T.moduleId,...T.patch});if(U.errors.length)throw new Error(U.errors.join("\uFF1B"));let Y=U.data,le=Object.fromEntries(p.map(Re=>[Re,b($[Re],Re)]));for(let Re of p){if(Y[Re]===void 0)continue;let fa=S($[Re]),li=S(Y[Re]);if(Re==="PageTabs"&&fa&&!li){if(!T.allowCreatePageTabs)throw new Error("\u65B0\u589E PageTabs \u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E allowCreatePageTabs=true");continue}if(b(Y[Re],Re)!==le[Re])throw new Error(`${Re} \u4EC5\u5141\u8BB8\u589E\u52A0/\u8C03\u6574 Badge* \u5C55\u793A\u5B57\u6BB5\uFF0C\u4E1A\u52A1\u52A8\u4F5C\u3001V8\u3001\u987A\u5E8F\u4E0E\u663E\u9690\u5FC5\u987B\u4FDD\u6301\u4E0D\u53D8`)}if(w.planned++,l)continue;let ze=m(g($,!0)),He=await t.updateModule({ModuleId:T.moduleId,...Y});if(He.Code!==1)throw new Error(He.Msg||"UpdateModule \u8FD4\u56DE\u5931\u8D25");w.updated++;let Dt=await k(T.moduleId);if(m(g(Dt,!0))!==ze)throw new Error("IMMUTABLE_GUARD\uFF1A\u83DC\u5355\u8DEF\u7531\u3001\u8868\u7ED1\u5B9A\u3001\u6743\u9650/SQL \u6761\u4EF6\u3001\u63A5\u53E3\u66FF\u6362\u6216\u5176\u5B83\u4E1A\u52A1\u914D\u7F6E\u53D1\u751F\u53D8\u5316");for(let Re of p)if(Y[Re]!==void 0&&!(Re==="PageTabs"&&S($[Re])&&T.allowCreatePageTabs)&&b(Dt[Re],Re)!==le[Re])throw new Error(`IMMUTABLE_GUARD\uFF1A${Re} \u7684\u4E1A\u52A1\u52A8\u4F5C\u6216 V8 \u53D1\u751F\u53D8\u5316`);w.states[A]={moduleId:T.moduleId,name:C,diyTableId:Dt.DiyTableId,updateTime:Dt.UpdateTime,fingerprint:y(Dt),previousFingerprint:P,presentation:v(Dt)},w.verified++}catch($){w.ok=!1,w.failures.push({moduleId:T.moduleId,name:C||void 0,error:$ instanceof Error?$.message:String($)})}}return{content:[{type:"text",text:JSON.stringify(w,null,2)}],isError:!w.ok&&w.matched===0}}),i.tool("microi_refresh_schema_cache",`Manually invalidate Redis caches for diy_table / diy_field / diy_table_field_list for the given tables (OsClient "${r}"). Useful after bulk DB changes or when caches go stale.`,{tables:f.array(f.string()).describe("Array of table names or TableIds. All cache key variants for each will be cleared.")},async({tables:o})=>{try{let s=await t.refreshSchemaCache(o);return s.Code!==1?{content:[{type:"text",text:`Error: ${s.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 Cache refreshed. ${JSON.stringify(s.Data)}`}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}),i.tool("microi_set_engine_anonymous",`Batch set sys_apiengine.AllowAnonymous for one or more API engines (OsClient "${r}"). Use 1 for login/register/public endpoints that need to be callable without a token; use 0 to require login. The backend also keeps the engine HTTP-callable (IsEnable=1, StopHttp=0) and refreshes the corresponding sys_apiengine dynamic route cache entries from the latest DB row.`,{apiEngineKeys:f.array(f.string()).describe("Array of ApiEngineKey strings"),allowAnonymous:f.number().optional().describe("1 = allow anonymous (default), 0 = require login")},async({apiEngineKeys:o,allowAnonymous:s})=>{try{let c=await t.setEngineAnonymous(o,s??1);return c.Code!==1?{content:[{type:"text",text:`Error: ${c.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 ${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_create_module",`Create a menu module for OsClient "${r}". Inserts a record into sys_menu table (NOT sys_module, NOT Sys_Module). Links a diy_table to the navigation sidebar. IDEMPOTENT \u2014 calling again with the same Name+ParentId returns Skipped:true with the existing ModuleId. URL collisions are auto-resolved with random suffixes (concurrency-safe). Every visible bound Diy module receives a real-data compact Hero, meaningful metrics, a sensible PC composite column and a complete mobile card when viewSchema is omitted; EnableViewSchema remains 0 because it controls Detail/Edit custom forms only. Step 4 of system design. \u26A0\uFE0F For business systems, also pass moreBtns/formBtns/pageTabs/batchSelectMoreBtns JSON to wire up business buttons in one call \u2014 see skill doc microi.skills/v8-menu-buttons.`,{name:f.string().describe('Module display name (Chinese, e.g. "\u5BA2\u6237\u7BA1\u7406", "\u8BA2\u5355\u5217\u8868")'),diyTableId:f.string().optional().describe("The TableId to bind this module to (from microi_create_table)"),parentId:f.string().optional().describe("Parent menu Id for nesting (omit for top-level)"),componentName:f.string().optional().describe('Component type. Default: "\u641C\u7D22+\u8868\u683C". Options: "\u641C\u7D22+\u8868\u683C", "\u6811+\u641C\u7D22+\u8868\u683C", "\u8BE6\u60C5", "\u62A5\u8868"'),componentPath:f.string().optional().describe('Component path. Default: "/diy/diy-table-rowlist"'),display:f.number().optional().describe("Show in PC menu (1=yes, 0=no). Default: 1"),appDisplay:f.number().optional().describe("Show in mobile menu (1=yes, 0=no). Default: 1"),hasChild:f.number().optional().describe("Whether this menu has visible child menus. A hidden TableChild carrier module MUST set 0."),openType:f.string().optional().describe('Open type. Default: "Diy" (low-code page). Options: "Diy", "Url", "Page", "MicroService"'),url:f.string().optional().describe("Menu route. MicroService menus normally use /micro-app/{MicroServiceKey}/{routePath}."),sort:f.number().optional().describe("Sort order for menu display. Default: 100. Lower numbers appear first"),icon:f.string().optional().describe('Menu icon class name (e.g. "el-icon-user", "el-icon-s-order", "fa fa-home")'),menuBadgeEnabled:f.number().optional().describe("Show a dynamic statistic badge beside this sidebar menu (1=yes, 0=no). Important menus with actionable counts should normally enable it."),menuBadgeApiEngineKey:f.string().optional().describe("ApiEngineKey for the sidebar badge. Recommended response: {Code:1,Data:{Value:number}}. Keep it tenant-scoped, inexpensive, and side-effect free."),searchFieldIds:f.string().optional().describe("SearchFieldIds JSON/object-array string. If omitted and diyTableId is bound, backend infers common searchable fields such as title/name/no/status/type/category/person/time."),tableDiyFieldIds:f.string().optional().describe('Comma-separated field Ids to show as table columns (e.g. "fieldId1,fieldId2,fieldId3"). Controls which fields appear in the list view.'),defaultOrderBy:f.string().optional().describe('Default sort expression (e.g. "CreateTime DESC", "Sort ASC")'),sqlWhere:f.string().optional().describe('Fixed SQL WHERE clause for data filtering (e.g. "Status=1", "IsDeleted=0")'),enableViewSchema:f.number().optional().describe("Enable custom Detail/Edit form views (1=yes, 0=no). List/Card presentation in ViewSchema is applied whenever configured and is not gated by this switch. Default: 0."),viewSchemaVersion:f.string().optional().describe('Optional ViewSchema protocol version stored in sys_menu.ViewSchemaVersion. Blank or omitted defaults to "1.0".'),viewConfigVersion:f.number().optional().describe("Optional monotonic configuration version stored in sys_menu.ViewConfigVersion. Omitted defaults to 1."),viewSchema:f.union([f.string(),nr]).optional().describe("Versioned cross-client view JSON object/string stored in sys_menu.ViewSchema. When omitted for a visible bound Diy module, MCP generates List/Card presentation only. Supports Detail/Edit/List/Card and PC/Mobile/All. Layout.List keeps multi-line Columns[].Lines, TrailingFields and RequiredFields; Layout.Card keeps AvatarTextField, TitleField, SubtitleFields, StatusFields, TopFields, RightFields, Fields, MetaFields and BottomFields."),moreBtns:f.string().optional().describe(`Row action buttons JSON ARRAY (string). Each item: {Id,Sort,Name,Icon,BtnStyle,IsVisible,ShowRow:true,V8CodeShow,V8Code,RunBackground,BackgroundTask,IsBackgroundTask,ApiEngineKey}. V8Code typically calls V8.ApiEngine.Run(...). Long tasks such as install/import/init should set RunBackground=true and ApiEngineKey so the frontend starts a background task. Example: '[{"Id":"01K...","Name":"\u6307\u6D3E","BtnStyle":"primary","IsVisible":true,"ShowRow":true,"V8CodeShow":"V8.Result=V8.Form.Status==\\"\u5F85\u6307\u6D3E\\";","V8Code":"V8.OpenAnyForm({TableName:\\"Diy_X\\",Id:V8.Form.Id,FormMode:\\"Edit\\",SelectFields:[\\"AssigneeId\\"],EventReplace:{Submit:async function(v8,p,cb){var r=await V8.ApiEngine.Run({ApiEngineKey:\\"x_assign\\",Id:v8.Form.Id,AssigneeId:v8.Form.AssigneeId});cb(r);V8.RefreshTable({_PageIndex:1});}}});"}]'`),formBtns:f.string().optional().describe("Form bottom buttons JSON ARRAY (string). Same item shape as moreBtns but ShowRow not required. Buttons may configure BadgeEnabled, BadgeApiEngineKey, BadgeValuePath, BadgeTone, BadgeMax, BadgeShowZero and BadgeRefreshSeconds."),batchSelectMoreBtns:f.string().optional().describe("Batch action buttons JSON ARRAY (string). Same item and optional Badge* fields as moreBtns. Use V8.TableRowSelected to access selected rows; badge APIs must batch current-page Ids instead of calling once per row."),pageTabs:f.string().optional().describe("Page top tabs JSON ARRAY (string). Each item: {Id,Sort,Name,Icon,V8Code,V8CodeShow,TargetSysMenuId}. TargetSysMenuId associates another module; clicking it replaces the current route and reloads that module. V8Code typically calls V8.SearchSet({field:value}) for tabs within the current module."),exportMoreBtns:f.string().optional().describe("Export menu extra buttons JSON ARRAY (string). Supports the same optional Badge* fields as formBtns."),pageBtns:f.string().optional().describe("Page-level top buttons JSON ARRAY (string). Supports the same optional Badge* fields; page counts normally come from Data.Buttons."),sortFieldIds:f.string().optional().describe("Comma-separated field Ids that user can sort by. JSON array string also accepted."),notShowFields:f.string().optional().describe("JSON array string of field Ids hidden from the list. If omitted and diyTableId is bound, backend hides Id-like fields, foreign keys, system fields, layout controls and heavy fields such as upload/rich text/map/child table."),sqlJoin:f.string().optional().describe('Custom SQL JOIN clause for the list query (e.g. "LEFT JOIN Diy_Customer C ON A.CustomerId=C.Id"). Use aliases A=main table, B/C/D=joined tables.'),joinTables:f.string().optional().describe('JSON array of joined tables for select fields cross-table: [{Id,AsName:"B",Name:"Diy_Xxx",Description:"xxx",IsVisible:true}]'),selectFields:f.string().optional().describe("JSON array of selectable fields (cross-table) for the list view."),statisticsFields:f.string().optional().describe('JSON array of fields to show as table footer statistics (e.g. [{Id,Type:"Sum"}], Type=Sum|Avg|Max|Min|Count). If omitted and diyTableId is bound, backend infers amount/price/count/point/balance numeric fields.'),inTableEdit:f.number().optional().describe("Enable inline edit in list view (1=yes,0=no). Default: 0"),inTableEditFields:f.string().optional().describe("JSON array string of field Ids that allow inline edit (when inTableEdit=1)."),mobileListFields:f.string().optional().describe("JSON array of fields shown in mobile/card list. If omitted and diyTableId is bound, backend picks compact title/status/summary fields."),cardTitleTagFields:f.string().optional().describe("JSON array of fields shown as title tags on mobile/card view."),cardBottomTagFields:f.string().optional().describe("JSON array of fields shown as bottom tags on mobile/card view."),microServiceId:f.string().optional().describe("sys_microiservice.Id. Required when openType=MicroService."),microServicePageId:f.string().optional().describe("sys_microiservice_page.Id for this menu route. Required when openType=MicroService."),microServiceRoutePath:f.string().optional().describe("Internal Vue route such as /context-test. Required when openType=MicroService."),microServiceKey:f.string().optional().describe("sys_microiservice.MsKey/AppKey. Used to generate the friendly menu URL."),confirmExecution:f.string().optional().describe("Required for real writes. Must exactly equal name, or EXECUTE. Omit for a dry-run payload.")},async({name:o,diyTableId:s,parentId:c,componentName:l,componentPath:u,display:p,appDisplay:d,hasChild:h,openType:m,url:g,sort:y,icon:v,menuBadgeEnabled:x,menuBadgeApiEngineKey:b,searchFieldIds:S,tableDiyFieldIds:k,defaultOrderBy:w,sqlWhere:T,enableViewSchema:C,viewSchemaVersion:$,viewConfigVersion:P,viewSchema:A,moreBtns:U,formBtns:Y,batchSelectMoreBtns:le,pageTabs:ze,exportMoreBtns:He,pageBtns:Dt,sortFieldIds:Re,notShowFields:fa,sqlJoin:li,joinTables:KR,selectFields:WR,statisticsFields:GR,inTableEdit:XR,inTableEditFields:YR,mobileListFields:QR,cardTitleTagFields:e2,cardBottomTagFields:t2,microServiceId:Uc,microServicePageId:Zc,microServiceRoutePath:Fo,microServiceKey:jo,confirmExecution:jx})=>{try{let Pn=String(m||"").toLowerCase()==="microservice"||!!(Uc||Zc||Fo||jo),Jc=m,kd=l,Td=u,Cd=g,Pd=Fo;if(Pn){let ma=[Uc?"":"microServiceId",Zc?"":"microServicePageId",Fo?"":"microServiceRoutePath",jo?"":"microServiceKey"].filter(Boolean);if(ma.length)return{content:[{type:"text",text:`Error: MicroService \u83DC\u5355\u7F3A\u5C11\u5B57\u6BB5\uFF1A${ma.join(", ")}`}],isError:!0};let Vo=String(Fo||"").trim().replace(/\\/gu,"/");if(!/^\/(?:[A-Za-z0-9][A-Za-z0-9_-]*(?:\/[A-Za-z0-9][A-Za-z0-9_-]*)*)?$/u.test(Vo)||Vo.includes(".."))return{content:[{type:"text",text:`Error: microServiceRoutePath \u4E0D\u5408\u6CD5\uFF1A${Fo}`}],isError:!0};Pd=Vo,Jc="MicroService",kd=l||"MicroService",Td=u||"/micro-app/host";let n2=Vo==="/"?"":"/"+Vo.slice(1).split("/").map(i2=>encodeURIComponent(i2)).join("/");Cd=g||`/micro-app/${encodeURIComponent(String(jo))}${n2}`}let Ad=A,r2=!!s&&!Pn&&String(Jc||"Diy").toLowerCase()==="diy"&&((p??1)===1||(d??1)===1);if(!Ad&&r2&&s){let ma=await t.getFieldList(void 0,s);if(ma.Code!==1)return{content:[{type:"text",text:`Error: \u65E0\u6CD5\u8BFB\u53D6\u6A21\u5757\u5B57\u6BB5\u5E76\u751F\u6210\u9ED8\u8BA4\u5C55\u793A\u914D\u7F6E\uFF1A${ma.Msg}`}],isError:!0};Ad=Tx(o,zr(ma.Data),o)}let Lo=hd(Ad);if(!Lo.ok)return{content:[{type:"text",text:`Error: ${Lo.errors.join(`
|
|
571
|
+
`).trim():Array.isArray(C)?C.map(x):!C||typeof C!="object"?C??null:Object.fromEntries(Object.entries(C).filter(([$])=>!$.startsWith("_")).sort(([$],[P])=>$.localeCompare(P)).map(([$,P])=>[$,x(P)]))},b=(T,C)=>{let $=d(T);if(!Array.isArray($))return m([]);let P=$.map((A,U)=>{if(!A||typeof A!="object"||Array.isArray(A))return A;let le=Object.fromEntries(Object.entries(A).filter(([ze,He])=>!ze.startsWith("_")&&!/^Badge/iu.test(ze)&&He!==""&&He!==null&&He!==void 0).sort(([ze],[He])=>ze.localeCompare(He)).map(([ze,He])=>[ze,ze==="Sort"&&Number.isFinite(Number(He))?Number(He):x(He)]));return le.Sort===void 0&&(le.Sort=U*10),le.IsVisible===void 0&&(le.IsVisible=!0),C==="MoreBtns"&&le.ShowRow===void 0&&(le.ShowRow=!0),le});return JSON.stringify(P.map(x))},S=T=>{let C=d(T);return!Array.isArray(C)||C.length===0},k=async T=>{let C=await t.getModule(T);if(C.Code!==1||!C.Data||typeof C.Data!="object")throw new Error(C.Msg||"\u8BFB\u53D6 sys_menu \u5931\u8D25");return C.Data},w={ok:!0,dryRun:l,requested:o.length,matched:0,planned:0,updated:0,verified:0,stale:0,states:[],failures:[]};for(let T of o){let C="";try{let $=await k(T.moduleId);C=String($.Name||"");let P=y($),A=w.states.length;if(w.states.push({moduleId:T.moduleId,name:C,diyTableId:$.DiyTableId,updateTime:$.UpdateTime,fingerprint:P,presentation:v($)}),T.expectedFingerprint&&P.toLowerCase()!==T.expectedFingerprint.toLowerCase())throw w.stale++,new Error(`STALE_MODULE_FINGERPRINT\uFF1A\u5F53\u524D ${P}\uFF0C\u8BA1\u5212 ${T.expectedFingerprint}`);if(!l&&!T.expectedFingerprint)throw new Error("\u771F\u5B9E\u5199\u5165\u5FC5\u987B\u63D0\u4F9B dry-run \u8FD4\u56DE\u7684 expectedFingerprint");w.matched++;let U=Oo({ModuleId:T.moduleId,...T.patch});if(U.errors.length)throw new Error(U.errors.join("\uFF1B"));let Y=U.data,le=Object.fromEntries(p.map(Re=>[Re,b($[Re],Re)]));for(let Re of p){if(Y[Re]===void 0)continue;let fa=S($[Re]),li=S(Y[Re]);if(Re==="PageTabs"&&fa&&!li){if(!T.allowCreatePageTabs)throw new Error("\u65B0\u589E PageTabs \u5FC5\u987B\u663E\u5F0F\u8BBE\u7F6E allowCreatePageTabs=true");continue}if(b(Y[Re],Re)!==le[Re])throw new Error(`${Re} \u4EC5\u5141\u8BB8\u589E\u52A0/\u8C03\u6574 Badge* \u5C55\u793A\u5B57\u6BB5\uFF0C\u4E1A\u52A1\u52A8\u4F5C\u3001V8\u3001\u987A\u5E8F\u4E0E\u663E\u9690\u5FC5\u987B\u4FDD\u6301\u4E0D\u53D8`)}if(w.planned++,l)continue;let ze=m(g($,!0)),He=await t.updateModule({ModuleId:T.moduleId,...Y});if(He.Code!==1)throw new Error(He.Msg||"UpdateModule \u8FD4\u56DE\u5931\u8D25");w.updated++;let Dt=await k(T.moduleId);if(m(g(Dt,!0))!==ze)throw new Error("IMMUTABLE_GUARD\uFF1A\u83DC\u5355\u8DEF\u7531\u3001\u8868\u7ED1\u5B9A\u3001\u6743\u9650/SQL \u6761\u4EF6\u3001\u63A5\u53E3\u66FF\u6362\u6216\u5176\u5B83\u4E1A\u52A1\u914D\u7F6E\u53D1\u751F\u53D8\u5316");for(let Re of p)if(Y[Re]!==void 0&&!(Re==="PageTabs"&&S($[Re])&&T.allowCreatePageTabs)&&b(Dt[Re],Re)!==le[Re])throw new Error(`IMMUTABLE_GUARD\uFF1A${Re} \u7684\u4E1A\u52A1\u52A8\u4F5C\u6216 V8 \u53D1\u751F\u53D8\u5316`);w.states[A]={moduleId:T.moduleId,name:C,diyTableId:Dt.DiyTableId,updateTime:Dt.UpdateTime,fingerprint:y(Dt),previousFingerprint:P,presentation:v(Dt)},w.verified++}catch($){w.ok=!1,w.failures.push({moduleId:T.moduleId,name:C||void 0,error:$ instanceof Error?$.message:String($)})}}return{content:[{type:"text",text:JSON.stringify(w,null,2)}],isError:!w.ok&&w.matched===0}}),i.tool("microi_refresh_schema_cache",`Manually invalidate Redis caches for diy_table / diy_field / diy_table_field_list for the given tables (OsClient "${r}"). Useful after bulk DB changes or when caches go stale.`,{tables:f.array(f.string()).describe("Array of table names or TableIds. All cache key variants for each will be cleared.")},async({tables:o})=>{try{let s=await t.refreshSchemaCache(o);return s.Code!==1?{content:[{type:"text",text:`Error: ${s.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 Cache refreshed. ${JSON.stringify(s.Data)}`}]}}catch(s){return{content:[{type:"text",text:`Error: ${s instanceof Error?s.message:String(s)}`}],isError:!0}}}),i.tool("microi_set_engine_anonymous",`Batch set sys_apiengine.AllowAnonymous for one or more API engines (OsClient "${r}"). Use 1 for login/register/public endpoints that need to be callable without a token; use 0 to require login. The backend also keeps the engine HTTP-callable (IsEnable=1, StopHttp=0) and refreshes the corresponding sys_apiengine dynamic route cache entries from the latest DB row.`,{apiEngineKeys:f.array(f.string()).describe("Array of ApiEngineKey strings"),allowAnonymous:f.number().optional().describe("1 = allow anonymous (default), 0 = require login")},async({apiEngineKeys:o,allowAnonymous:s})=>{try{let c=await t.setEngineAnonymous(o,s??1);return c.Code!==1?{content:[{type:"text",text:`Error: ${c.Msg}`}],isError:!0}:{content:[{type:"text",text:`\u2705 ${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_create_module",`Create a menu module for OsClient "${r}". Inserts a record into sys_menu table (NOT sys_module, NOT Sys_Module). Links a diy_table to the navigation sidebar. IDEMPOTENT \u2014 calling again with the same Name+ParentId returns Skipped:true with the existing ModuleId. URL collisions are auto-resolved with random suffixes (concurrency-safe). Every visible bound Diy module receives a real-data compact Hero, meaningful metrics, a sensible PC composite column (normally one primary field plus one secondary line, never three visual rows by default) and a complete mobile card when viewSchema is omitted; EnableViewSchema remains 0 because it controls Detail/Edit custom forms only. Step 4 of system design. \u26A0\uFE0F For business systems, also pass moreBtns/formBtns/pageTabs/batchSelectMoreBtns JSON to wire up business buttons in one call \u2014 see skill doc microi.skills/v8-menu-buttons.`,{name:f.string().describe('Module display name (Chinese, e.g. "\u5BA2\u6237\u7BA1\u7406", "\u8BA2\u5355\u5217\u8868")'),diyTableId:f.string().optional().describe("The TableId to bind this module to (from microi_create_table)"),parentId:f.string().optional().describe("Parent menu Id for nesting (omit for top-level)"),componentName:f.string().optional().describe('Component type. Default: "\u641C\u7D22+\u8868\u683C". Options: "\u641C\u7D22+\u8868\u683C", "\u6811+\u641C\u7D22+\u8868\u683C", "\u8BE6\u60C5", "\u62A5\u8868"'),componentPath:f.string().optional().describe('Component path. Default: "/diy/diy-table-rowlist"'),display:f.number().optional().describe("Show in PC menu (1=yes, 0=no). Default: 1"),appDisplay:f.number().optional().describe("Show in mobile menu (1=yes, 0=no). Default: 1"),hasChild:f.number().optional().describe("Whether this menu has visible child menus. A hidden TableChild carrier module MUST set 0."),openType:f.string().optional().describe('Open type. Default: "Diy" (low-code page). Options: "Diy", "Url", "Page", "MicroService"'),url:f.string().optional().describe("Menu route. MicroService menus normally use /micro-app/{MicroServiceKey}/{routePath}."),sort:f.number().optional().describe("Sort order for menu display. Default: 100. Lower numbers appear first"),icon:f.string().optional().describe('Menu icon class name (e.g. "el-icon-user", "el-icon-s-order", "fa fa-home")'),menuBadgeEnabled:f.number().optional().describe("Show a dynamic statistic badge beside this sidebar menu (1=yes, 0=no). Important menus with actionable counts should normally enable it."),menuBadgeApiEngineKey:f.string().optional().describe("ApiEngineKey for the sidebar badge. Recommended response: {Code:1,Data:{Value:number}}. Keep it tenant-scoped, inexpensive, and side-effect free."),searchFieldIds:f.string().optional().describe("SearchFieldIds JSON/object-array string. If omitted and diyTableId is bound, backend infers common searchable fields such as title/name/no/status/type/category/person/time."),tableDiyFieldIds:f.string().optional().describe('Comma-separated field Ids to show as table columns (e.g. "fieldId1,fieldId2,fieldId3"). Controls which fields appear in the list view.'),defaultOrderBy:f.string().optional().describe('Default sort expression (e.g. "CreateTime DESC", "Sort ASC")'),sqlWhere:f.string().optional().describe('Fixed SQL WHERE clause for data filtering (e.g. "Status=1", "IsDeleted=0")'),enableViewSchema:f.number().optional().describe("Enable custom Detail/Edit form views (1=yes, 0=no). List/Card presentation in ViewSchema is applied whenever configured and is not gated by this switch. Default: 0."),viewSchemaVersion:f.string().optional().describe('Optional ViewSchema protocol version stored in sys_menu.ViewSchemaVersion. Blank or omitted defaults to "1.0".'),viewConfigVersion:f.number().optional().describe("Optional monotonic configuration version stored in sys_menu.ViewConfigVersion. Omitted defaults to 1."),viewSchema:f.union([f.string(),nr]).optional().describe("Versioned cross-client view JSON object/string stored in sys_menu.ViewSchema. When omitted for a visible bound Diy module, MCP generates List/Card presentation only. Supports Detail/Edit/List/Card and PC/Mobile/All. Layout.List keeps multi-line Columns[].Lines, TrailingFields and RequiredFields; Layout.Card keeps AvatarTextField, TitleField, SubtitleFields, StatusFields, TopFields, RightFields, Fields, MetaFields and BottomFields."),moreBtns:f.string().optional().describe(`Row action buttons JSON ARRAY (string). Each item: {Id,Sort,Name,Icon,BtnStyle,IsVisible,ShowRow:true,V8CodeShow,V8Code,RunBackground,BackgroundTask,IsBackgroundTask,ApiEngineKey}. V8Code typically calls V8.ApiEngine.Run(...). Long tasks such as install/import/init should set RunBackground=true and ApiEngineKey so the frontend starts a background task. Example: '[{"Id":"01K...","Name":"\u6307\u6D3E","BtnStyle":"primary","IsVisible":true,"ShowRow":true,"V8CodeShow":"V8.Result=V8.Form.Status==\\"\u5F85\u6307\u6D3E\\";","V8Code":"V8.OpenAnyForm({TableName:\\"Diy_X\\",Id:V8.Form.Id,FormMode:\\"Edit\\",SelectFields:[\\"AssigneeId\\"],EventReplace:{Submit:async function(v8,p,cb){var r=await V8.ApiEngine.Run({ApiEngineKey:\\"x_assign\\",Id:v8.Form.Id,AssigneeId:v8.Form.AssigneeId});cb(r);V8.RefreshTable({_PageIndex:1});}}});"}]'`),formBtns:f.string().optional().describe("Form bottom buttons JSON ARRAY (string). Same item shape as moreBtns but ShowRow not required. Buttons may configure BadgeEnabled, BadgeApiEngineKey, BadgeValuePath, BadgeTone, BadgeMax, BadgeShowZero and BadgeRefreshSeconds."),batchSelectMoreBtns:f.string().optional().describe("Batch action buttons JSON ARRAY (string). Same item and optional Badge* fields as moreBtns. Use V8.TableRowSelected to access selected rows; badge APIs must batch current-page Ids instead of calling once per row."),pageTabs:f.string().optional().describe("Page top tabs JSON ARRAY (string). Each item: {Id,Sort,Name,Icon,V8Code,V8CodeShow,TargetSysMenuId}. TargetSysMenuId associates another module; clicking it replaces the current route and reloads that module. V8Code typically calls V8.SearchSet({field:value}) for tabs within the current module."),exportMoreBtns:f.string().optional().describe("Export menu extra buttons JSON ARRAY (string). Supports the same optional Badge* fields as formBtns."),pageBtns:f.string().optional().describe("Page-level top buttons JSON ARRAY (string). Supports the same optional Badge* fields; page counts normally come from Data.Buttons."),sortFieldIds:f.string().optional().describe("Comma-separated field Ids that user can sort by. JSON array string also accepted."),notShowFields:f.string().optional().describe("JSON array string of field Ids hidden from the list. If omitted and diyTableId is bound, backend hides Id-like fields, foreign keys, system fields, layout controls and heavy fields such as upload/rich text/map/child table."),sqlJoin:f.string().optional().describe('Custom SQL JOIN clause for the list query (e.g. "LEFT JOIN Diy_Customer C ON A.CustomerId=C.Id"). Use aliases A=main table, B/C/D=joined tables.'),joinTables:f.string().optional().describe('JSON array of joined tables for select fields cross-table: [{Id,AsName:"B",Name:"Diy_Xxx",Description:"xxx",IsVisible:true}]'),selectFields:f.string().optional().describe("JSON array of selectable fields (cross-table) for the list view."),statisticsFields:f.string().optional().describe('JSON array of fields to show as table footer statistics (e.g. [{Id,Type:"Sum"}], Type=Sum|Avg|Max|Min|Count). If omitted and diyTableId is bound, backend infers amount/price/count/point/balance numeric fields.'),inTableEdit:f.number().optional().describe("Enable inline edit in list view (1=yes,0=no). Default: 0"),inTableEditFields:f.string().optional().describe("JSON array string of field Ids that allow inline edit (when inTableEdit=1)."),mobileListFields:f.string().optional().describe("JSON array of fields shown in mobile/card list. If omitted and diyTableId is bound, backend picks compact title/status/summary fields."),cardTitleTagFields:f.string().optional().describe("JSON array of fields shown as title tags on mobile/card view."),cardBottomTagFields:f.string().optional().describe("JSON array of fields shown as bottom tags on mobile/card view."),microServiceId:f.string().optional().describe("sys_microiservice.Id. Required when openType=MicroService."),microServicePageId:f.string().optional().describe("sys_microiservice_page.Id for this menu route. Required when openType=MicroService."),microServiceRoutePath:f.string().optional().describe("Internal Vue route such as /context-test. Required when openType=MicroService."),microServiceKey:f.string().optional().describe("sys_microiservice.MsKey/AppKey. Used to generate the friendly menu URL."),confirmExecution:f.string().optional().describe("Required for real writes. Must exactly equal name, or EXECUTE. Omit for a dry-run payload.")},async({name:o,diyTableId:s,parentId:c,componentName:l,componentPath:u,display:p,appDisplay:d,hasChild:h,openType:m,url:g,sort:y,icon:v,menuBadgeEnabled:x,menuBadgeApiEngineKey:b,searchFieldIds:S,tableDiyFieldIds:k,defaultOrderBy:w,sqlWhere:T,enableViewSchema:C,viewSchemaVersion:$,viewConfigVersion:P,viewSchema:A,moreBtns:U,formBtns:Y,batchSelectMoreBtns:le,pageTabs:ze,exportMoreBtns:He,pageBtns:Dt,sortFieldIds:Re,notShowFields:fa,sqlJoin:li,joinTables:KR,selectFields:WR,statisticsFields:GR,inTableEdit:XR,inTableEditFields:YR,mobileListFields:QR,cardTitleTagFields:e2,cardBottomTagFields:t2,microServiceId:Uc,microServicePageId:Zc,microServiceRoutePath:Fo,microServiceKey:jo,confirmExecution:jx})=>{try{let Pn=String(m||"").toLowerCase()==="microservice"||!!(Uc||Zc||Fo||jo),Jc=m,kd=l,Td=u,Cd=g,Pd=Fo;if(Pn){let ma=[Uc?"":"microServiceId",Zc?"":"microServicePageId",Fo?"":"microServiceRoutePath",jo?"":"microServiceKey"].filter(Boolean);if(ma.length)return{content:[{type:"text",text:`Error: MicroService \u83DC\u5355\u7F3A\u5C11\u5B57\u6BB5\uFF1A${ma.join(", ")}`}],isError:!0};let Vo=String(Fo||"").trim().replace(/\\/gu,"/");if(!/^\/(?:[A-Za-z0-9][A-Za-z0-9_-]*(?:\/[A-Za-z0-9][A-Za-z0-9_-]*)*)?$/u.test(Vo)||Vo.includes(".."))return{content:[{type:"text",text:`Error: microServiceRoutePath \u4E0D\u5408\u6CD5\uFF1A${Fo}`}],isError:!0};Pd=Vo,Jc="MicroService",kd=l||"MicroService",Td=u||"/micro-app/host";let n2=Vo==="/"?"":"/"+Vo.slice(1).split("/").map(i2=>encodeURIComponent(i2)).join("/");Cd=g||`/micro-app/${encodeURIComponent(String(jo))}${n2}`}let Ad=A,r2=!!s&&!Pn&&String(Jc||"Diy").toLowerCase()==="diy"&&((p??1)===1||(d??1)===1);if(!Ad&&r2&&s){let ma=await t.getFieldList(void 0,s);if(ma.Code!==1)return{content:[{type:"text",text:`Error: \u65E0\u6CD5\u8BFB\u53D6\u6A21\u5757\u5B57\u6BB5\u5E76\u751F\u6210\u9ED8\u8BA4\u5C55\u793A\u914D\u7F6E\uFF1A${ma.Msg}`}],isError:!0};Ad=Tx(o,zr(ma.Data),o)}let Lo=hd(Ad);if(!Lo.ok)return{content:[{type:"text",text:`Error: ${Lo.errors.join(`
|
|
571
572
|
`)}`}],isError:!0};if(jx!==o&&jx!=="EXECUTE")return{content:[{type:"text",text:JSON.stringify({dryRun:!0,confirmationRequired:o,module:{Name:o,ParentId:c,HasChild:h,OpenType:Jc||"Diy",ComponentName:kd,ComponentPath:Td,Url:Cd,MenuBadgeEnabled:x??0,MenuBadgeApiEngineKey:b,EnableViewSchema:C??0,ViewSchema:Lo.value?JSON.parse(Lo.value):void 0,IsMicroiService:Pn?1:0,MicroServiceId:Uc,MicroServicePageId:Zc,MicroServiceRoutePath:Pd,MicroServiceKey:jo}},null,2)}]};let Id=await t.createModule({Name:o,DiyTableId:s,ParentId:c,ComponentName:kd,ComponentPath:Td,Display:p??1,AppDisplay:d??1,HasChild:h,OpenType:Jc,Url:Cd,Sort:y,Icon:v,MenuBadgeEnabled:x??0,MenuBadgeApiEngineKey:b,SearchFieldIds:S,TableDiyFieldIds:k,DefaultOrderBy:w,SqlWhere:T,EnableViewSchema:C??0,ViewSchemaVersion:String($||"").trim()||"1.0",ViewConfigVersion:P??1,ViewSchema:Lo.value,MoreBtns:U,FormBtns:Y,BatchSelectMoreBtns:le,PageTabs:ze,ExportMoreBtns:He,PageBtns:Dt,SortFieldIds:Re,NotShowFields:fa,SqlJoin:li,JoinTables:KR,SelectFields:WR,StatisticsFields:GR,InTableEdit:XR,InTableEditFields:YR,MobileListFields:QR,CardTitleTagFields:e2,CardBottomTagFields:t2,IsMicroiService:Pn?1:void 0,MicroServiceId:Uc,MicroServicePageId:Zc,MicroServiceRoutePath:Pd,MicroServiceKey:jo});if(Id.Code!==1)return{content:[{type:"text",text:`Error: ${Id.Msg}`}],isError:!0};let Lx=Id.Data;return{content:[{type:"text",text:`\u2705 Module "${o}" created.
|
|
572
573
|
- ModuleId: ${Lx?.ModuleId}
|
|
573
574
|
- Url: ${Lx?.Url||"(auto-generated)"}
|