@microi.net/cli 5.2.1 → 5.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +1 -1
- package/scripts/microi-skills.meta.json +192 -192
- package/skills/.microi-skills-version.json +2 -2
- package/skills/app-store/SKILL.md +10 -8
- package/skills/microi-client-frontend/SKILL.md +15 -1
- package/skills/microi-form-engine/SKILL.md +87 -87
- package/skills/microi-form-layout/SKILL.md +16 -7
- package/skills/microi-system-delivery/SKILL.md +13 -13
- package/skills/microi-system-delivery/references/progressive-01-/346/240/207/345/207/206/345/267/245/344/275/234/346/265/201.md +53 -53
- package/skills/module-engine/SKILL.md +8 -8
- package/skills/module-engine/references/module-config.md +204 -204
- package/skills/v8-api-config/SKILL.md +167 -154
- package/skills/v8-cache-pattern/SKILL.md +114 -114
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 wp(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]:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",i]})??Je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:G(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}=xp(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}=vp(t.keyType._def,e);return{...r,propertyNames:i}}}return r}function IP(t,e){if(e.mapStrategy==="record")return wp(t,e);let r=G(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Je(e),n=G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Je(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function RP(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 $P(t){return t.target==="openAi"?void 0:{not:Je({...t,currentPath:[...t.currentPath,"not"]})}}function OP(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var oc={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function MP(t,e){if(e.target==="openApi3")return NP(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in oc&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((i,a)=>{let o=oc[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 NP(t,e)}var NP=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,i)=>G(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 DP(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:oc[t.innerType._def.typeName],nullable:!0}:{type:[oc[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=G(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function FP(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",tb(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ge(r,"minimum",n.value,n.message,e):ge(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ge(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ge(r,"maximum",n.value,n.message,e):ge(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ge(r,"maximum",n.value,n.message,e));break;case"multipleOf":ge(r,"multipleOf",n.value,n.message,e);break}return r}function zP(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=pB(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=G(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=uB(t,e);return o!==void 0&&(n.additionalProperties=o),n}function uB(t,e){if(t.catchall._def.typeName!=="ZodNever")return G(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 pB(t){try{return t.isOptional()}catch{return!0}}var LP=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return G(t.innerType._def,e);let r=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Je(e)},r]}:Je(e)};var jP=(t,e)=>{if(e.pipeStrategy==="input")return G(t.in._def,e);if(e.pipeStrategy==="output")return G(t.out._def,e);let r=G(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=G(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(i=>i!==void 0)}};function VP(t,e){return G(t.type._def,e)}function qP(t,e){let n={type:"array",uniqueItems:!0,items:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ge(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ge(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function BP(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:G(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function UP(t){return{not:Je(t)}}function JP(t){return Je(t)}var ZP=(t,e)=>G(t.innerType._def,e);var HP=(t,e,r)=>{switch(e){case M.ZodString:return xp(t,r);case M.ZodNumber:return FP(t,r);case M.ZodObject:return zP(t,r);case M.ZodBigInt:return wP(t,r);case M.ZodBoolean:return _P();case M.ZodDate:return rb(t,r);case M.ZodUndefined:return UP(r);case M.ZodNull:return OP(r);case M.ZodArray:return xP(t,r);case M.ZodUnion:case M.ZodDiscriminatedUnion:return MP(t,r);case M.ZodIntersection:return CP(t,r);case M.ZodTuple:return BP(t,r);case M.ZodRecord:return wp(t,r);case M.ZodLiteral:return PP(t,r);case M.ZodEnum:return TP(t);case M.ZodNativeEnum:return RP(t);case M.ZodNullable:return DP(t,r);case M.ZodOptional:return LP(t,r);case M.ZodMap:return IP(t,r);case M.ZodSet:return qP(t,r);case M.ZodLazy:return()=>t.getter()._def;case M.ZodPromise:return VP(t,r);case M.ZodNaN:case M.ZodNever:return $P(r);case M.ZodEffects:return kP(t,r);case M.ZodAny:return Je(r);case M.ZodUnknown:return JP(r);case M.ZodDefault:return EP(t,r);case M.ZodBranded:return vp(t,r);case M.ZodReadonly:return ZP(t,r);case M.ZodCatch:return SP(t,r);case M.ZodPipeline:return jP(t,r);case M.ZodFunction:case M.ZodVoid:case M.ZodSymbol:return;default:return(n=>{})(e)}};function G(t,e,r=!1){let n=e.seen.get(t);if(e.override){let s=e.override?.(t,e,n,r);if(s!==yP)return s}if(n&&!r){let s=dB(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=HP(t,t.typeName,e),o=typeof a=="function"?G(a(),e):a;if(o&&fB(t,e,o),e.postProcess){let s=e.postProcess(o,t,e);return i.jsonSchema=o,s}return i.jsonSchema=o,o}var dB=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:bp(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`),Je(e)):e.$refStrategy==="seen"?Je(e):void 0}},fB=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var ab=(t,e)=>{let r=vP(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:G(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Je(r)}),{}):void 0,i=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,a=G(t._def,i===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,i]},!1)??Je(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 mB(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ob(t,e){return hr(t)?Nm(t,{target:mB(e?.target),io:e?.pipeStrategy??"input"}):ab(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function sb(t){let r=Wn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=yp(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function cb(t,e){let r=Kn(t,e);if(!r.success)throw r.error;return r.data}var hB=6e4,_p=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(xl,r=>{this._oncancel(r)}),this.setNotificationHandler(_l,r=>{this._onprogress(r)}),this.setRequestHandler(wl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Sl,async(r,n)=>{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new B(H.InvalidParams,"Failed to retrieve task: Task not found");return{...i}}),this.setRequestHandler(kl,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 B(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 B(H.InvalidParams,`Task not found: ${a}`);if(!Gn(o.status))return await this._waitForTaskUpdate(a,n.signal),await i();if(Gn(o.status)){let s=await this._taskStore.getTaskResult(a,n.sessionId);return this._clearTaskQueue(a),{...s,_meta:{...s._meta,[$n]:{taskId:a}}}}return await i()};return await i()}),this.setRequestHandler(Tl,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 B(H.InvalidParams,`Failed to list tasks: ${i instanceof Error?i.message:String(i)}`)}}),this.setRequestHandler(Pl,async(r,n)=>{try{let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new B(H.InvalidParams,`Task not found: ${r.params.taskId}`);if(Gn(i.status))throw new B(H.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 B(H.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...a}}catch(i){throw i instanceof B?i:new B(H.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),B.fromError(H.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),is(a)||Lw(a)?this._onresponse(a):Zm(a)?this._onrequest(a,o):zw(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=B.fromError(H.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?.[$n]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:H.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=Mw(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 B(H.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:H.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),is(e))n(e);else{let o=new B(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(is(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),is(e))i(e);else{let o=B.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 B?o:new B(H.InternalError,String(o))}}return}let a;try{let o=await this.request(e,xa,n);if(o.task)a=o.task.taskId,yield{type:"taskCreated",task:o.task};else throw new B(H.InternalError,"Task creation did not return a task");for(;;){let s=await this.getTask({taskId:a},n);if(yield{type:"taskStatus",task:s},Gn(s.status)){s.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:a},r,n)}:s.status==="failed"?yield{type:"error",error:new B(H.InternalError,`Task ${a} failed`)}:s.status==="cancelled"&&(yield{type:"error",error:new B(H.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 B?o:new B(H.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||{},[$n]: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(_=>this._onerror(new Error(`Failed to send cancellation: ${_}`)));let b=x instanceof B?x:new B(H.RequestTimeout,String(x));u(b)};this._responseHandlers.set(d,x=>{if(!n?.signal?.aborted){if(x instanceof Error)return u(x);try{let b=Kn(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??hB,y=()=>m(B.fromError(H.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 _=this._responseHandlers.get(d);_?_(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},El,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},Cl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Vw,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||{},[$n]: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||{},[$n]: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||{},[$n]:r.relatedTask}}}),await this._transport.send(o,r)}setRequestHandler(e,r){let n=sb(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(i,a)=>{let o=cb(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=sb(e);this._notificationHandlers.set(n,i=>{let a=cb(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"&&Zm(i.message)){let a=i.message.id,o=this._requestResolvers.get(a);o?(o(new B(H.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 B(H.InvalidRequest,"Request cancelled"));return}let o=setTimeout(i,n);r.addEventListener("abort",()=>{clearTimeout(o),a(new B(H.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 B(H.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=ls.parse({method:"notifications/tasks/status",params:s});await this.notification(c),Gn(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 B(H.InvalidParams,`Task "${i}" not found - it may have been cleaned up`);if(Gn(s.status))throw new B(H.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=ls.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Gn(c.status)&&this._cleanupTaskProgressHandler(i)}},listTasks:i=>n.listTasks(i,r)}}};function KP(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function WP(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];KP(o)&&KP(a)?r[i]={...o,...a}:r[i]=a}return r}var MI=Ne(Hv(),1),DI=Ne(NI(),1);function oK(){let t=new MI.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,DI.default)(t),t}var id=class{constructor(e){this._ajv=e??oK()}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 ad=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},ds,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},Sa,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 FI(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 zI(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 od=class extends _p{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ps.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 id,this.setRequestHandler(Wm,n=>this._oninitialize(n)),this.setNotificationHandler(Gm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(nh,async(n,i)=>{let a=i.sessionId||i.requestInfo?.headers["mcp-session-id"]||void 0,{level:o}=n.params,s=ps.safeParse(o);return s.success&&this._loggingLevels.set(a,s.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ad(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=WP(this._capabilities,e)}setRequestHandler(e,r){let i=Wn(e)?.method;if(!i)throw new Error("Schema is missing a method literal");let a;if(hr(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=Kn(_a,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new B(H.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,d=await Promise.resolve(r(c,l));if(p.task){let m=Kn(xa,d);if(!m.success){let g=m.error instanceof Error?m.error.message:String(m.error);throw new B(H.InvalidParams,`Invalid task creation result: ${g}`)}return m.data}let h=Kn(Ml,d);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new B(H.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){zI(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&FI(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:$w.includes(r)?r:Um,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"},vl)}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},ih,r):this.request({method:"sampling/createMessage",params:e},ds,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},Sa,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},Sa,r);if(a.action==="accept"&&a.content&&i.requestedSchema)try{let s=this._jsonSchemaValidator.getValidator(i.requestedSchema)(a.content);if(!s.valid)throw new B(H.InvalidParams,`Elicitation response content does not match requested schema: ${s.errorMessage}`)}catch(o){throw o instanceof B?o:new B(H.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},ah,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 jI=Symbol.for("mcp.completable");function tx(t){return!!t&&typeof t=="object"&&jI in t}function VI(t){return t[jI]?.complete}var LI;(function(t){t.Completable="McpCompletable"})(LI||(LI={}));var sd=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 sK=/^[A-Za-z0-9._-]{1,128}$/;function cK(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"),!sK.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 lK(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 rx(t){let e=cK(t);return lK(t,e.warnings),e.isValid}var cd=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 ld=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 od(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new cd(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ai(Nl)),this.server.assertCanSetRequestHandler(ai(_a)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Nl,()=>({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=co(r.inputSchema);return i?ob(i,{strictUnions:!0,pipeStrategy:"input"}):uK})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let i=co(r.outputSchema);i&&(n.outputSchema=ob(i,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(_a,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B(H.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B(H.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 B(H.InternalError,`Tool ${e.params.name} has taskSupport '${a}' but was not registered with registerToolTask`);if(a==="required"&&!i)throw new B(H.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 B&&n.code===H.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=co(e.inputSchema)??e.inputSchema,o=await hp(a,r);if(!o.success){let s="error"in o?o.error:"Unknown error",c=gp(s);throw new B(H.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 B(H.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let i=co(e.outputSchema),a=await hp(i,r.structuredContent);if(!a.success){let o="error"in a?a.error:"Unknown error",s=gp(o);throw new B(H.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 B(H.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ai(Dl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Dl,async e=>{switch(e.params.ref.type){case"ref/prompt":return Hw(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Kw(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(H.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(H.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(H.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Dc;let a=Wn(n.argsSchema)?.[e.params.argument.name];if(!tx(a))return Dc;let o=VI(a);if(!o)return Dc;let s=await o(e.params.argument.value,e.params.context);return BI(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 Dc;throw new B(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let i=n.resourceTemplate.completeCallback(e.params.argument.name);if(!i)return Dc;let a=await i(e.params.argument.value,e.params.context);return BI(a)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ai(Al)),this.server.assertCanSetRequestHandler(ai(Il)),this.server.assertCanSetRequestHandler(ai(Rl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Al,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(Il,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Rl,async(e,r)=>{let n=new URL(e.params.uri),i=this._registeredResources[n.toString()];if(i){if(!i.enabled)throw new B(H.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 B(H.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ai($l)),this.server.assertCanSetRequestHandler(ai(Ol)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($l,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?pK(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ol,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B(H.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B(H.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let i=co(n.argsSchema),a=await hp(i,e.params.arguments);if(!a.success){let c="error"in a?a.error:"Unknown error",l=gp(c);throw new B(H.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:Gi(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=Gi(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 Zt?c._def?.innerType:c;return tx(l)})&&this.setCompletionRequestHandler(),o}_createRegisteredTool(e,r,n,i,a,o,s,c,l){rx(e);let u={title:r,description:n,inputSchema:qI(i),outputSchema:qI(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"&&rx(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=Gi(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Gi(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(nx(c))i=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!nx(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()}},ud=class{constructor(e,r){this._callbacks=r,this._uriTemplate=typeof e=="string"?new sd(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},uK={type:"object",properties:{}};function UI(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function JI(t){return"_def"in t||"_zod"in t||UI(t)}function nx(t){return typeof t!="object"||t===null||JI(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(UI)}function qI(t){if(t){if(nx(t))return Gi(t);if(!JI(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function pK(t){let e=Wn(t);return e?Object.entries(e).map(([r,n])=>{let i=mP(n),a=hP(n);return{name:r,description:i,required:!a}}):[]}function ai(t){let r=Wn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=yp(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function BI(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Dc={completion:{values:[],hasMore:!1}};var Qe=Ne(require("node:crypto"),1),vt=Ne(require("node:fs"),1),Tt=Ne(require("node:path"),1);var ix=Ne(require("node:crypto"),1),oi=Ne(require("node:fs"),1),ar=Ne(require("node:path"),1),ax=100*1024*1024,ox=Math.ceil(ax/3)*4+512,dK=new Set([".pdf",".png",".jpg",".jpeg",".gif",".bmp",".tif",".tiff",".webp"]);function ZI(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=ar.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=ar.default.extname(r).toLowerCase();if(n&&!dK.has(n))throw new Error("OCR \u4EC5\u652F\u6301 PDF\u3001PNG\u3001JPEG\u3001GIF\u3001BMP\u3001TIFF \u6216 WebP \u6587\u4EF6\u3002");return r}function fK(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>ox)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>ax)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 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");let n,i=ZI(t.fileName);if(e){let a=String(t.filePath).trim();if(!ar.default.isAbsolute(a))throw new Error("filePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let o=oi.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>ax)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=ZI(ar.default.basename(a));if(!s||!ar.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=oi.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=fK(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:ix.default.createHash("sha256").update(n).digest("hex"),auditFileName:i||"(unnamed OCR input)"}}function cx(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 lx=20*1024*1024,mK=25*1024*1024,ux=2*1024*1024,px=Math.ceil(lx/3)*4+512,hK=new Set([".txt",".html",".htm",".odt",".odp",".docx",".pptx",".xlsx",".epub",".pdf"]);function HI(t){let e=String(t||"").trim();if(!e||e.includes("\0"))throw new Error("fileName \u65E0\u6548\u3002");let r=ar.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(!hK.has(ar.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 gK(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>px)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>lx||i.toString("base64").replace(/=+$/u,"")!==n.replace(/=+$/u,""))throw new Error("fileByteBase64 \u65E0\u6548\u6216\u8D85\u8FC7 20 MB\u3002");return i}function dx(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(!ar.default.isAbsolute(a))throw new Error("filePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");let o=oi.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>lx)throw new Error("\u7FFB\u8BD1\u6587\u4EF6\u5FC5\u987B\u5927\u4E8E 0 \u5B57\u8282\u4E14\u4E0D\u8D85\u8FC7 20 MB\u3002");if(i=HI(t.fileName||ar.default.basename(a)),n=oi.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=HI(t.fileName),n=gK(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:ix.default.createHash("sha256").update(n).digest("hex"),auditFileName:i}}function fx(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>mK||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 KI(t,e){let r=String(t||"").trim(),n=ar.default.resolve(r);if(!ar.default.isAbsolute(r))throw new Error("outputFilePath \u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\u3002");if(oi.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=oi.default.lstatSync(ar.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 oi.default.writeFileSync(n,e,{flag:"wx"}),n}var dd={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 ue(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}var yK=new Set(["true","false","axis","item","none","vertical","horizontal"]);function bK(t){if(typeof t!="string")return"";let e=t.trim();return e?yK.has(e.toLowerCase())?"":e:""}function Ao(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 WI(t,e){return{...t,...ue(e)}}function fd(){return Math.floor(Math.random()*8e4+1e4)}function vK(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 F(t,e,r,n,i){let a={sort:t,label:e,type:r,value:n};return i&&(a.typeOptions=i),a}var xK=[{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 wK(){return{prop:"period",label:"\u7EDF\u8BA1\u5468\u671F",type:"select",value:"month",defaultValue:"month",remote:!1,options:xK.map(t=>({...t}))}}function ca(t){let e=Array.isArray(t)?t.map(n=>ue(n)).filter(n=>Object.keys(n).length):[];return e.some(n=>n.prop==="period"||n.prop==="_period")?e:[wK(),...e]}function YI(t){return{...t,searchData:ca(t.searchData)}}function _K(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=ue(e[n]);Object.keys(i).length&&(i.value=!0,e[n]=i)}}function hx(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 GI(t,e,r){return hx(ue(t[e]).value,r)}function pd(t,e){return ue(t[e]).value===!0}function SK(t){let e=Array.isArray(t.widgetParams)?t.widgetParams:[],r=ue(e[0]),n=ue(r.typeOptions).dataJson;if(Array.isArray(n))return n.length;let i=ue(n);return Array.isArray(i.data)?i.data.length:Array.isArray(i.bodyData)?i.bodyData.length:0}function EK(t){let e=si(t,"type"),r=Array.isArray(t.widgetParams)?t.widgetParams:[],n=SK(t);if(e==="statistic"){let i=Math.min(24,Math.max(1,GI(r,1,6))),a=Math.max(1,Math.floor(24/i)),o=Math.max(1,Math.ceil(Math.max(n,1)/a)),s=pd(r,18)||pd(r,19)?44:0;return Math.max(190,s+o*88+18)}if(e==="progress"){let i=Math.min(24,Math.max(1,GI(r,1,12))),a=Math.max(1,Math.floor(24/i)),o=Math.max(1,Math.ceil(Math.max(n,1)/a)),s=pd(r,26)||pd(r,27)?44:0;return Math.max(180,s+o*108+24)}return 0}function kK(t,e,r){let n=EK(t);if(!n)return 0;let i=ue(t.widgetOption);return hx(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 TK(t,e,r){return{number:fd(),wrapperNumber:t,span:e,offset:0,push:0,pull:0,height:r,marginTop:0,dynamicStyle:{padding:"8px",backgroundColor:""}}}function CK(t,e){return[F(0,"Data source","textarea","",{rows:3,dataJson:{data:t,searchData:ca([])}}),F(1,"Grid width","slider",6,{min:1,max:24,step:1}),F(2,"Background","color",""),F(3,"Gap","input","5px"),F(4,"Block colors","input","#2563eb,#16a34a,#f59e0b,#dc2626,#7c3aed,#0891b2"),F(5,"Padding","input","18px"),F(6,"Radius","input","8px"),F(7,"Title size","input","13px"),F(8,"Title weight","input","500"),F(9,"Title color","color",e?"#dbeafe":"#ffffff"),F(10,"Title margin","input","0 0 10px 0"),F(11,"Value size","input","22px"),F(12,"Value weight","input","700"),F(13,"Value color","color","#ffffff"),F(14,"Icon position","radio","suffix"),F(15,"Icon color","color","#ffffff"),F(16,"Icon size","input","18px"),F(17,"Background image","input",""),F(18,"Show search","switch",!0),F(19,"Date filter","switch",!0),F(20,"Precision","number",0),F(21,"Value padding","input","0"),F(22,"Value margin","input","0"),F(23,"Icon margin","input","0")]}function mx(t,e,r,n=""){let i=YI(e);return t==="pie"?[F(0,"Data source","textarea","",{rows:3,dataJson:i}),F(1,"Show search","switch",!0),F(2,"Inner radius","number",36),F(3,"Outer radius","number",92),F(4,"Unit","input",n),F(5,"Title","input",r),F(6,"Subtitle","input",""),F(7,"Show legend","switch",!0),F(8,"Legend orient","select","vertical"),F(9,"Legend position","select","left"),F(10,"Tooltip","switch",!0),F(11,"Trigger","select","item"),F(12,"Toolbox","switch",!1),F(13,"Show label","switch",!0),F(14,"Label position","select","outside"),F(15,"Border radius","number",8),F(16,"Border width","number",2),F(17,"Pad angle","number",2),F(18,"Nightingale","switch",!1),F(19,"Date filter","switch",!0),F(20,"Label format","input","{d}%")]:[F(0,"Data source","textarea","",{rows:3,dataJson:i}),F(1,"Show search","switch",!0),F(2,"Boundary gap","switch",t==="bar"),F(3,"Bar effect","select","shadow"),F(4,"Unit","input",n),F(5,"Title","input",r),F(6,"Subtitle","input",""),F(7,"Show legend","switch",!0),F(8,"Legend orient","select","horizontal"),F(9,"Legend position","select","center"),F(10,"Tooltip","switch",!0),F(11,"Trigger","select","axis"),F(12,"Toolbox","switch",!1),F(13,"Show label","switch",t==="bar"),F(14,"Label position","select","outside"),F(15,"Split line","switch",!0),F(16,"Date filter","switch",!0),F(17,"Rotate","switch",!1)]}function PK(t){return[F(0,"Data source","textarea","",{rows:3,dataJson:YI(t)}),F(1,"Show search","switch",!0),F(2,"Stripe","switch",!0),F(3,"Border","switch",!0),F(4,"Size","select","small"),F(5,"Progress width","number",16),F(6,"Merge column","input",""),F(7,"Page size","number",-1),F(8,"Summary","switch",!1),F(9,"Border color","color","var(--el-border-color-lighter)"),F(10,"Header background","color","var(--el-fill-color-light)"),F(11,"Header color","color","var(--el-table-header-text-color)"),F(12,"Text color","color","var(--el-table-text-color)"),F(13,"Date filter","switch",!0),F(14,"Pie width","number",30),F(15,"Pie background","color","#409eff50"),F(16,"Pie border","color","#409eff")]}function Co(t,e,r,n,i,a){return{type:t,label:e,category:0,show:1,icon:"",img:"",widgetOption:TK(r,n,i),widgetParams:a}}function Po(t,e,r,n,i){let a=fd();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 gx(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 QI(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 AK(t){let e=t.prompt||"",r=gx(e,t.theme),n=/dark|深色|黑色|大屏|驾驶舱/.test(`${e} ${t.style||""}`.toLowerCase()),i=QI(r),a=t.title||i.title,o=t.desc||i.subtitle;return{formConfig:{...dd,dark:n,title:a,dynamicStyle:{padding:"12px 0 0 0",backgroundColor:n?"#0f172a":"#f3f4f6",opacity:1}},wrapperList:[Po(a,24,120,c=>[Co("workbench","Workbench",c,24,90,[F(0,"Data source","textarea","",{rows:3,dataJson:{icon:"",title:a,subTitle:o}})])],n),Po("\u6838\u5FC3\u6307\u6807",24,220,c=>[Co("statistic","Statistic",c,24,190,CK(i.stats,n))],n),Po("\u8D8B\u52BF\u5206\u6790",12,340,c=>[Co("bar","Bar Chart",c,24,300,mx("bar",{xAxis:i.xAxis,series:i.barSeries,searchData:[]},"\u4E1A\u52A1\u8D8B\u52BF",""))],n),Po("\u7ED3\u6784\u5360\u6BD4",12,340,c=>[Co("pie","Pie Chart",c,24,300,mx("pie",{data:i.pieData,searchData:[]},"\u5206\u7C7B\u5360\u6BD4",""))],n),Po("\u6548\u7387\u8D70\u52BF",12,340,c=>[Co("line","Line Chart",c,24,300,mx("line",{xAxis:i.xAxis,series:i.lineSeries,searchData:[]},"\u6548\u7387\u8D70\u52BF",""))],n),Po("\u91CD\u70B9\u660E\u7EC6",12,340,c=>[Co("tabel","Table",c,24,300,PK({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 XI(t,e,r){return{options:{left:t,top:e,width:r,height:1,borderStyle:"solid"},printElementType:{title:"Line",type:"hline"}}}function IK(t,e,r,n){return{options:{left:t,top:e,width:r,height:n,borderWidth:1},printElementType:{title:"Rect",type:"rect"}}}function RK(t){return gx(t)}function $K(t){let e=RK(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}),XI(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}),IK(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}),XI(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 sa(t){let e=Ao(t);if(!e.ok)return t;let r=e.value;if(typeof r=="string"){let a=Ao(r);a.ok&&(r=a.value)}let n=ue(r);if(n.JsonObj!==void 0)return sa(n.JsonObj);if(n.jsonObj!==void 0)return sa(n.jsonObj);if(n.JsonStr!==void 0)return sa(n.JsonStr);if(n.jsonStr!==void 0)return sa(n.jsonStr);let i=ue(n.formData??n.FormData);if(Object.keys(i).length){if(i.JsonObj!==void 0)return sa(i.JsonObj);if(i.jsonObj!==void 0)return sa(i.jsonObj);if(i.formConfig!==void 0||i.wrapperList!==void 0)return i}return r}function OK(t,e,r){let n=si(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=ue(i[l]);if(!Object.keys(u).length||u.value===void 0||u.value==="")continue;let p=bK(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=ue(i[0]),s={rows:3,...ue(o.typeOptions)},c=s.dataJson;if(["statistic","pie","funnel","progress"].includes(n))if(Array.isArray(c))s.dataJson={data:c,searchData:ca([])},r.push(`${e}.widgetParams[0].typeOptions.dataJson array was wrapped as {data, searchData}.`);else{let l=ue(c);s.dataJson={...l,data:Array.isArray(l.data)?l.data:[],searchData:ca(l.searchData)}}if(["bar","line","linebar"].includes(n)){let l=ue(s.dataJson);s.dataJson={...l,xAxis:Array.isArray(l.xAxis)?l.xAxis:[],series:Array.isArray(l.series)?l.series:[],searchData:ca(l.searchData)}}if(n==="tabel")if(Array.isArray(c))s.dataJson={headerData:[],bodyData:c,total:c.length,searchData:ca([])},r.push(`${e}.widgetParams[0].typeOptions.dataJson array was wrapped as table bodyData.`);else{let l=ue(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:ca(l.searchData)}}_K(n,i),o.typeOptions=s,i[0]=o,t.widgetParams=i}function En(t){let e=sa(t),r=Ao(e);if(!r.ok)return{ok:!1,errors:[`JsonObj is not valid JSON: ${r.error}`],warnings:[]};let n=ue(r.value),i=[],a=[];Object.keys(n).length||i.push("JsonObj must be an object."),n.formConfig!==void 0&&Object.keys(ue(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=ue(c);si(u,"type")||(u.type="pannel"),si(u,"label")||(u.label="Card"),u.hidden===void 0&&(u.hidden=!1),u.icon=u.icon??"",u.img=u.img??"",u.wrapperOption=WI({number:fd(),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=ue(d);si(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=WI({number:fd(),wrapperNumber:ue(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=[F(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 OK(m,g,a),p=Math.max(p,kK(m,g,a)),m}):(u.widgetList=[],a.push(`wrapperList[${l}].widgetList was missing and was set to an empty array.`)),p>0){let d=ue(u.wrapperOption),h=p+16;hx(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:{...dd,...ue(n.formConfig),dynamicStyle:{...ue(dd.dynamicStyle),...ue(ue(n.formConfig).dynamicStyle)},watermarkStyle:{...ue(dd.watermarkStyle),...ue(ue(n.formConfig).watermarkStyle)}},wrapperList:o};return{ok:i.length===0,value:s,json:JSON.stringify(s),errors:i,warnings:a}}function NK(t){let e=Ao(t);if(!e.ok)return t;let r=e.value,n=ue(r);return n.PageObj!==void 0?r=n.PageObj:n.pageObj!==void 0&&(r=n.pageObj),r}function la(t){let e=NK(t),r=Ao(e);if(!r.ok)return{ok:!1,errors:[`PageObj is not valid JSON: ${r.error}`],warnings:[]};let n=ue(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=ue(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=ue(u);return si(ue(d.printElementType),"type")||i.push(`panels[${c}].printElements[${p}].printElementType.type is required.`),d.options=ue(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 ua(t){if(t==null||t==="")return{ok:!0,value:{},json:"{}",errors:[],warnings:[]};let e=Ao(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 si(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 eR(t){let e=QI(gx(t.prompt||"",t.theme)),r=t.title||e.title,n=AK({...t,title:r});return{title:r,number:t.number||vK(r),desc:t.desc||e.subtitle||si(ue(n.formConfig),"title")||"",jsonObj:n,jsonStr:JSON.stringify(n)}}function tR(t){let e=$K(t),r=Array.isArray(e.pageObj.panels)?e.pageObj.panels:[],n=t.title||si(ue(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 rR="/* MICROI_WF_LINE_CONDITION_JSON",MK="MICROI_WF_LINE_CONDITION_JSON */",Dt=f.record(f.unknown());function X(t,e=!1){return{content:[{type:"text",text:t}],isError:e}}function ee(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function gd(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 gd(n)}return[]}function w(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 $o(t,...e){for(let r of e){let n=t[r];if(Array.isArray(n))return n.map(i=>typeof i=="string"?i:w(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 ct(t,...e){for(let r of e)if(Object.prototype.hasOwnProperty.call(t,r))return t[r]}function $e(t){return t.trim().toLowerCase()}function gR(t,e){return`${$e(t)}::${$e(e)}`}function Fc(t){return["Id","CreateTime","UpdateTime","CreateUserId","CreateUserName","UpdateUserId","UpdateUserName","OsClient","IsDeleted"].some(e=>e.toLowerCase()===t.toLowerCase())}function yR(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 wr(t,...e){for(let r of e){let n=ct(t,r);if(n==null||n==="")continue;return(Array.isArray(n)?n:typeof n=="string"?yR(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:w(o,"field","Field","fieldName","FieldName","name","Name","id","Id","fieldId","FieldId"),asName:w(o,"asName","AsName","alias","Alias")||void 0,type:w(o,"type","Type")||void 0,displayType:w(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 DK(){return{byTableAndRef:new Map,fieldsByTable:new Map}}function bR(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(gR(i,s),e);let a=$e(i),o=t.fieldsByTable.get(a)||[];o.some(s=>s.id===e.id||$e(s.name)===$e(e.name))||(o.push(e),t.fieldsByTable.set(a,o))}}function nR(t,e,r){if(!(!e||!r))return t.byTableAndRef.get(gR(e,r))}function Oo(t,e){return t.fieldsByTable.get($e(e))||[]}function vR(t,e,r){return{id:r,name:r,label:r,tableId:t,tableName:e,tableDescription:e,component:"Text",type:"varchar(255)"}}function zr(t){return Object.fromEntries(Object.entries(t).filter(([,e])=>e!=null&&e!==""))}function xx(){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 yt(t,e){let r=[`## ${t}`,`- Code: ${e.Code}`,e.Msg?`- Message: ${e.Msg}`:"","","```json",JSON.stringify(e.Data??{},null,2),"```"].filter(Boolean);return X(r.join(`
|
|
129
|
-
`),e.Code!==1)}function zc(t){if(!(t==null||t===""))return typeof t=="string"?t:JSON.stringify(t)}function FK(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`),Er(r,"UnknownTotal","unknownTotal")===!0&&n.push("\u603B\u5DE5\u4F5C\u91CF\u672A\u77E5\u4E14\u53EF\u80FD\u957F\u65F6\u95F4\u8FD0\u884C");let c=w(e,"V8Code","v8Code"),l=[w(e,"Name","name"),w(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 zK(t){let e=ee(t),r=ee(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=w(r,"ExecutionMode","executionMode").trim().toLowerCase(),i=Er(r,"ClientChunked","clientChunked")===!0||n==="clientchunked"||n==="clientsequential",a=ie(r,"MaxItemsPerChunk","maxItemsPerChunk")??0,o=Er(r,"Resumable","resumable")===!0;return{declared:i,valid:i&&a>0&&o,maxItemsPerChunk:a,resumable:o}}var md="https://api.itdos.com",yx="iTdos";function LK(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||md).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!==md)throw new Error(`storeApiBase \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE ${md}\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=md,o=String(t.storeOsClient||yx).trim();if(o.toLowerCase()!==yx.toLowerCase())throw new Error(`storeOsClient \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE\u79DF\u6237 ${yx}\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:zr({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 jK(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=w(l,"Name","name");u||r.push(`${t}[${c}].Name \u4E0D\u80FD\u4E3A\u7A7A`);let p=FK(l),d=zK(l),h=l.RunBackground??l.runBackground??l.BackgroundTask??l.backgroundTask??l.IsBackgroundTask??l.isBackgroundTask,m=w(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&&(!w(g,"IdempotencyKey","idempotencyKey")&&!$o(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`),w(g,"BusinessTable","businessTable")&&(!w(g,"BusinessStatusField","businessStatusField")||!w(g,"BusinessTaskIdField","businessTaskIdField"))&&n.push(`${t}[${c}] \u5DF2\u5173\u8054\u4E1A\u52A1\u8868\uFF0C\u4F46\u7F3A\u5C11 BusinessStatusField/BusinessTaskIdField`));let y=w(l,"TargetSysMenuId","targetSysMenuId"),v=t==="PageTabs"&&!!y;!w(l,"V8Code","v8Code")&&!w(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=w(l,"Id","id")||xx();w(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=w(l,"V8CodeShow","v8CodeShow");return b&&!b.includes("V8.Result")&&n.push(`${t}[${c}].V8CodeShow \u5EFA\u8BAE\u663E\u5F0F\u8D4B\u503C V8.Result=true/false`),zr({...l,Id:x,Sort:ie(l,"Sort","sort")??c*10,Name:u,Icon:w(l,"Icon","icon")||void 0,BtnStyle:w(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:w(l,"V8Code","v8Code")||void 0,Url:w(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 No(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=jK(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]=w(t,c,l),delete e[l]);let s=["ViewSchema","viewSchema"].find(c=>t[c]!==void 0);if(s){let c=vd(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 Er(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 VK(t,e,r,n){let i=ct(t,"v8Limit","V8Limit"),a=ct(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(a==null||a===""))return;let o=i!=null&&i!=="",s=o?Er(t,"v8Limit","V8Limit"):Lc(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(o&&a!==void 0){let c=Er(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\u8868\u5355\u5F15\u64CE\u8BF7\u6539\u7528\u6B63\u5411\u5B57\u6BB5 v8Limit\uFF08false=\u4E0D\u9650\uFF0Ctrue=\u542F\u7528\u9650\u5236\uFF09`);return s}function qK(t,e){return{ok:e.Code===1,results:t,validation:{Code:e.Code,Msg:e.Msg??null,Data:e.Data??null}}}function Lc(t){let e=Er(t,"v8Limit","V8Limit");if(e!==void 0)return e;let r=Er(t,"v8Unlimited","V8Unlimited");return r===void 0?void 0:!r}function BK(t,e,r,n){let i=ct(t,"v8Limit","V8Limit"),a=ct(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(a==null||a===""))return;let o=i!=null&&i!=="",s=o?Er(t,"v8Limit","V8Limit"):Lc(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(o&&a!==void 0){let c=Er(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 UK=["Detail","Edit","List","Card"],JK=["PC","Mobile","All"],ZK=["ApiEngine","OpenDetail","OpenList","OpenForm","Navigate","Dial","Scan","Map","Refresh","Back","Copy"],HK=new Set(["v8code","v8codeshow","script","javascript","eval","onclick","function"]);function wx(t,e){let r=String(t??"").trim().toLowerCase();return e.find(n=>n.toLowerCase()===r)||""}function Tn(t,...e){let r=new Set(e.map(i=>i.toLowerCase()));return Object.entries(t).find(([i])=>r.has(i.toLowerCase()))?.[1]}function _x(t,e="ViewSchema"){if(Array.isArray(t)){for(let r=0;r<t.length;r+=1){let n=_x(t[r],`${e}[${r}]`);if(n)return n}return""}if(!t||typeof t!="object")return"";for(let[r,n]of Object.entries(t)){if(HK.has(r.toLowerCase()))return`${e}.${r}`;let i=_x(n,`${e}.${r}`);if(i)return i}return""}function Sx(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=wx(Tn(o,"ActionType","Type"),ZK);if(!s){n.push(`${e}[${a}].ActionType \u4E0D\u53D7\u652F\u6301`);return}s==="ApiEngine"&&!w(o,"ApiEngineKey","apiEngineKey")&&n.push(`${e}[${a}] \u4F7F\u7528 ApiEngine \u65F6\u5FC5\u987B\u914D\u7F6E ApiEngineKey`);let c=Tn(o,"SuccessActions");n.push(...Sx(c,`${e}[${a}].SuccessActions`,r+1))}),n}function vd(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=_x(n);i&&e.push(`ViewSchema \u4E0D\u5141\u8BB8\u5305\u542B\u53EF\u6267\u884C\u524D\u7AEF\u811A\u672C\u5B57\u6BB5\uFF1A${i}`);let o=Tn(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}wx(Tn(u,"Scene"),UK)||e.push(`ViewSchema.Views[${l}].Scene \u4E0D\u53D7\u652F\u6301`);let p=Tn(u,"Device");p!==void 0&&!wx(p,JK)&&e.push(`ViewSchema.Views[${l}].Device \u4E0D\u53D7\u652F\u6301`);let d=Tn(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(...Sx(Tn(h,"Actions","ActionSchema"),`ViewSchema.Views[${l}].Layout.Actions`));let m=Tn(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(...Sx(Tn(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 xR(t,e){let r=[],n=t.toLowerCase();if(n==="keyvalue"){let i=w(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()}}):gd(e.items).map(o=>({Key:w(o,"Key","key"),Value:w(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=w(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=w(e,"sql","Sql");return i||r.push("SQL \u6570\u636E\u6E90\u7F3A\u5C11 sql"),{config:{DataSource:"Sql",Sql:i,SelectLabel:w(e,"selectLabel","SelectLabel")||"Name",SelectSaveField:w(e,"selectSaveField","SelectSaveField")||"Id",DataSourceSqlRemote:e.dataSourceSqlRemote??e.DataSourceSqlRemote??!0,EnableSearch:e.enableSearch??e.EnableSearch??!0},warnings:r}}if(n==="apiengine"){let i=w(e,"apiEngineKey","DataSourceApiEngineKey");return i||r.push("\u63A5\u53E3\u5F15\u64CE\u6570\u636E\u6E90\u7F3A\u5C11 apiEngineKey"),{config:{DataSource:"ApiEngine",DataSourceApiEngineKey:i,SelectLabel:w(e,"selectLabel")||"name",SelectSaveField:w(e,"selectSaveField")||"id"},warnings:r}}if(n==="datasource"){let i=w(e,"dataSourceId","DataSourceId");return i||r.push("\u6570\u636E\u6E90\u5F15\u64CE\u914D\u7F6E\u7F3A\u5C11 dataSourceId"),{config:{DataSource:"DataSource",DataSourceId:i,SelectLabel:w(e,"selectLabel")||"Name",SelectSaveField:w(e,"selectSaveField")||"Id"},warnings:r}}if(n==="autonumber")return{config:{AutoNumberFixed:w(e,"prefix","AutoNumberFixed"),AutoNumberLength:ie(e,"length","AutoNumberLength")??4},warnings:r};if(n==="datetime")return{config:{DateTimeType:w(e,"dateTimeType","DateTimeType")||"datetime"},warnings:r};if(n==="joinform"){let i=w(e,"tableId"),a=w(e,"tableName"),o=w(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:zr({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 bx(t,e){let r=kr(t);return zr({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||(yd.has(r)||Sr(t)||r==="numbertext"?"In":"Out"),DisplaySelect:e?.displaySelect??["opentable","joinform","department","selecttree"].includes(r),Equal:e?.equal??(yd.has(r)||r==="numbertext"?!0:void 0),IsVisible:!0})}function Io(t,e,r,n,i){return n.map(a=>{let o=nR(t,e,a.ref)||nR(t,r,a.ref)||(Fc(a.ref)?vR(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=ct(t,r);if(!(n==null||n===""))return typeof n=="string"?n:JSON.stringify(n)}return""}var KK=new Set(["id","osclient","isdeleted","createuserid","updateuserid","deleteuserid","tenantid","storeid","userid","userids","roleid","roleids","parentid","parentids","class","code","enname","endescription"]),Rx=new Set(["button","divider","collapsegroup","tabs","alert","statictext","html","devcomponent"]),WK=new Set(["textarea","richtext","codeeditor","jsontable","imgupload","fileupload","tablechild","map","maparea","jointable","opentable","treecheckbox","transfer"]),GK=new Set(["text","textarea","select","multipleselect","radio","checkbox","datetime","date","numbertext","autonumber","switch","department","address","cascader","selecttree","opentable","joinform","autocomplete","taginput"]),yd=new Set(["select","multipleselect","radio","checkbox","switch","department","selecttree","opentable","joinform","cascader"]);function Yt(t){return(t||"").trim().toLowerCase()}function st(t){return`${t.name||""} ${t.label||""} ${t.component||""} ${t.type||""}`.toLowerCase()}function me(t,e){return e.some(r=>t.includes(r.toLowerCase()))}function kr(t){return Yt(t.component||"Text")}function XK(t){return Rx.has(kr(t))}function YK(t){return WK.has(kr(t))}function QK(t){let e=t.name||"",r=Yt(e).replace(/[_\-\s]+/g,"");return!!(KK.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 jc(t){return Fc(t.name)&&!["CreateTime","UpdateTime","UserName"].some(e=>e.toLowerCase()===t.name.toLowerCase())||QK(t)||XK(t)||YK(t)?!0:kr(t).includes("hidden")}function ci(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 _r(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 xd(t){let e=Yt(t.type);return kr(t)==="numbertext"||e.startsWith("decimal")||e==="int"||e==="bigint"}function Sr(t){let e=st(t);return kr(t)==="datetime"||me(e,["time","date","\u65E5\u671F","\u65F6\u95F4"])}function eW(t){let e=kr(t),r=yd.has(e)||e==="numbertext"||e==="rate"||e==="progress";return{ref:t.name,displayType:r||Sr(t)?"In":"Out",displaySelect:["opentable","joinform","department","selecttree"].includes(e),equal:r?!0:void 0}}function iR(t){let e=st(t),r=0;return me(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),me(e,["status","state","type","category","level","class","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])&&(r+=45),me(e,["customer","member","user","owner","\u8D1F\u8D23\u4EBA","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8054\u7CFB\u4EBA"])&&(r+=35),Sr(t)&&(r+=25),xd(t)&&!me(e,["phone","mobile","tel","\u7535\u8BDD","\u624B\u673A"])&&(r+=15),kr(t)==="textarea"&&(r-=25),r}function Ex(t){let e=st(t),r=0;return me(e,["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])&&(r+=70),me(e,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])&&(r+=45),me(e,["customer","member","user","owner","phone","mobile","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u7535\u8BDD","\u624B\u673A"])&&(r+=35),me(e,["amount","money","price","total","count","qty","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D"])&&(r+=30),Sr(t)&&(r+=15),kr(t)==="autonumber"&&(r+=55),r}function tW(t){return ci(t.filter(jc))}function Vc(t){let e=t.filter(n=>!jc(n)),r=e.length?e:t;return ci(_r(r,Ex)).slice(0,Math.min(12,r.length))}function rW(t){let e=t.filter(n=>!jc(n)&&GK.has(kr(n))),r=_r(e,iR).filter(n=>iR(n)>0);return ci(r.length?r:e).slice(0,Math.min(8,e.length))}function nW(t){let e=t.filter(r=>!jc(r)&&(Sr(r)||xd(r)||Yt(r.name)==="sort"));return ci(_r(e,r=>{let n=st(r);return me(n,["update","\u4FEE\u6539"])?80:me(n,["create","\u521B\u5EFA"])?75:Yt(r.name)==="sort"?70:me(n,["amount","money","price","total","count","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?60:20})).slice(0,Math.min(8,e.length))}function wR(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!jc(n)&&xd(n)&&!me(i,e)&&me(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 ci(_r(r,n=>me(st(n),["amount","money","price","total","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D"])?80:40)).slice(0,6)}function iW(t){let e=Vc(t),r=_r(e,a=>me(st(a),["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])?100:0)[0],n=_r(e.filter(a=>a!==r),a=>me(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 ci([r,...n.slice(0,1),...i].filter(Boolean)).slice(0,4)}function aW(t){return _r(Vc(t),e=>me(st(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])?100:0).filter(e=>me(st(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])).slice(0,2)}function oW(t){return _r(Vc(t),e=>{let r=st(e);return me(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?90:Sr(e)?60:0}).filter(e=>{let r=st(e);return Sr(e)||me(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])}).slice(0,3)}function _R(t,e=0){let r=ee(t),n=w(r,"name","Name");return n?{id:w(r,"id","Id")||n,name:n,label:w(r,"label","Label")||n,tableId:w(r,"tableId","TableId"),tableName:w(r,"tableName","TableName"),tableDescription:w(r,"tableDescription","TableDescription"),component:w(r,"component","Component")||"Text",type:w(r,"type","Type")||"varchar(500)"}:null}function wd(t){let e=_R(t);if(!e)return 150;let r=st(e),n=kr(e);return["richtext","textarea","address","map","maparea","fileupload","imgupload"].includes(n)||me(r,["address","remark","description","content","\u5730\u5740","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247"])?240:me(r,["name","title","subject","customer","company","\u540D\u79F0","\u6807\u9898","\u4E3B\u9898","\u5BA2\u6237","\u4F01\u4E1A"])?200:Sr(e)?170:xd(e)?140:n==="autonumber"||me(r,["phone","mobile","email","code","number","\u7F16\u53F7","\u5355\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])?160:yd.has(n)||me(r,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?130:150}function kn(t,e={}){return{Name:t.name,Label:t.label||t.name,...e}}function pa(t,e,r){let n=[];for(let i of t)if(!(!i?.name||r.has(Yt(i.name)))&&(r.add(Yt(i.name)),n.push(i),n.length>=e))break;return n}function $x(t,e,r=""){let n=e.map(_R).filter(Boolean),i=Vc(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=_r(i,A=>{let D=st(A);return me(D,["title","subject","\u6807\u9898","\u4E3B\u9898"])?150:me(D,["name","\u540D\u79F0"])?130:kr(A)==="autonumber"||me(D,["no","code","number","\u7F16\u53F7","\u5355\u53F7","\u7F16\u7801"])?110:Ex(A)})[0]||i[0],l=_r(i.filter(A=>A!==c),A=>me(st(A),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])?100:0).filter(A=>me(st(A),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])),u=wR(n).filter(A=>A!==c),p=_r(n.filter(Sr),A=>me(st(A),["create","\u521B\u5EFA"])?100:50),d=_r(i.filter(A=>A!==c&&!l.includes(A)&&!u.includes(A)),A=>{let D=st(A);return me(D,["customer","member","user","owner","contact","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u8054\u7CFB\u4EBA"])?90:Sr(A)?70:Ex(A)}).slice(0,1),h=ci([...l.slice(0,1),...u.slice(0,1)]),m=ci([c,...d,...h].filter(Boolean)).map(A=>A.name),g=c?Math.min(520,Math.max(340,wd(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,D)=>({Key:`Aggregate:${A.name}`,Label:`${A.label||A.name}\u5408\u8BA1`,Source:"Field",Field:A.name,...y[D]}));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?[Yt(c.name)]:[]),b=pa(d,1,x),_=pa(l,1,x),k=pa(l,1,x),S=pa(u,1,x),T=pa(p,2,x),C=pa(i,2,x),O=pa([...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=>kn(A,{Icon:Sr(A)?"fas fa-clock":"fas fa-circle-info",Tone:"info"})),TrailingFields:h.map(A=>kn(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=>kn(A,{Icon:"fas fa-circle-info",Tone:"info"})),StatusFields:_.map(A=>kn(A,{DisplayStyle:"Tag",Icon:"fas fa-circle-check",Tone:"success"})),TopFields:k.map(A=>kn(A,{DisplayStyle:"Tag",Icon:"fas fa-tag",Tone:"primary"})),RightFields:S.map(A=>kn(A,{Icon:"fas fa-coins",Tone:"danger",FontWeight:"700"})),Fields:C.map(A=>kn(A)),MetaFields:T.map(A=>kn(A,{Icon:"fas fa-clock",Tone:"info"})),BottomFields:O.map(A=>kn(A,{Icon:Sr(A)?"fas fa-calendar":"fas fa-chart-simple",Tone:"warning"})),HideIndex:!0,ShowCreateTime:T.length===0,ShowUpdateTime:!1}}}]}}function sW(t,e,r){let n=t.length?t:[vR(e,r,"CreateTime")],i=n.find(a=>Yt(a.name)==="createtime")||n.find(a=>Yt(a.name)==="updatetime")||n.find(a=>Yt(a.name)==="sort");if(i)return JSON.stringify([{Id:i.id,Name:i.name,Type:Yt(i.name)==="sort"?"ASC":"DESC",Sort:0}])}function cW(t,e,r,n){let i=ct(t,"DefaultOrderBy");if(i!=null&&i!=="")return typeof i=="string"?i:JSON.stringify(i);let a=ct(t,"defaultOrderBy");if(a!=null&&a!==""){let s=Array.isArray(a)||typeof a=="string"&&a.trim().startsWith("[")?wr({value:a},"value"):[{ref:String(a).trim(),type:"DESC"}];return JSON.stringify(Io(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=wr(t,"orderBy","OrderBy","defaultSort","DefaultSort","sortBy","SortBy");if(o.length)return JSON.stringify(Io(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 lW(t,e,r,n){if(!r&&!n)return{};let i=Oo(e,r).length?Oo(e,r):Oo(e,n),a={},o=wr(t,"searchFields","SearchFields","searchFieldNames","SearchFieldNames"),s=o.length?Io(e,r,n,o,"module.searchFields"):rW(i).map(h=>({meta:h,ref:eW(h)}));!nt(t,"searchFieldIds","SearchFieldIds")&&s.length&&(a.SearchFieldIds=JSON.stringify(s.map(({meta:h,ref:m})=>bx(h,m))));let c=wr(t,"listFields","ListFields","tableFields","TableFields","columns","Columns"),l=c.length?Io(e,r,n,c,"module.listFields"):Vc(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})=>bx(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=wr(t,...h.refKeys),g={SortFieldIds:nW(i),NotShowFields:tW(i),MobileListFields:iW(i),CardTitleTagFields:aW(i),CardBottomTagFields:oW(i),InTableEditFields:[]};if(!m.length&&!g[h.canonical]?.length)continue;let y=m.length?Io(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})=>bx(v,x)):y.map(({meta:v})=>v.id))}let p=wr(t,"statisticsFieldNames","StatisticsFieldNames","statFields","StatFields");if(!nt(t,"statisticsFields","StatisticsFields")){let h=p.length?Io(e,r,n,p,"module.statisticsFields"):wR(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=cW(t,e,r,n)||(nt(t,"DefaultOrderBy","defaultOrderBy")?void 0:sW(i,r,n));return d&&(a.DefaultOrderBy=d),a}function aR(t,e,r){let n=gd(ee(e).Tables);for(let i of n){let a=w(i,"Id","id"),o=w(i,"Name","name");if(!a||!o)continue;r?.set(o.toLowerCase(),a);let s=ct(i,"_Fields","Fields","fields"),c=Array.isArray(s)?gd(s):[];for(let l of c){let u=w(l,"Id","id"),p=w(l,"Name","name");!u||!p||bR(t,{id:u,name:p,label:w(l,"Label","label")||p,tableId:a,tableName:o,tableDescription:w(i,"Description","description")||o,component:w(l,"Component","component")||"Text",type:w(l,"Type","type")||"varchar(255)"})}}}function kt(t){return Yt(w(t,"component","Component")||"Text")}function uW(t){return`${w(t,"name","Name")} ${w(t,"label","Label")} ${w(t,"component","Component")}`.toLowerCase()}function pW(t,e){let r=uW(t),n=kt(t);return["imgupload","fileupload","richtext","codeeditor","jsontable","tablechild","map","maparea","textarea"].includes(n)||me(r,["remark","note","content","file","image","attach","map","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247","\u5730\u56FE"])?"attachment":me(r,["phone","mobile","email","address","city","contact","\u8054\u7CFB\u4EBA","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1","\u5730\u5740","\u57CE\u5E02"])?"contact":me(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 kx(t){let e=ce(t,"fields","Fields"),r=ct(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=>!Rx.has(kt(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=w(l,"name","Name");if(!p||w(l,"tab","Tab"))return;let d=pW(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 vx(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,y=new Set(o.map(x=>w(x,"apiEngineKey","ApiEngineKey").toLowerCase()).filter(Boolean));!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 v=SW(t);return e.push(...v.errors),r.push(...v.warnings),i.forEach(x=>n.push(`save_role ${w(x,"name","Name")}`)),a.forEach((x,b)=>{let _=w(x,"name","Name");_||e.push(`tables[${b}].name \u4E0D\u80FD\u4E3A\u7A7A`),VK(x,`tables[${b}]`,e,r),n.push(`create_table ${_||`(index ${b})`}`),kx(x).tabs?.length&&r.push(`table ${_||`(index ${b})`} has many fields; generator will create diy_table.Tabs and assign empty field Tab values automatically`),_&&g.set(_.toLowerCase(),new Set),ce(x,"fields","Fields").forEach((D,Z)=>{let V=w(D,"name","Name"),te=w(D,"label","Label");V||e.push(`tables[${b}].fields[${Z}].name \u4E0D\u80FD\u4E3A\u7A7A`),te||e.push(`tables[${b}].fields[${Z}].label \u4E0D\u80FD\u4E3A\u7A7A`),_&&V&&g.get(_.toLowerCase())?.add(V.toLowerCase()),_&&te&&g.get(_.toLowerCase())?.add(te.toLowerCase()),n.push(`add_field ${_}.${V}`)});let S=_d(x);n.push(`configure_form_banner ${_||`(index ${b})`}`);let T=g.get(_.toLowerCase())||new Set,C=(D,Z)=>{D&&!T.has(D.toLowerCase())&&!Fc(D)&&e.push(`${Z} references unknown field "${D}" on table "${_}"`)};C(w(S,"FormBannerTitleField"),`tables[${b}].formBanner.titleField`),C(w(S,"FormBannerSubtitleField"),`tables[${b}].formBanner.subtitleField`),C(w(S,"FormBannerImageField"),`tables[${b}].formBanner.imageField`),C(w(S,"FormBannerBackgroundField"),`tables[${b}].formBanner.backgroundField`),bd(JSON.parse(w(S,"FormBannerTagFields")||"[]")).forEach((D,Z)=>{let V=typeof D=="string"?D:w(ee(D),"Field","field","Name","name");C(V,`tables[${b}].formBanner.tagFields[${Z}]`)}),bd(JSON.parse(w(S,"FormBannerMetrics")||"[]")).forEach((D,Z)=>{let V=ee(D),te=typeof D=="string"?D:w(V,"Field","field","Name","name");C(te,`tables[${b}].formBanner.metrics[${Z}]`);let _e=w(V,"ApiEngineKey","apiEngineKey");_e&&!y.has(_e.toLowerCase())&&r.push(`tables[${b}].formBanner.metrics[${Z}] references ApiEngineKey "${_e}" not declared in this manifest; it must already exist in the target tenant`)});let A=new Set(ce(x,"fields","Fields").map(D=>w(D,"name","Name").toLowerCase()).filter(Boolean));["id","createtime","updatetime","createuser","osclient"].forEach(D=>A.add(D)),ce(x,"indexes","Indexes").forEach((D,Z)=>{let V=$o(D,"columns","Columns");V.length||e.push(`tables[${b}].indexes[${Z}].columns \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5`);for(let te of V)A.has(te.toLowerCase())||e.push(`tables[${b}].indexes[${Z}] references unknown physical field "${te}" on table "${_}"`);V.some((te,_e)=>V.findIndex(xt=>xt.toLowerCase()===te.toLowerCase())!==_e)&&e.push(`tables[${b}].indexes[${Z}] \u5305\u542B\u91CD\u590D\u5B57\u6BB5`),n.push(`create_index ${_}.${w(D,"name","Name")||V.join("_")}`)})}),l.forEach(x=>n.push(`save_data_source ${w(x,"dataSourceKey","DataSourceKey")}`)),o.forEach((x,b)=>{let _=w(x,"apiEngineKey","ApiEngineKey");_||e.push(`engines[${b}].apiEngineKey \u4E0D\u80FD\u4E3A\u7A7A`),BK(x,`engines[${b}]`,e,r),n.push(`upsert_engine ${_}`)}),c.forEach(x=>n.push(`save_event ${w(x,"formEngineKey","FormEngineKey")}/${w(x,"eventType","EventType")}`)),s.forEach(x=>{let b=No(x);e.push(...b.errors),r.push(...b.warnings);let _=w(x,"table","tableName","diyTableName","DiyTableName"),k=w(x,"name","Name"),S=w(x,"openType","OpenType"),T=w(x,"microServiceKey","MicroServiceKey"),C=w(x,"microServiceRoutePath","MicroServiceRoutePath");if(S.toLowerCase()==="microservice"||!!(ie(x,"isMicroiService","IsMicroiService")===1||T||C||w(x,"microServiceId","MicroServiceId")||w(x,"microServicePageId","MicroServicePageId"))){if(T||e.push(`modules.${k||"(unnamed)"}.microServiceKey \u4E0D\u80FD\u4E3A\u7A7A`),C||e.push(`modules.${k||"(unnamed)"}.microServiceRoutePath \u4E0D\u80FD\u4E3A\u7A7A`),C)try{Ix(C)}catch(P){e.push(`modules.${k||"(unnamed)"}.microServiceRoutePath ${P instanceof Error?P.message:String(P)}`)}n.push(`resolve_microservice_binding ${T||"(missing)"}${C||"/(missing)"}`)}if(_&&g.has(_.toLowerCase())){let P=g.get(_.toLowerCase())||new Set,A=[["listFields",wr(x,"listFields","ListFields","tableFields","TableFields","columns","Columns")],["searchFields",wr(x,"searchFields","SearchFields","searchFieldNames","SearchFieldNames")],["sortFields",wr(x,"sortFields","SortFields")],["hiddenFields",wr(x,"hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName")],["mobileFields",wr(x,"mobileFields","MobileFields")]];for(let[D,Z]of A)for(let V of Z)!P.has(V.ref.toLowerCase())&&!Fc(V.ref)&&e.push(`modules.${k||_}.${D} references unknown field "${V.ref}" on table "${_}"`)}_&&!wr(x,"listFields","ListFields","tableFields","TableFields","columns","Columns").length&&!nt(x,"TableDiyFieldIds","SelectFields")&&r.push(`module ${k||_} has no listFields; generator will use the first business fields from ${_}`),n.push(`create_or_update_module ${w(x,"name","Name")}`)}),m.forEach(x=>n.push(`set_permission ${w(x,"roleId","RoleId")||"admin"}`)),u.forEach((x,b)=>{let _=En(x.json??x.JsonObj??x.JsonStr??x);e.push(..._.errors.map(k=>`pages[${b}]: ${k}`)),r.push(..._.warnings.map(k=>`pages[${b}]: ${k}`)),n.push(`save_page ${w(x,"title","Title")}`)}),p.forEach((x,b)=>{let _=la(x.PageObj??x.pageObj),k=ua(x.PrintObj??x.printObj);e.push(..._.errors.map(S=>`printTemplates[${b}].PageObj: ${S}`)),r.push(..._.warnings.map(S=>`printTemplates[${b}].PageObj: ${S}`)),e.push(...k.errors.map(S=>`printTemplates[${b}].PrintObj: ${S}`)),r.push(...k.warnings.map(S=>`printTemplates[${b}].PrintObj: ${S}`)),n.push(`save_print_template ${w(x,"title","Title")}`)}),d.forEach((x,b)=>{let _=Cx(x);e.push(..._.errors.map(k=>`workflows[${b}]: ${k}`)),r.push(..._.warnings.map(k=>`workflows[${b}]: ${k}`)),n.push(`save_workflow ${w(ee(x.FlowDesign??x.flowDesign??x),"FlowName","flowName","name")}`)}),h.forEach(x=>n.push(`save_job ${w(x,"jobName","JobName")}`)),{plan:n,errors:e,warnings:r}}function Ox(t){return{flow:ee(t.FlowDesign??t.flowDesign??t),nodes:ce(t,"Nodes","nodes"),lines:ce(t,"Lines","lines")}}function Ro(t){return w(t,"Id","id","NodeId","nodeId")}function da(t){return w(t,"NodeName","nodeName","Name","name")}function SR(t){return w(t,"NodeType","nodeType","Type","type")}function Tx(t){let e=`${SR(t)} ${da(t)}`.toLowerCase();return e.includes("start")||e.includes("begin")||e.includes("\u5F00\u59CB")||e.includes("\u53D1\u8D77")}function oR(t){let e=`${SR(t)} ${da(t)}`.toLowerCase();return e.includes("end")||e.includes("finish")||e.includes("\u7ED3\u675F")||e.includes("\u5B8C\u6210")}function Cx(t){let e=[],r=[],{flow:n,nodes:i,lines:a}=Ox(t),o=w(n,"FlowName","flowName","Name","name"),s=w(n,"TableId","tableId"),c=w(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=Ro(m),v=da(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=w(m,"Id","id","LineId","lineId")||`(index ${g})`,v=w(m,"FromNodeId","fromNodeId"),x=w(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(Tx),h=i.filter(oR);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=Ro(m),y=da(m)||g;if(!g)return;let v=u.get(g)||[],x=p.get(g)||[];!Tx(m)&&x.length===0&&r.push(`\u8282\u70B9 ${y} \u6CA1\u6709\u5165\u7EBF`),!oR(m)&&v.length===0&&r.push(`\u8282\u70B9 ${y} \u6CA1\u6709\u51FA\u7EBF`),v.length>1&&(w(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:Ro(m),name:da(m)})),endNodes:h.map(m=>({id:Ro(m),name:da(m)}))}}}function dW(t){let e=t.indexOf(rR);if(e<0)return null;let r=e+rR.length,n=t.indexOf(MK,r);if(n<0)return null;try{return ee(JSON.parse(t.slice(r,n).trim()))}catch{return null}}function sR(t){return t==null||String(t).trim()===""}function cR(t,e){let r=w(t,"field","Field"),n=w(t,"operator","Operator")||"eq",i=ct(t,"value","Value"),a=r?e[r]:void 0,o=a==null?"":String(a),s=i==null?"":String(i);if(n==="empty")return sR(a);if(n==="notEmpty")return!sR(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 fW(t){let e=ee(t.workflow),r=ee(t.formData),n=w(t,"lineValueV8Code","LineValueV8","code");if(!n&&Object.keys(e).length>0){let{nodes:s}=Ox(e),c=w(t,"nodeId","NodeId"),l=(c?s.find(u=>Ro(u)===c):s.find(Tx)||s[0])||{};n=w(l,"LineValueV8","lineValueV8","V8Code","v8Code")}let i=dW(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=>!!ct(s,"isDefault","IsDefault"))||null;for(let s of a){if(s===o)continue;let c=ce(s,"rules","Rules").filter(u=>w(u,"field","Field"));if(c.length===0)continue;if(w(s,"match","Match")==="any"?c.some(u=>cR(u,r)):c.every(u=>cR(u,r)))return{ok:!0,selectedRoute:s,assignment:lR(s),source:"matched"}}return{ok:!!o,selectedRoute:o,assignment:o?lR(o):null,source:o?"default":"none"}}function lR(t){let e=w(t,"lineValue","LineValue"),r=w(t,"toNodeId","ToNodeId");return e?{LineValue:e}:{NextNodeId:r}}function mW(t,e){let{flow:r,nodes:n,lines:i}=Ox(t),a={...r},o=w(r,"table","tableName","TableName","diyTableName","DiyTableName");if(!w(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=Ro(u)||`wf_node_${p+1}_${xx().slice(0,8)}`,h={...u,Id:d},m=da(h);return m&&s.set(d,m),h}),l=i.map((u,p)=>{let d=w(u,"FromNodeId","fromNodeId"),h=w(u,"ToNodeId","toNodeId"),m=w(u,"LineName","lineName")||`${s.get(d)||d||"\u5F53\u524D\u8282\u70B9"} \u5230 ${s.get(h)||h||"\u4E0B\u4E00\u8282\u70B9"}`;return{...u,Id:w(u,"Id","id","LineId","lineId")||`wf_line_${p+1}_${xx().slice(0,8)}`,LineName:m}});return{FlowDesign:a,Nodes:c,Lines:l}}async function xr(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 uR(t,e){let r=w(e,"apiEngineKey","ApiEngineKey"),n=w(e,"apiName","ApiName","name","Name")||r,i=w(e,"category","Category")||"AI\u751F\u6210",a=ct(e,"code","Code","ApiV8Code"),o=typeof a=="string",s=o?String(a):"",c=Lc(e),l=await t.getEngineCode(r);return l.Code===1?!o&&c!==void 0?t.updateEngineRuntimeLimit(r,c):o?t.saveEngineCode(r,s,{functionDescription:w(e,"functionDescription","FunctionDescription")||void 0,changeSummary:w(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:w(e,"functionDescription","FunctionDescription")||void 0,changeSummary:w(e,"changeSummary","ChangeSummary")||void 0})}function hW(t,e,r,n){let i=w(t,"table","tableName","diyTableName","DiyTableName"),a=No(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 FK(t,e={}){let r=ee(t),n=ee(r.Workload??r.workload??r.BackgroundWorkload??r.backgroundWorkload),i=[],a=ie(n,"ExpectedSeconds","expectedSeconds")??0,o=ie(n,"ExpectedItems","expectedItems","EstimatedRows","estimatedRows")??0,s=ie(n,"FanOutOperations","fanOutOperations","FanOut","fanOut")??0,c=ie(n,"ExternalCalls","externalCalls")??0;a>=120&&i.push(`\u9884\u8BA1\u8017\u65F6 ${a}s >= 120s`),o>=500&&i.push(`\u9884\u8BA1\u5904\u7406 ${o} \u6761 >= 500 \u6761`),s>=1e3&&i.push(`\u9884\u8BA1\u6247\u51FA ${s} \u4E2A\u5B50\u64CD\u4F5C >= 1000`),c>=100&&i.push(`\u9884\u8BA1\u5916\u90E8\u8C03\u7528 ${c} \u6B21 >= 100 \u6B21`),Er(n,"UnknownTotal","unknownTotal")===!0&&i.push("\u603B\u5DE5\u4F5C\u91CF\u672A\u77E5\u4E14\u53EF\u80FD\u957F\u65F6\u95F4\u8FD0\u884C");let l=w(r,"V8Code","v8Code"),u=[w(r,"Name","name"),w(r,"ApiEngineKey","apiEngineKey"),l].join(" "),p=/\bV8\.OpenAppDialog\s*\(/i.test(l)&&!/\bV8\.(?:ApiEngine\.RunBackground|Method\.QueueBackgroundTask)\s*\(/i.test(l);return e.inferActionSemantics!==!1&&!p&&/(批量.{0,4}(导入|生成|修复|处理)|安装|初始化|全量同步|数据迁移|数据库备份|批量任务)/i.test(u)&&i.push("\u52A8\u4F5C\u8BED\u4E49\u5C5E\u4E8E\u5178\u578B\u957F\u4EFB\u52A1"),{required:i.length>0,reasons:i}}function zK(t){let e=ee(t),r=ee(e.Workload??e.workload??e.BackgroundWorkload??e.backgroundWorkload),n=w(r,"ExecutionMode","executionMode").trim().toLowerCase(),i=Er(r,"ClientChunked","clientChunked")===!0||n==="clientchunked"||n==="clientsequential",a=ie(r,"MaxItemsPerChunk","maxItemsPerChunk")??0,o=Er(r,"Resumable","resumable")===!0;return{declared:i,valid:i&&a>0&&o,maxItemsPerChunk:a,resumable:o}}var md="https://api.itdos.com",yx="iTdos";function LK(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||md).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!==md)throw new Error(`storeApiBase \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE ${md}\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=md,o=String(t.storeOsClient||yx).trim();if(o.toLowerCase()!==yx.toLowerCase())throw new Error(`storeOsClient \u4EC5\u5141\u8BB8\u543E\u7801\u5B98\u65B9\u5546\u57CE\u79DF\u6237 ${yx}\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:zr({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 jK(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=w(l,"Name","name");u||r.push(`${t}[${c}].Name \u4E0D\u80FD\u4E3A\u7A7A`);let p=FK(l,{inferActionSemantics:t!=="PageTabs"}),d=zK(l),h=l.RunBackground??l.runBackground??l.BackgroundTask??l.backgroundTask??l.IsBackgroundTask??l.isBackgroundTask,m=w(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&&(!w(g,"IdempotencyKey","idempotencyKey")&&!$o(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`),w(g,"BusinessTable","businessTable")&&(!w(g,"BusinessStatusField","businessStatusField")||!w(g,"BusinessTaskIdField","businessTaskIdField"))&&n.push(`${t}[${c}] \u5DF2\u5173\u8054\u4E1A\u52A1\u8868\uFF0C\u4F46\u7F3A\u5C11 BusinessStatusField/BusinessTaskIdField`));let y=w(l,"TargetSysMenuId","targetSysMenuId"),v=t==="PageTabs"&&!!y;!w(l,"V8Code","v8Code")&&!w(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=w(l,"Id","id")||xx();w(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=w(l,"V8CodeShow","v8CodeShow");return b&&!b.includes("V8.Result")&&n.push(`${t}[${c}].V8CodeShow \u5EFA\u8BAE\u663E\u5F0F\u8D4B\u503C V8.Result=true/false`),zr({...l,Id:x,Sort:ie(l,"Sort","sort")??c*10,Name:u,Icon:w(l,"Icon","icon")||void 0,BtnStyle:w(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:w(l,"V8Code","v8Code")||void 0,Url:w(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 No(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=jK(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]=w(t,c,l),delete e[l]);let s=["ViewSchema","viewSchema"].find(c=>t[c]!==void 0);if(s){let c=vd(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 Er(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 VK(t,e,r,n){let i=ct(t,"v8Limit","V8Limit"),a=ct(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(a==null||a===""))return;let o=i!=null&&i!=="",s=o?Er(t,"v8Limit","V8Limit"):Lc(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(o&&a!==void 0){let c=Er(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\u8868\u5355\u5F15\u64CE\u8BF7\u6539\u7528\u6B63\u5411\u5B57\u6BB5 v8Limit\uFF08false=\u4E0D\u9650\uFF0Ctrue=\u542F\u7528\u9650\u5236\uFF09`);return s}function qK(t,e){return{ok:e.Code===1,results:t,validation:{Code:e.Code,Msg:e.Msg??null,Data:e.Data??null}}}function Lc(t){let e=Er(t,"v8Limit","V8Limit");if(e!==void 0)return e;let r=Er(t,"v8Unlimited","V8Unlimited");return r===void 0?void 0:!r}function BK(t,e,r,n){let i=ct(t,"v8Limit","V8Limit"),a=ct(t,"v8Unlimited","V8Unlimited");if((i==null||i==="")&&(a==null||a===""))return;let o=i!=null&&i!=="",s=o?Er(t,"v8Limit","V8Limit"):Lc(t);if(s===void 0){r.push(`${e}.v8Limit \u5FC5\u987B\u662F boolean \u6216 0/1`);return}if(o&&a!==void 0){let c=Er(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 UK=["Detail","Edit","List","Card"],JK=["PC","Mobile","All"],ZK=["ApiEngine","OpenDetail","OpenList","OpenForm","Navigate","Dial","Scan","Map","Refresh","Back","Copy"],HK=new Set(["v8code","v8codeshow","script","javascript","eval","onclick","function"]);function wx(t,e){let r=String(t??"").trim().toLowerCase();return e.find(n=>n.toLowerCase()===r)||""}function Tn(t,...e){let r=new Set(e.map(i=>i.toLowerCase()));return Object.entries(t).find(([i])=>r.has(i.toLowerCase()))?.[1]}function _x(t,e="ViewSchema"){if(Array.isArray(t)){for(let r=0;r<t.length;r+=1){let n=_x(t[r],`${e}[${r}]`);if(n)return n}return""}if(!t||typeof t!="object")return"";for(let[r,n]of Object.entries(t)){if(HK.has(r.toLowerCase()))return`${e}.${r}`;let i=_x(n,`${e}.${r}`);if(i)return i}return""}function Sx(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=wx(Tn(o,"ActionType","Type"),ZK);if(!s){n.push(`${e}[${a}].ActionType \u4E0D\u53D7\u652F\u6301`);return}s==="ApiEngine"&&!w(o,"ApiEngineKey","apiEngineKey")&&n.push(`${e}[${a}] \u4F7F\u7528 ApiEngine \u65F6\u5FC5\u987B\u914D\u7F6E ApiEngineKey`);let c=Tn(o,"SuccessActions");n.push(...Sx(c,`${e}[${a}].SuccessActions`,r+1))}),n}function vd(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=_x(n);i&&e.push(`ViewSchema \u4E0D\u5141\u8BB8\u5305\u542B\u53EF\u6267\u884C\u524D\u7AEF\u811A\u672C\u5B57\u6BB5\uFF1A${i}`);let o=Tn(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}wx(Tn(u,"Scene"),UK)||e.push(`ViewSchema.Views[${l}].Scene \u4E0D\u53D7\u652F\u6301`);let p=Tn(u,"Device");p!==void 0&&!wx(p,JK)&&e.push(`ViewSchema.Views[${l}].Device \u4E0D\u53D7\u652F\u6301`);let d=Tn(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(...Sx(Tn(h,"Actions","ActionSchema"),`ViewSchema.Views[${l}].Layout.Actions`));let m=Tn(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(...Sx(Tn(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 xR(t,e){let r=[],n=t.toLowerCase();if(n==="keyvalue"){let i=w(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()}}):gd(e.items).map(o=>({Key:w(o,"Key","key"),Value:w(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=w(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=w(e,"sql","Sql");return i||r.push("SQL \u6570\u636E\u6E90\u7F3A\u5C11 sql"),{config:{DataSource:"Sql",Sql:i,SelectLabel:w(e,"selectLabel","SelectLabel")||"Name",SelectSaveField:w(e,"selectSaveField","SelectSaveField")||"Id",DataSourceSqlRemote:e.dataSourceSqlRemote??e.DataSourceSqlRemote??!0,EnableSearch:e.enableSearch??e.EnableSearch??!0},warnings:r}}if(n==="apiengine"){let i=w(e,"apiEngineKey","DataSourceApiEngineKey");return i||r.push("\u63A5\u53E3\u5F15\u64CE\u6570\u636E\u6E90\u7F3A\u5C11 apiEngineKey"),{config:{DataSource:"ApiEngine",DataSourceApiEngineKey:i,SelectLabel:w(e,"selectLabel")||"name",SelectSaveField:w(e,"selectSaveField")||"id"},warnings:r}}if(n==="datasource"){let i=w(e,"dataSourceId","DataSourceId");return i||r.push("\u6570\u636E\u6E90\u5F15\u64CE\u914D\u7F6E\u7F3A\u5C11 dataSourceId"),{config:{DataSource:"DataSource",DataSourceId:i,SelectLabel:w(e,"selectLabel")||"Name",SelectSaveField:w(e,"selectSaveField")||"Id"},warnings:r}}if(n==="autonumber")return{config:{AutoNumberFixed:w(e,"prefix","AutoNumberFixed"),AutoNumberLength:ie(e,"length","AutoNumberLength")??4},warnings:r};if(n==="datetime")return{config:{DateTimeType:w(e,"dateTimeType","DateTimeType")||"datetime"},warnings:r};if(n==="joinform"){let i=w(e,"tableId"),a=w(e,"tableName"),o=w(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:zr({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 bx(t,e){let r=kr(t);return zr({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||(yd.has(r)||Sr(t)||r==="numbertext"?"In":"Out"),DisplaySelect:e?.displaySelect??["opentable","joinform","department","selecttree"].includes(r),Equal:e?.equal??(yd.has(r)||r==="numbertext"?!0:void 0),IsVisible:!0})}function Io(t,e,r,n,i){return n.map(a=>{let o=nR(t,e,a.ref)||nR(t,r,a.ref)||(Fc(a.ref)?vR(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=ct(t,r);if(!(n==null||n===""))return typeof n=="string"?n:JSON.stringify(n)}return""}var KK=new Set(["id","osclient","isdeleted","createuserid","updateuserid","deleteuserid","tenantid","storeid","userid","userids","roleid","roleids","parentid","parentids","class","code","enname","endescription"]),Rx=new Set(["button","divider","collapsegroup","tabs","alert","statictext","html","devcomponent"]),WK=new Set(["textarea","richtext","codeeditor","jsontable","imgupload","fileupload","tablechild","map","maparea","jointable","opentable","treecheckbox","transfer"]),GK=new Set(["text","textarea","select","multipleselect","radio","checkbox","datetime","date","numbertext","autonumber","switch","department","address","cascader","selecttree","opentable","joinform","autocomplete","taginput"]),yd=new Set(["select","multipleselect","radio","checkbox","switch","department","selecttree","opentable","joinform","cascader"]);function Yt(t){return(t||"").trim().toLowerCase()}function st(t){return`${t.name||""} ${t.label||""} ${t.component||""} ${t.type||""}`.toLowerCase()}function me(t,e){return e.some(r=>t.includes(r.toLowerCase()))}function kr(t){return Yt(t.component||"Text")}function XK(t){return Rx.has(kr(t))}function YK(t){return WK.has(kr(t))}function QK(t){let e=t.name||"",r=Yt(e).replace(/[_\-\s]+/g,"");return!!(KK.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 jc(t){return Fc(t.name)&&!["CreateTime","UpdateTime","UserName"].some(e=>e.toLowerCase()===t.name.toLowerCase())||QK(t)||XK(t)||YK(t)?!0:kr(t).includes("hidden")}function ci(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 _r(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 xd(t){let e=Yt(t.type);return kr(t)==="numbertext"||e.startsWith("decimal")||e==="int"||e==="bigint"}function Sr(t){let e=st(t);return kr(t)==="datetime"||me(e,["time","date","\u65E5\u671F","\u65F6\u95F4"])}function eW(t){let e=kr(t),r=yd.has(e)||e==="numbertext"||e==="rate"||e==="progress";return{ref:t.name,displayType:r||Sr(t)?"In":"Out",displaySelect:["opentable","joinform","department","selecttree"].includes(e),equal:r?!0:void 0}}function iR(t){let e=st(t),r=0;return me(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),me(e,["status","state","type","category","level","class","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])&&(r+=45),me(e,["customer","member","user","owner","\u8D1F\u8D23\u4EBA","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8054\u7CFB\u4EBA"])&&(r+=35),Sr(t)&&(r+=25),xd(t)&&!me(e,["phone","mobile","tel","\u7535\u8BDD","\u624B\u673A"])&&(r+=15),kr(t)==="textarea"&&(r-=25),r}function Ex(t){let e=st(t),r=0;return me(e,["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])&&(r+=70),me(e,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])&&(r+=45),me(e,["customer","member","user","owner","phone","mobile","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u7535\u8BDD","\u624B\u673A"])&&(r+=35),me(e,["amount","money","price","total","count","qty","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D","\u6570\u91CF","\u79EF\u5206","\u4F59\u989D"])&&(r+=30),Sr(t)&&(r+=15),kr(t)==="autonumber"&&(r+=55),r}function tW(t){return ci(t.filter(jc))}function Vc(t){let e=t.filter(n=>!jc(n)),r=e.length?e:t;return ci(_r(r,Ex)).slice(0,Math.min(12,r.length))}function rW(t){let e=t.filter(n=>!jc(n)&&GK.has(kr(n))),r=_r(e,iR).filter(n=>iR(n)>0);return ci(r.length?r:e).slice(0,Math.min(8,e.length))}function nW(t){let e=t.filter(r=>!jc(r)&&(Sr(r)||xd(r)||Yt(r.name)==="sort"));return ci(_r(e,r=>{let n=st(r);return me(n,["update","\u4FEE\u6539"])?80:me(n,["create","\u521B\u5EFA"])?75:Yt(r.name)==="sort"?70:me(n,["amount","money","price","total","count","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?60:20})).slice(0,Math.min(8,e.length))}function wR(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!jc(n)&&xd(n)&&!me(i,e)&&me(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 ci(_r(r,n=>me(st(n),["amount","money","price","total","\u91D1\u989D","\u4EF7\u683C","\u603B\u989D"])?80:40)).slice(0,6)}function iW(t){let e=Vc(t),r=_r(e,a=>me(st(a),["name","title","no","code","\u540D\u79F0","\u6807\u9898","\u7F16\u53F7"])?100:0)[0],n=_r(e.filter(a=>a!==r),a=>me(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 ci([r,...n.slice(0,1),...i].filter(Boolean)).slice(0,4)}function aW(t){return _r(Vc(t),e=>me(st(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])?100:0).filter(e=>me(st(e),["status","state","type","category","level","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u7B49\u7EA7"])).slice(0,2)}function oW(t){return _r(Vc(t),e=>{let r=st(e);return me(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])?90:Sr(e)?60:0}).filter(e=>{let r=st(e);return Sr(e)||me(r,["amount","money","price","total","count","qty","\u79EF\u5206","\u4F59\u989D","\u91D1\u989D","\u4EF7\u683C","\u6570\u91CF"])}).slice(0,3)}function _R(t,e=0){let r=ee(t),n=w(r,"name","Name");return n?{id:w(r,"id","Id")||n,name:n,label:w(r,"label","Label")||n,tableId:w(r,"tableId","TableId"),tableName:w(r,"tableName","TableName"),tableDescription:w(r,"tableDescription","TableDescription"),component:w(r,"component","Component")||"Text",type:w(r,"type","Type")||"varchar(500)"}:null}function wd(t){let e=_R(t);if(!e)return 150;let r=st(e),n=kr(e);return["richtext","textarea","address","map","maparea","fileupload","imgupload"].includes(n)||me(r,["address","remark","description","content","\u5730\u5740","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247"])?240:me(r,["name","title","subject","customer","company","\u540D\u79F0","\u6807\u9898","\u4E3B\u9898","\u5BA2\u6237","\u4F01\u4E1A"])?200:Sr(e)?170:xd(e)?140:n==="autonumber"||me(r,["phone","mobile","email","code","number","\u7F16\u53F7","\u5355\u53F7","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1"])?160:yd.has(n)||me(r,["status","state","type","category","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B"])?130:150}function kn(t,e={}){return{Name:t.name,Label:t.label||t.name,...e}}function pa(t,e,r){let n=[];for(let i of t)if(!(!i?.name||r.has(Yt(i.name)))&&(r.add(Yt(i.name)),n.push(i),n.length>=e))break;return n}function $x(t,e,r=""){let n=e.map(_R).filter(Boolean),i=Vc(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=_r(i,A=>{let D=st(A);return me(D,["title","subject","\u6807\u9898","\u4E3B\u9898"])?150:me(D,["name","\u540D\u79F0"])?130:kr(A)==="autonumber"||me(D,["no","code","number","\u7F16\u53F7","\u5355\u53F7","\u7F16\u7801"])?110:Ex(A)})[0]||i[0],l=_r(i.filter(A=>A!==c),A=>me(st(A),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])?100:0).filter(A=>me(st(A),["status","state","type","category","stage","\u72B6\u6001","\u7C7B\u578B","\u5206\u7C7B","\u9636\u6BB5"])),u=wR(n).filter(A=>A!==c),p=_r(n.filter(Sr),A=>me(st(A),["create","\u521B\u5EFA"])?100:50),d=_r(i.filter(A=>A!==c&&!l.includes(A)&&!u.includes(A)),A=>{let D=st(A);return me(D,["customer","member","user","owner","contact","\u5BA2\u6237","\u4F1A\u5458","\u7528\u6237","\u8D1F\u8D23\u4EBA","\u8054\u7CFB\u4EBA"])?90:Sr(A)?70:Ex(A)}).slice(0,1),h=ci([...l.slice(0,1),...u.slice(0,1)]),m=ci([c,...d,...h].filter(Boolean)).map(A=>A.name),g=c?Math.min(520,Math.max(340,wd(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,D)=>({Key:`Aggregate:${A.name}`,Label:`${A.label||A.name}\u5408\u8BA1`,Source:"Field",Field:A.name,...y[D]}));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?[Yt(c.name)]:[]),b=pa(d,1,x),_=pa(l,1,x),k=pa(l,1,x),S=pa(u,1,x),T=pa(p,2,x),C=pa(i,2,x),O=pa([...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=>kn(A,{Icon:Sr(A)?"fas fa-clock":"fas fa-circle-info",Tone:"info"})),TrailingFields:h.map(A=>kn(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=>kn(A,{Icon:"fas fa-circle-info",Tone:"info"})),StatusFields:_.map(A=>kn(A,{DisplayStyle:"Tag",Icon:"fas fa-circle-check",Tone:"success"})),TopFields:k.map(A=>kn(A,{DisplayStyle:"Tag",Icon:"fas fa-tag",Tone:"primary"})),RightFields:S.map(A=>kn(A,{Icon:"fas fa-coins",Tone:"danger",FontWeight:"700"})),Fields:C.map(A=>kn(A)),MetaFields:T.map(A=>kn(A,{Icon:"fas fa-clock",Tone:"info"})),BottomFields:O.map(A=>kn(A,{Icon:Sr(A)?"fas fa-calendar":"fas fa-chart-simple",Tone:"warning"})),HideIndex:!0,ShowCreateTime:T.length===0,ShowUpdateTime:!1}}}]}}function sW(t,e,r){let n=t.length?t:[vR(e,r,"CreateTime")],i=n.find(a=>Yt(a.name)==="createtime")||n.find(a=>Yt(a.name)==="updatetime")||n.find(a=>Yt(a.name)==="sort");if(i)return JSON.stringify([{Id:i.id,Name:i.name,Type:Yt(i.name)==="sort"?"ASC":"DESC",Sort:0}])}function cW(t,e,r,n){let i=ct(t,"DefaultOrderBy");if(i!=null&&i!=="")return typeof i=="string"?i:JSON.stringify(i);let a=ct(t,"defaultOrderBy");if(a!=null&&a!==""){let s=Array.isArray(a)||typeof a=="string"&&a.trim().startsWith("[")?wr({value:a},"value"):[{ref:String(a).trim(),type:"DESC"}];return JSON.stringify(Io(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=wr(t,"orderBy","OrderBy","defaultSort","DefaultSort","sortBy","SortBy");if(o.length)return JSON.stringify(Io(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 lW(t,e,r,n){if(!r&&!n)return{};let i=Oo(e,r).length?Oo(e,r):Oo(e,n),a={},o=wr(t,"searchFields","SearchFields","searchFieldNames","SearchFieldNames"),s=o.length?Io(e,r,n,o,"module.searchFields"):rW(i).map(h=>({meta:h,ref:eW(h)}));!nt(t,"searchFieldIds","SearchFieldIds")&&s.length&&(a.SearchFieldIds=JSON.stringify(s.map(({meta:h,ref:m})=>bx(h,m))));let c=wr(t,"listFields","ListFields","tableFields","TableFields","columns","Columns"),l=c.length?Io(e,r,n,c,"module.listFields"):Vc(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})=>bx(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=wr(t,...h.refKeys),g={SortFieldIds:nW(i),NotShowFields:tW(i),MobileListFields:iW(i),CardTitleTagFields:aW(i),CardBottomTagFields:oW(i),InTableEditFields:[]};if(!m.length&&!g[h.canonical]?.length)continue;let y=m.length?Io(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})=>bx(v,x)):y.map(({meta:v})=>v.id))}let p=wr(t,"statisticsFieldNames","StatisticsFieldNames","statFields","StatFields");if(!nt(t,"statisticsFields","StatisticsFields")){let h=p.length?Io(e,r,n,p,"module.statisticsFields"):wR(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=cW(t,e,r,n)||(nt(t,"DefaultOrderBy","defaultOrderBy")?void 0:sW(i,r,n));return d&&(a.DefaultOrderBy=d),a}function aR(t,e,r){let n=gd(ee(e).Tables);for(let i of n){let a=w(i,"Id","id"),o=w(i,"Name","name");if(!a||!o)continue;r?.set(o.toLowerCase(),a);let s=ct(i,"_Fields","Fields","fields"),c=Array.isArray(s)?gd(s):[];for(let l of c){let u=w(l,"Id","id"),p=w(l,"Name","name");!u||!p||bR(t,{id:u,name:p,label:w(l,"Label","label")||p,tableId:a,tableName:o,tableDescription:w(i,"Description","description")||o,component:w(l,"Component","component")||"Text",type:w(l,"Type","type")||"varchar(255)"})}}}function kt(t){return Yt(w(t,"component","Component")||"Text")}function uW(t){return`${w(t,"name","Name")} ${w(t,"label","Label")} ${w(t,"component","Component")}`.toLowerCase()}function pW(t,e){let r=uW(t),n=kt(t);return["imgupload","fileupload","richtext","codeeditor","jsontable","tablechild","map","maparea","textarea"].includes(n)||me(r,["remark","note","content","file","image","attach","map","\u5907\u6CE8","\u8BF4\u660E","\u5185\u5BB9","\u9644\u4EF6","\u56FE\u7247","\u5730\u56FE"])?"attachment":me(r,["phone","mobile","email","address","city","contact","\u8054\u7CFB\u4EBA","\u7535\u8BDD","\u624B\u673A","\u90AE\u7BB1","\u5730\u5740","\u57CE\u5E02"])?"contact":me(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 kx(t){let e=ce(t,"fields","Fields"),r=ct(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=>!Rx.has(kt(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=w(l,"name","Name");if(!p||w(l,"tab","Tab"))return;let d=pW(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 vx(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,y=new Set(o.map(x=>w(x,"apiEngineKey","ApiEngineKey").toLowerCase()).filter(Boolean));!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 v=SW(t);return e.push(...v.errors),r.push(...v.warnings),i.forEach(x=>n.push(`save_role ${w(x,"name","Name")}`)),a.forEach((x,b)=>{let _=w(x,"name","Name");_||e.push(`tables[${b}].name \u4E0D\u80FD\u4E3A\u7A7A`),VK(x,`tables[${b}]`,e,r),n.push(`create_table ${_||`(index ${b})`}`),kx(x).tabs?.length&&r.push(`table ${_||`(index ${b})`} has many fields; generator will create diy_table.Tabs and assign empty field Tab values automatically`),_&&g.set(_.toLowerCase(),new Set),ce(x,"fields","Fields").forEach((D,Z)=>{let V=w(D,"name","Name"),te=w(D,"label","Label");V||e.push(`tables[${b}].fields[${Z}].name \u4E0D\u80FD\u4E3A\u7A7A`),te||e.push(`tables[${b}].fields[${Z}].label \u4E0D\u80FD\u4E3A\u7A7A`),_&&V&&g.get(_.toLowerCase())?.add(V.toLowerCase()),_&&te&&g.get(_.toLowerCase())?.add(te.toLowerCase()),n.push(`add_field ${_}.${V}`)});let S=_d(x);n.push(`configure_form_banner ${_||`(index ${b})`}`);let T=g.get(_.toLowerCase())||new Set,C=(D,Z)=>{D&&!T.has(D.toLowerCase())&&!Fc(D)&&e.push(`${Z} references unknown field "${D}" on table "${_}"`)};C(w(S,"FormBannerTitleField"),`tables[${b}].formBanner.titleField`),C(w(S,"FormBannerSubtitleField"),`tables[${b}].formBanner.subtitleField`),C(w(S,"FormBannerImageField"),`tables[${b}].formBanner.imageField`),C(w(S,"FormBannerBackgroundField"),`tables[${b}].formBanner.backgroundField`),bd(JSON.parse(w(S,"FormBannerTagFields")||"[]")).forEach((D,Z)=>{let V=typeof D=="string"?D:w(ee(D),"Field","field","Name","name");C(V,`tables[${b}].formBanner.tagFields[${Z}]`)}),bd(JSON.parse(w(S,"FormBannerMetrics")||"[]")).forEach((D,Z)=>{let V=ee(D),te=typeof D=="string"?D:w(V,"Field","field","Name","name");C(te,`tables[${b}].formBanner.metrics[${Z}]`);let _e=w(V,"ApiEngineKey","apiEngineKey");_e&&!y.has(_e.toLowerCase())&&r.push(`tables[${b}].formBanner.metrics[${Z}] references ApiEngineKey "${_e}" not declared in this manifest; it must already exist in the target tenant`)});let A=new Set(ce(x,"fields","Fields").map(D=>w(D,"name","Name").toLowerCase()).filter(Boolean));["id","createtime","updatetime","createuser","osclient"].forEach(D=>A.add(D)),ce(x,"indexes","Indexes").forEach((D,Z)=>{let V=$o(D,"columns","Columns");V.length||e.push(`tables[${b}].indexes[${Z}].columns \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5B57\u6BB5`);for(let te of V)A.has(te.toLowerCase())||e.push(`tables[${b}].indexes[${Z}] references unknown physical field "${te}" on table "${_}"`);V.some((te,_e)=>V.findIndex(xt=>xt.toLowerCase()===te.toLowerCase())!==_e)&&e.push(`tables[${b}].indexes[${Z}] \u5305\u542B\u91CD\u590D\u5B57\u6BB5`),n.push(`create_index ${_}.${w(D,"name","Name")||V.join("_")}`)})}),l.forEach(x=>n.push(`save_data_source ${w(x,"dataSourceKey","DataSourceKey")}`)),o.forEach((x,b)=>{let _=w(x,"apiEngineKey","ApiEngineKey");_||e.push(`engines[${b}].apiEngineKey \u4E0D\u80FD\u4E3A\u7A7A`),BK(x,`engines[${b}]`,e,r),n.push(`upsert_engine ${_}`)}),c.forEach(x=>n.push(`save_event ${w(x,"formEngineKey","FormEngineKey")}/${w(x,"eventType","EventType")}`)),s.forEach(x=>{let b=No(x);e.push(...b.errors),r.push(...b.warnings);let _=w(x,"table","tableName","diyTableName","DiyTableName"),k=w(x,"name","Name"),S=w(x,"openType","OpenType"),T=w(x,"microServiceKey","MicroServiceKey"),C=w(x,"microServiceRoutePath","MicroServiceRoutePath");if(S.toLowerCase()==="microservice"||!!(ie(x,"isMicroiService","IsMicroiService")===1||T||C||w(x,"microServiceId","MicroServiceId")||w(x,"microServicePageId","MicroServicePageId"))){if(T||e.push(`modules.${k||"(unnamed)"}.microServiceKey \u4E0D\u80FD\u4E3A\u7A7A`),C||e.push(`modules.${k||"(unnamed)"}.microServiceRoutePath \u4E0D\u80FD\u4E3A\u7A7A`),C)try{Ix(C)}catch(P){e.push(`modules.${k||"(unnamed)"}.microServiceRoutePath ${P instanceof Error?P.message:String(P)}`)}n.push(`resolve_microservice_binding ${T||"(missing)"}${C||"/(missing)"}`)}if(_&&g.has(_.toLowerCase())){let P=g.get(_.toLowerCase())||new Set,A=[["listFields",wr(x,"listFields","ListFields","tableFields","TableFields","columns","Columns")],["searchFields",wr(x,"searchFields","SearchFields","searchFieldNames","SearchFieldNames")],["sortFields",wr(x,"sortFields","SortFields")],["hiddenFields",wr(x,"hiddenFields","HiddenFields","notShowFieldsByName","NotShowFieldsByName")],["mobileFields",wr(x,"mobileFields","MobileFields")]];for(let[D,Z]of A)for(let V of Z)!P.has(V.ref.toLowerCase())&&!Fc(V.ref)&&e.push(`modules.${k||_}.${D} references unknown field "${V.ref}" on table "${_}"`)}_&&!wr(x,"listFields","ListFields","tableFields","TableFields","columns","Columns").length&&!nt(x,"TableDiyFieldIds","SelectFields")&&r.push(`module ${k||_} has no listFields; generator will use the first business fields from ${_}`),n.push(`create_or_update_module ${w(x,"name","Name")}`)}),m.forEach(x=>n.push(`set_permission ${w(x,"roleId","RoleId")||"admin"}`)),u.forEach((x,b)=>{let _=En(x.json??x.JsonObj??x.JsonStr??x);e.push(..._.errors.map(k=>`pages[${b}]: ${k}`)),r.push(..._.warnings.map(k=>`pages[${b}]: ${k}`)),n.push(`save_page ${w(x,"title","Title")}`)}),p.forEach((x,b)=>{let _=la(x.PageObj??x.pageObj),k=ua(x.PrintObj??x.printObj);e.push(..._.errors.map(S=>`printTemplates[${b}].PageObj: ${S}`)),r.push(..._.warnings.map(S=>`printTemplates[${b}].PageObj: ${S}`)),e.push(...k.errors.map(S=>`printTemplates[${b}].PrintObj: ${S}`)),r.push(...k.warnings.map(S=>`printTemplates[${b}].PrintObj: ${S}`)),n.push(`save_print_template ${w(x,"title","Title")}`)}),d.forEach((x,b)=>{let _=Cx(x);e.push(..._.errors.map(k=>`workflows[${b}]: ${k}`)),r.push(..._.warnings.map(k=>`workflows[${b}]: ${k}`)),n.push(`save_workflow ${w(ee(x.FlowDesign??x.flowDesign??x),"FlowName","flowName","name")}`)}),h.forEach(x=>n.push(`save_job ${w(x,"jobName","JobName")}`)),{plan:n,errors:e,warnings:r}}function Ox(t){return{flow:ee(t.FlowDesign??t.flowDesign??t),nodes:ce(t,"Nodes","nodes"),lines:ce(t,"Lines","lines")}}function Ro(t){return w(t,"Id","id","NodeId","nodeId")}function da(t){return w(t,"NodeName","nodeName","Name","name")}function SR(t){return w(t,"NodeType","nodeType","Type","type")}function Tx(t){let e=`${SR(t)} ${da(t)}`.toLowerCase();return e.includes("start")||e.includes("begin")||e.includes("\u5F00\u59CB")||e.includes("\u53D1\u8D77")}function oR(t){let e=`${SR(t)} ${da(t)}`.toLowerCase();return e.includes("end")||e.includes("finish")||e.includes("\u7ED3\u675F")||e.includes("\u5B8C\u6210")}function Cx(t){let e=[],r=[],{flow:n,nodes:i,lines:a}=Ox(t),o=w(n,"FlowName","flowName","Name","name"),s=w(n,"TableId","tableId"),c=w(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=Ro(m),v=da(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=w(m,"Id","id","LineId","lineId")||`(index ${g})`,v=w(m,"FromNodeId","fromNodeId"),x=w(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(Tx),h=i.filter(oR);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=Ro(m),y=da(m)||g;if(!g)return;let v=u.get(g)||[],x=p.get(g)||[];!Tx(m)&&x.length===0&&r.push(`\u8282\u70B9 ${y} \u6CA1\u6709\u5165\u7EBF`),!oR(m)&&v.length===0&&r.push(`\u8282\u70B9 ${y} \u6CA1\u6709\u51FA\u7EBF`),v.length>1&&(w(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:Ro(m),name:da(m)})),endNodes:h.map(m=>({id:Ro(m),name:da(m)}))}}}function dW(t){let e=t.indexOf(rR);if(e<0)return null;let r=e+rR.length,n=t.indexOf(MK,r);if(n<0)return null;try{return ee(JSON.parse(t.slice(r,n).trim()))}catch{return null}}function sR(t){return t==null||String(t).trim()===""}function cR(t,e){let r=w(t,"field","Field"),n=w(t,"operator","Operator")||"eq",i=ct(t,"value","Value"),a=r?e[r]:void 0,o=a==null?"":String(a),s=i==null?"":String(i);if(n==="empty")return sR(a);if(n==="notEmpty")return!sR(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 fW(t){let e=ee(t.workflow),r=ee(t.formData),n=w(t,"lineValueV8Code","LineValueV8","code");if(!n&&Object.keys(e).length>0){let{nodes:s}=Ox(e),c=w(t,"nodeId","NodeId"),l=(c?s.find(u=>Ro(u)===c):s.find(Tx)||s[0])||{};n=w(l,"LineValueV8","lineValueV8","V8Code","v8Code")}let i=dW(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=>!!ct(s,"isDefault","IsDefault"))||null;for(let s of a){if(s===o)continue;let c=ce(s,"rules","Rules").filter(u=>w(u,"field","Field"));if(c.length===0)continue;if(w(s,"match","Match")==="any"?c.some(u=>cR(u,r)):c.every(u=>cR(u,r)))return{ok:!0,selectedRoute:s,assignment:lR(s),source:"matched"}}return{ok:!!o,selectedRoute:o,assignment:o?lR(o):null,source:o?"default":"none"}}function lR(t){let e=w(t,"lineValue","LineValue"),r=w(t,"toNodeId","ToNodeId");return e?{LineValue:e}:{NextNodeId:r}}function mW(t,e){let{flow:r,nodes:n,lines:i}=Ox(t),a={...r},o=w(r,"table","tableName","TableName","diyTableName","DiyTableName");if(!w(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=Ro(u)||`wf_node_${p+1}_${xx().slice(0,8)}`,h={...u,Id:d},m=da(h);return m&&s.set(d,m),h}),l=i.map((u,p)=>{let d=w(u,"FromNodeId","fromNodeId"),h=w(u,"ToNodeId","toNodeId"),m=w(u,"LineName","lineName")||`${s.get(d)||d||"\u5F53\u524D\u8282\u70B9"} \u5230 ${s.get(h)||h||"\u4E0B\u4E00\u8282\u70B9"}`;return{...u,Id:w(u,"Id","id","LineId","lineId")||`wf_line_${p+1}_${xx().slice(0,8)}`,LineName:m}});return{FlowDesign:a,Nodes:c,Lines:l}}async function xr(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 uR(t,e){let r=w(e,"apiEngineKey","ApiEngineKey"),n=w(e,"apiName","ApiName","name","Name")||r,i=w(e,"category","Category")||"AI\u751F\u6210",a=ct(e,"code","Code","ApiV8Code"),o=typeof a=="string",s=o?String(a):"",c=Lc(e),l=await t.getEngineCode(r);return l.Code===1?!o&&c!==void 0?t.updateEngineRuntimeLimit(r,c):o?t.saveEngineCode(r,s,{functionDescription:w(e,"functionDescription","FunctionDescription")||void 0,changeSummary:w(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:w(e,"functionDescription","FunctionDescription")||void 0,changeSummary:w(e,"changeSummary","ChangeSummary")||void 0})}function hW(t,e,r,n){let i=w(t,"table","tableName","diyTableName","DiyTableName"),a=No(t);if(a.errors.length)throw new Error(a.errors.join(`
|
|
130
130
|
`));let o=w(t,"diyTableId","DiyTableId")||(i?e.get(i.toLowerCase()):""),s=i||w(t,"DiyTableName","diyTableName"),c=n?lW(t,n,o||"",s):{},l=ie(t,"display","Display")??1,u=ie(t,"appDisplay","AppDisplay")??1,p=w(t,"openType","OpenType")||"Diy",d=a.data.ViewSchema;if(!d&&n&&o&&(l===1||u===1)&&Yt(p)==="diy"){let m=Oo(n,o).length?Oo(n,o):Oo(n,s);if(m.length){let g=$x(w(t,"name","Name"),m,m[0]?.tableDescription||s),y=vd(g);if(!y.ok)throw new Error(y.errors.join(`
|
|
131
131
|
`));d=y.value}}return zr({...a.data,...c,Name:w(t,"name","Name"),DiyTableId:o,ParentId:w(t,"parentId","ParentId")||(r?r.get(w(t,"parentName","ParentName").toLowerCase()):void 0),ComponentName:w(t,"componentName","ComponentName"),ComponentPath:w(t,"componentPath","ComponentPath"),Display:l,AppDisplay:u,HasChild:ie(t,"hasChild","HasChild"),OpenType:p,Url:w(t,"url","Url"),Sort:ie(t,"sort","Sort"),Icon:w(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:w(t,"sqlWhere","SqlWhere"),SqlJoin:w(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:w(t,"menuBadgeApiEngineKey","MenuBadgeApiEngineKey"),EnableViewSchema:ie(t,"enableViewSchema","EnableViewSchema")??0,ViewSchemaVersion:w(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:w(t,"microServiceId","MicroServiceId"),MicroServicePageId:w(t,"microServicePageId","MicroServicePageId"),MicroServiceRoutePath:w(t,"microServiceRoutePath","MicroServiceRoutePath"),MicroServiceKey:w(t,"microServiceKey","MicroServiceKey")})}function gW(t){let e=w(t,"formOpenType","FormOpenType"),r=w(t,"formOpenWidth","FormOpenWidth");if(e)return{type:e,width:r||"80%"};let i=ce(t,"fields","Fields").filter(c=>!Rx.has(kt(c))),a=i.filter(c=>kt(c)==="tablechild").length,o=i.filter(c=>["tablechild","richtext","codeeditor","jsontable","imgupload","fileupload","map","maparea","devcomponent"].includes(kt(c))).length;return{type:i.length>=36||a>=2||i.length>=28&&a>=1||o>=7?"Drawer":"Dialog",width:r||"80%"}}function yW(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 Nx(t){let e=ct(t,"relation","Relation");if(!e||typeof e!="object"||Array.isArray(e))return;let r=ee(e);return{cardinality:yW(w(r,"cardinality","Cardinality")),targetTable:w(r,"targetTable","TargetTable","table","Table"),joinFieldName:w(r,"joinFieldName","JoinFieldName","foreignKey","ForeignKey"),childForeignKey:w(r,"childForeignKey","ChildForeignKey","foreignKey","ForeignKey"),childModule:w(r,"childModule","ChildModule","module","Module"),primaryTableFieldName:w(r,"primaryTableFieldName","PrimaryTableFieldName")||"Id"}}var bW=new Set(["collapsegroup","tabs","divider","empty","alert","statictext","html","button"]),Px=new Set(["select","multipleselect","radio","checkbox","switch","cascader","selecttree","department"]),vW=new Set(["numbertext","slider","rate","progress"]);function ER(t){return`${w(t,"name","Name")} ${w(t,"label","Label")} ${w(t,"description","Description")}`.toLowerCase()}function hd(t,e,r){let n=ER(t),i=e.findIndex(a=>n.includes(a));return i>=0?100-i:r}function Ax(t){return Px.has(kt(t))?!1:vW.has(kt(t))?!0:/^(tinyint|smallint|mediumint|int|bigint|decimal|numeric|float|double|real)(\b|\()/iu.test(w(t,"type","Type"))}function xW(t){if(!Ax(t))return!1;let e=ER(t);return/(^|\s|_)(id|ids)(\s|_|$)|sort|order|latitude|longitude|phone|mobile|enabled?|disabled?|visible|deleted|status|state|type|category|version|timeout|retry|limit|pagesize|page size|offset|loaded|load count|record count|data count|排序|经度|纬度|电话|手机|启用|禁用|显示|删除|状态|类型|分类|版本|超时|重试|限制|分页|本页|加载|记录数/iu.test(e)?!1:me(e,["amount","money","price","total","count","quantity","number","score","rate","progress","budget","cost","fee","tax","discount","income","expense","balance","point","weight","volume","area","duration","hour","day","\u91D1\u989D","\u603B\u989D","\u4EF7\u683C","\u6570\u91CF","\u4E2A\u6570","\u79EF\u5206","\u6BD4\u4F8B","\u8FDB\u5EA6","\u4F59\u989D","\u9884\u7B97","\u6210\u672C","\u8D39\u7528","\u7A0E\u989D","\u6298\u6263","\u6536\u5165","\u652F\u51FA","\u91CD\u91CF","\u4F53\u79EF","\u9762\u79EF","\u65F6\u957F","\u5DE5\u65F6","\u5929\u6570","\u8BC4\u5206","\u5B8C\u6210\u5EA6"])}function bd(t){return Array.isArray(t)?t:typeof t!="string"||!t.trim()?[]:yR(t)}function _d(t){let e=ce(t,"fields","Fields").filter(g=>{let y=w(g,"name","Name"),v=ie(g,"visible","Visible");return!!y&&v!==0&&!Fc(y)&&!bW.has(kt(g))}),r=ct(t,"formBanner","FormBanner"),n=ee(r),i=g=>e.map((y,v)=>({field:y,index:v,score:g(y,v)})).filter(y=>y.score>0).sort((y,v)=>v.score-y.score||y.index-v.index).map(y=>y.field),a=w(n,"titleField","TitleField")||w(i((g,y)=>{let v=hd(g,["title","name","subject","code","no","number","\u6807\u9898","\u540D\u79F0","\u4E3B\u9898","\u7F16\u53F7","\u5355\u53F7","\u7F16\u7801"],20-y);return kt(g)==="autonumber"?v+=50:kt(g)==="text"&&(v+=20),(Px.has(kt(g))||Ax(g))&&(v-=80),v})[0]||{},"name","Name"),o=w(n,"subtitleField","SubtitleField")||w(i((g,y)=>w(g,"name","Name")===a||Ax(g)||kt(g)==="imgupload"?0:hd(g,["subtitle","customer","client","project","company","category","type","date","contact","\u526F\u6807\u9898","\u5BA2\u6237","\u9879\u76EE","\u516C\u53F8","\u5355\u4F4D","\u5206\u7C7B","\u7C7B\u578B","\u65E5\u671F","\u8054\u7CFB\u4EBA","\u8BF4\u660E"],12-y)+(["text","select","radio","datetime","department","selecttree"].includes(kt(g))?18:0))[0]||{},"name","Name"),s=w(n,"imageField","ImageField")||w(e.find(g=>["imgupload","imageupload"].includes(kt(g)))||{},"name","Name"),c=ct(n,"tagFields","TagFields","tags","Tags"),l=c!==void 0?bd(c):i((g,y)=>Px.has(kt(g))?hd(g,["status","state","stage","type","category","level","\u72B6\u6001","\u9636\u6BB5","\u7C7B\u578B","\u5206\u7C7B","\u7EA7\u522B"],30-y):0).slice(0,3).map(g=>({Key:w(g,"name","Name"),Field:w(g,"name","Name"),Label:w(g,"label","Label")||w(g,"name","Name")})),u=ct(n,"metrics","Metrics"),p=u!==void 0?bd(u):i(g=>xW(g)?hd(g,["amount","money","price","total","count","quantity","number","score","rate","progress","budget","cost","fee","tax","discount","income","expense","balance","point","weight","\u91D1\u989D","\u603B\u989D","\u4EF7\u683C","\u6570\u91CF","\u4E2A\u6570","\u79EF\u5206","\u6BD4\u4F8B","\u8FDB\u5EA6","\u4F59\u989D","\u9884\u7B97","\u6210\u672C","\u8D39\u7528"],0):0).slice(0,3).map(g=>({Key:w(g,"name","Name"),Field:w(g,"name","Name"),Label:w(g,"label","Label")||w(g,"name","Name"),Auto:!0})),h={FormBannerEnabled:Er(n,"enabled","Enabled")===!1?0:1,FormBannerTitleField:a,FormBannerSubtitleField:o,FormBannerImageField:s,FormBannerIcon:w(n,"icon","Icon")||"far fa-file-alt",FormBannerBackgroundField:w(n,"backgroundField","BackgroundField"),FormBannerTagFields:JSON.stringify(l)},m=e.some(g=>kt(g)==="tablechild"||Nx(g)?.cardinality==="1:N");return(u!==void 0||p.length>0||!m)&&(h.FormBannerMetrics=JSON.stringify(p)),h}function wW(t){if(typeof t=="string"){if(!t.trim())return{};try{return ee(JSON.parse(t))}catch{return{}}}return ee(t)}function _W(t){return w(t,"table","tableName","diyTableName","DiyTableName")}function SW(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=w(s,"name","Name");c&&a.set($e(c),s)}for(let s of i){let c=w(s,"name","Name");c&&o.set($e(c),s)}return n.forEach((s,c)=>{let l=w(s,"name","Name"),u=ce(s,"fields","Fields"),p=new Set(u.map(d=>$e(w(d,"name","Name"))).filter(Boolean));u.forEach((d,h)=>{let m=$e(w(d,"component","Component"));if(m!=="joinform"&&m!=="tablechild")return;let g=`tables[${c}].fields[${h}]`,y=w(d,"name","Name"),v=Nx(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}$e(v.targetTable)===$e(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($e(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($e(v.joinFieldName))?$e(v.joinFieldName)===$e(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"),_=new Set(b.map(S=>$e(w(S,"name","Name"))).filter(Boolean));if(v.childForeignKey?_.has($e(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 S=o.get($e(v.childModule));S?($e(_W(S))!==$e(v.targetTable)&&e.push(`${g}.relation.childModule \u5FC5\u987B\u7ED1\u5B9A\u5B50\u8868 ${v.targetTable}`),(ie(S,"display","Display")!==0||ie(S,"appDisplay","AppDisplay")!==0||ie(S,"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(S=>{let T=$o(S,"columns","Columns").map($e);return T.length>=2&&T[0]==="osclient"&&T[1]===$e(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 EW(t,e,r,n){let i=$e(w(t,"component","Component")),a=Nx(t);if(!a||i!=="joinform"&&i!=="tablechild")throw new Error(`${e}.${w(t,"name","Name")} \u7F3A\u5C11\u6709\u6548 relation`);let o=r.get($e(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=wW(ct(t,"config","Config"));if(i==="joinform")return{...s,JoinForm:{...ee(s.JoinForm),TableId:o,TableName:a.targetTable,JoinFieldName:a.joinFieldName}};let c=n.get($e(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 Ix(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 kW(t,e){let r=w(e,"openType","OpenType"),n=w(e,"microServiceKey","MicroServiceKey"),i=w(e,"microServiceRoutePath","MicroServiceRoutePath"),a=w(e,"microServiceId","MicroServiceId"),o=w(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=Ix(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=w(p,"Id","id"),h=w(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=w(x,"RoutePath","routePath","Path","path");if(!b)return!1;try{return Ix(b)===c}catch{return!1}}),y=g?w(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:w(e,"componentName","ComponentName")||"MicroService",ComponentPath:w(e,"componentPath","ComponentPath")||"/micro-app/host",Url:w(e,"url","Url")||`/micro-app/${encodeURIComponent(n)}${v}`,MicroServiceId:d,MicroServicePageId:y,MicroServiceRoutePath:c,MicroServiceKey:n}}function pR(t){return zr({...t,Id:w(t,"Id","roleId","RoleId")||void 0,Name:w(t,"Name","name"),Level:ie(t,"Level","level"),Sort:ie(t,"Sort","sort"),Remark:w(t,"Remark","remark","description"),DeptIds:w(t,"DeptIds","deptIds"),BaseLimit:w(t,"BaseLimit","baseLimit")})}function dR(t){return zr({...t,Id:w(t,"Id","dataSourceId","DataSourceId")||void 0,DataSourceName:w(t,"DataSourceName","dataSourceName","name","Name"),DataSourceKey:w(t,"DataSourceKey","dataSourceKey"),DataSourceType:w(t,"DataSourceType","dataSourceType")||"V8",SqlDataSource:w(t,"SqlDataSource","sqlDataSource","sql"),V8DataSource:w(t,"V8DataSource","v8DataSource","code"),JsonDataSource:zc(t.JsonDataSource??t.jsonDataSource??t.json),TestParam:zc(t.TestParam??t.testParam),DataSourceRole:w(t,"DataSourceRole","dataSourceRole"),AllowAnonymous:ie(t,"AllowAnonymous","allowAnonymous"),IsEnable:ie(t,"IsEnable","isEnable")??1})}function fR(t){let e=la(t.PageObj??t.pageObj);if(!e.ok||!e.json)throw new Error(`printTemplates.${w(t,"Title","title")||"(untitled)"} PageObj invalid: ${e.errors.join("; ")}`);let r=ua(t.PrintObj??t.printObj);if(!r.ok||!r.json)throw new Error(`printTemplates.${w(t,"Title","title")||"(untitled)"} PrintObj invalid: ${r.errors.join("; ")}`);return zr({...t,Id:w(t,"Id","printId","PrintId")||void 0,Title:w(t,"Title","title"),Number:w(t,"Number","number"),Desc:w(t,"Desc","desc","description"),DataApi:w(t,"DataApi","dataApi"),PageObj:e.json,PrintObj:r.json})}function mR(t){return zr({...t,Id:w(t,"Id","jobId","JobId")||void 0,JobName:w(t,"JobName","jobName","name","Name"),CronExpression:w(t,"CronExpression","cronExpression","cron"),JobType:w(t,"JobType","jobType")||"1",ApiEngineKey:w(t,"ApiEngineKey","apiEngineKey"),JobParam:zc(t.JobParam??t.jobParam??t.params),JobDesc:w(t,"JobDesc","jobDesc","description"),CronDesc:w(t,"CronDesc","cronDesc"),DllName:w(t,"DllName","dllName"),JobPath:w(t,"JobPath","jobPath")})}function kR(t){let e=$e(w(t,"component","Component"));return e==="joinform"||e==="tablechild"}function hR(t,e,r,n,i){let a=ee(e.configSource??e.ConfigSource),o=w(a,"sourceType")?xR(w(a,"sourceType"),a):void 0;return zr({TableId:r,Name:w(e,"name","Name"),Label:w(e,"label","Label"),Type:w(e,"type","Type")||(kR(e)?"mediumtext":""),Component:w(e,"component","Component"),Visible:ie(e,"visible","Visible")??1,AppVisible:ie(e,"appVisible","AppVisible")??1,Tab:w(e,"tab","Tab")||n.fieldTabs.get(w(e,"name","Name")),TableWidth:ie(e,"tableWidth","TableWidth")??wd(e),Sort:ie(e,"sort","Sort"),Readonly:ie(e,"readonly","Readonly"),NotEmpty:ie(e,"notEmpty","NotEmpty"),Unique:ie(e,"unique","Unique"),DefaultValue:w(e,"defaultValue","DefaultValue"),Placeholder:w(e,"placeholder","Placeholder"),FormWidth:ie(e,"formWidth","FormWidth"),Data:o?.data??w(e,"data","Data"),Config:i!==void 0?JSON.stringify(i):o?JSON.stringify(o.config):zc(e.config??e.Config),Description:w(e,"description","Description"),Encrypt:ie(e,"encrypt","Encrypt"),InTableEdit:ie(e,"inTableEdit","InTableEdit")})}function TW(t){return{osClient:t,workflow:["Call microi_get_db_schema first to inspect existing tables.","Call microi_get_manifest_schema to draft a manifest from the user requirement.","Call microi_plan_system with the manifest and fix all errors.","Call microi_generate_system with dryRun=true.",`Call microi_generate_system with dryRun=false and confirmExecution="${t||"EXECUTE"}" only after the user confirms writes.`,"Call microi_validate_system after generation if you need an independent validation pass."],manifestShape:{name:"System name",roles:[{name:"Admin",level:999}],tables:[{name:"Biz_Order",description:"Order main table",v8Limit:!1,tabs:[{Id:"basic",Name:"Basic Info",Sort:10},{Id:"business",Name:"Business Info",Sort:20}],formBanner:{enabled:!0,titleField:"OrderNo",subtitleField:"CustomerName",imageField:"",icon:"far fa-file-alt",backgroundField:"",tagFields:[{Field:"Status",Label:"Status"}],metrics:[{Field:"Amount",Label:"Order Amount",Prefix:"\xA5",Icon:"fas fa-coins"},{Key:"Pending",Label:"Pending",ApiEngineKey:"biz_order_metrics",ValuePath:"Data.Pending",RefreshSeconds:30}]},fields:[{name:"OrderNo",label:"Order No",type:"varchar(50)",component:"AutoNumber",tab:"basic",configSource:{sourceType:"AutoNumber",prefix:"ORD",length:6},notEmpty:1,unique:1,tableWidth:160,sort:10},{name:"CustomerName",label:"Customer",type:"varchar(100)",component:"Text",tab:"basic",notEmpty:1,tableWidth:160,sort:20},{name:"OwnerName",label:"Owner",type:"varchar(100)",component:"Text",tab:"basic",tableWidth:150,sort:30},{name:"Amount",label:"Order Amount",type:"decimal(18,2)",component:"NumberText",tab:"business",tableWidth:140,sort:40},{name:"Status",label:"Status",type:"varchar(50)",component:"Select",tab:"business",configSource:{sourceType:"KeyValue",items:[{Key:"Draft",Value:"Draft"},{Key:"Submitted",Value:"Submitted"}]},tableWidth:130,sort:50}],indexes:[{name:"uk_biz_order_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.",formBanner:"Semantic diy_table Banner configuration. Configure enabled/titleField/subtitleField/imageField/icon/backgroundField/tagFields/metrics here, never in sys_menu. The default Banner uses a compact theme-colored dark gradient. When omitted, generator writes useful type-aware defaults: title/name/code, customer/project subtitle, first ImgUpload, up to 3 option tags and up to 3 business-semantic metrics. Id/sort/enabled/status/version/page-load numbers are never metrics. A TableChild form may leave metrics unset so runtime performs authorized full-child count/SUM inference. Metrics may also use ApiEngineKey + ValuePath + ParamMap + RefreshSeconds.",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.",v8Limit:"Default false. Missing/null/false means no per-execution Jint budgets; true enables timeout, statement, recursion and allocation limits for this table's backend V8 events. Legacy v8Unlimited is accepted only as an inverted compatibility alias."},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.","Every generated business table must have a useful compact theme-colored dark-gradient form Banner. Put its configuration in tables[].formBanner/diy_table, not in modules/sys_menu. Prefer a business number/name title, a customer/project subtitle, real option tags and at most 3 business-semantic current-record or authorized full-child metrics; exclude technical numbers and never fabricate statistics.","JoinForm 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 TR(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()=>X(JSON.stringify(TW(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=No(s);return X(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:Dt.optional().describe("Source options, such as data/options, sql, apiEngineKey, dataSourceId, tableId, prefix, length")},async({sourceType:s,options:c})=>{let l=xR(s,c||{});return X(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:Dt.describe("System manifest with tables, engines, modules, permissions, pages, dataSources, printTemplates, workflows, jobs")},async({manifest:s})=>{let c=vx(s);return X(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:Dt.describe("Workflow package with FlowDesign, Nodes and Lines")},async({workflow:s})=>{let c=Cx(s);return X(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:Dt.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:Dt.optional().describe("Sample business form data used for rule evaluation")},async s=>X(JSON.stringify(fW(s),null,2))),t.tool("microi_validate_system",`Validate that a generated low-code system exists on Microi server after generation. OsClient: ${n}`,{manifest:Dt.describe("The same manifest used by microi_generate_system")},async({manifest:s})=>{try{let c=vx(s);if(c.errors.length>0)return X(JSON.stringify({ok:!1,failedAt:"manifestPreflight",errors:c.errors,warnings:c.warnings},null,2),!0);let l=await e.validateLowCodeSystem(s);return yt("Low-Code System Validation",l)}catch(c){return X(`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:Dt.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=vx(s);if(u.errors.length>0)return X(JSON.stringify({ok:!1,...u},null,2),!0);if(c)return X(JSON.stringify({ok:!0,dryRun:!0,...u},null,2));if(l!==i)return X(`\u5199\u5165\u5DF2\u62E6\u622A\uFF1A\u8BF7\u91CD\u65B0\u8C03\u7528\u5E76\u4F20 confirmExecution="${i}"\u3002
|