@microi.net/cli 5.6.4 → 5.6.6
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 +5 -5
- package/cordis.patch.yml +1 -1
- package/package.json +1 -1
- package/scripts/mcp-server.js +1 -1
- package/scripts/microi-cli.js +11 -11
- package/scripts/microi-skills.meta.json +196 -196
- package/skills/.microi-skills-version.json +2 -2
- package/skills/.progressive-disclosure-manifest.json +17 -17
- package/skills/microi-client-frontend/SKILL.md +12 -4
- package/skills/microi-deployment/SKILL.md +11 -0
- package/skills/v8-security/SKILL.md +2 -2
- package/skills/v8-security/references/progressive-01-2-/346/235/203/351/231/220/346/240/241/351/252/214.md +5 -4
package/scripts/mcp-server.js
CHANGED
|
@@ -123,7 +123,7 @@ Content-Type: application/octet-stream\r
|
|
|
123
123
|
`,"utf8"));let a=Buffer.concat(o),s=Buffer.from(`\r
|
|
124
124
|
--${n}--\r
|
|
125
125
|
`,"utf8"),c=At.default.statSync(e).size;async function*l(){yield a;let u=At.default.createReadStream(e),p=i==="gzip"?u.pipe((0,oI.createGzip)()):u;for await(let f of p)yield Buffer.isBuffer(f)?f:Buffer.from(f);yield s}return{body:iI.Readable.from(l()),contentLength:a.length+c+s.length}}async function bB(t,e,r){let n=zn.default.createHash("sha256");if(r>0){let i=At.default.createReadStream(t,{start:e,end:e+r-1});for await(let o of i)n.update(o)}return n.digest("hex")}function vB(t){return t.ProtocolVersion!==3?{}:{ProtocolVersion:3,PublishMode:"stage",ExpectedGateEpoch:String(t.ExpectedGateEpoch??""),RequestFingerprint:String(t.RequestFingerprint??""),DeliveryBatchId:String(t.DeliveryBatchId??""),SourceManifestHash:String(t.SourceManifestHash??""),RuntimeManifestHash:String(t.RuntimeManifestHash??""),RouteSnapshotJson:String(t.RouteSnapshotJson??""),RouteSnapshotHash:String(t.RouteSnapshotHash??""),ExpectedCurrentVersion:Number(t.ExpectedCurrentVersion),ExpectedAppVersion:t.ExpectedAppVersion??null,ExpectedPublishFence:String(t.ExpectedPublishFence??""),ExpectedPublishRowVersion:String(t.ExpectedPublishRowVersion??""),ExpectedVersionRowVersion:t.ExpectedVersionRowVersion??null,ExpectedActivePublishVersionId:t.ExpectedActivePublishVersionId??null,ExpectedCommittedPublishVersionId:t.ExpectedCommittedPublishVersionId??null}}function hi(t){return String(t??"").replace(/\r\n/g,`
|
|
126
|
-
`).trim()}function Nb(t){return t?.V8Limit!==void 0&&t.V8Limit!==null?Number(t.V8Limit)===1?1:0:t?.V8Unlimited!==void 0&&t.V8Unlimited!==null?Number(t.V8Unlimited)===1?0:1:0}function Up(t){if(t===void 0)return;let e=(Array.isArray(t)?t:String(t).split(";")).map(r=>String(r||"").trim()).filter(Boolean);return Array.from(new Set(e.map(r=>r.toLowerCase()))).map(r=>e.find(n=>n.toLowerCase()===r)||r).join(";")}function Db(t){if(Array.isArray(t))return t.map(Db);if(!t||typeof t!="object")return t;let e=Object.entries(t).filter(([r])=>!r.startsWith("_")).sort(([r],[n])=>r.localeCompare(n));return Object.fromEntries(e.map(([r,n])=>[r,Db(n)]))}function rI(t){try{let e=typeof t=="string"?JSON.parse(t):t;return JSON.stringify(Db(e))}catch{return}}function xB(t,e){let r=new Set(["OsClient","ModuleId","Id"]),n=[];for(let[i,o]of Object.entries(t)){if(r.has(i)||o===void 0)continue;let a=e[i];if(yB.has(i)||i==="ViewSchema"){let s=rI(o),c=rI(a);(!s||!c||s!==c)&&n.push(i);continue}String(o??"")!==String(a??"")&&n.push(i)}return{matched:n.length===0,mismatches:n}}var Dc=class{config;token="";refreshTimer;rsaPublicKey;did;requestTimeoutMs;writeRequestTimeoutMs;readbackRequestTimeoutMs;inflightRefresh;inflightAuthRecovery;inflightCredentialRecovery;constructor(e){this.config=e,this.reloadWorkspaceCredentials(),this.rsaPublicKey=e.rsaPublicKey||aB,this.did=LA(process.env.MICROI_MCP_DID,nI.default.hostname()),this.requestTimeoutMs=Bp(e.requestTimeoutMs??process.env.MICROI_MCP_HTTP_TIMEOUT_MS,lB),this.writeRequestTimeoutMs=Bp(e.writeRequestTimeoutMs??process.env.MICROI_MCP_WRITE_TIMEOUT_MS,uB),this.readbackRequestTimeoutMs=Bp(e.readbackRequestTimeoutMs??process.env.MICROI_MCP_READBACK_TIMEOUT_MS,pB),e.token&&(this.token=vr(e.token))}rsaEncrypt(e){let r=(this.rsaPublicKey||"").trim();return r?zn.default.publicEncrypt({key:r,padding:zn.default.constants.RSA_PKCS1_PADDING},Buffer.from(e,"utf-8")).toString("base64"):e}updateToken(e){this.token=vr(e)}async login(e){if(this.token){this.startAutoRefresh(),console.error("[microi-mcp] Using provided token (auto-refresh enabled)");return}if(this.reloadWorkspaceCredentials(),!this.config.username||!this.config.password)throw new Error("Login credentials are unavailable from environment or workspace protected storage");let r=this.rsaEncrypt(this.config.password),n=new URLSearchParams;n.append("Account",this.config.username),n.append("Pwd",r),this.config.osClient&&n.append("OsClient",this.config.osClient),n.append("_ClientType","MCP");let i=await fetch(`${this.config.apiBaseUrl}${O.LOGIN}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{}},body:n.toString()}),o=i.headers.get("authorization")||"",a=await i.text();if(!i.ok||!a)throw new Error(`Login failed: HTTP ${i.status} \u2014 ${a?.slice(0,200)||"empty response"}`);let s;try{s=JSON.parse(a)}catch{throw new Error(`Login failed: invalid JSON \u2014 ${a.slice(0,200)}`)}if(s.Code!==1)throw new Error(`Login failed: ${s.Msg||"Unknown error"}`);if(!o)throw new Error("Login succeeded but no token in response header");this.token=vr(o),this.startAutoRefresh(),console.error("[microi-mcp] Login successful")}startAutoRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{qA(this.token)&&this.refreshTokenNow().catch(e=>console.error("[microi-mcp] Token refresh failed:",e))},60*60*1e3)}async refreshTokenNow(){return this.inflightRefresh?this.inflightRefresh:this.token?(this.inflightRefresh=(async()=>{try{let e=await fetch(`${this.config.apiBaseUrl}${O.REFRESH_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{}},body:JSON.stringify({authorization:this.token,OsClient:this.config.osClient||void 0,_ClientType:"MCP"})}),r=e.headers.get("authorization"),n=await e.text(),i=null;try{i=JSON.parse(n)}catch{}return r&&i?.Code===1?(this.token=vr(r),this.writeTokenToFile(),console.error("[microi-mcp] Token refreshed"),!0):(console.error(`[microi-mcp] Refresh rejected: Code=${i?.Code} Msg=${i?.Msg||""}`),!1)}catch(e){return console.error("[microi-mcp] Refresh request error:",e),!1}finally{this.inflightRefresh=void 0}})(),this.inflightRefresh):!1}reloadTokenFromFile(){let e=this.config.tokenFilePath;if(!e)return!1;try{let r=JSON.parse(At.default.readFileSync(e,"utf-8")),n=Zp(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork),i=String(this.config.apiBaseUrl||"").replace(/\/+$/,""),o=this.config.osClient?n.filter(c=>c!==i):n,a=Lp(o.map(c=>Ra(r[c])))||Ra(r[i]),s=vr(a);if(s&&s!==this.token)return this.token=s,!0}catch{}return!1}writeTokenToFile(){let e=this.config.tokenFilePath;if(!(!e||!this.token))try{let r={};try{r=JSON.parse(At.default.readFileSync(e,"utf-8"))}catch{}let[n]=Zp(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork);if(!n)return;r[n]=Object.values(r).some(Vp)?YA(this.token):this.token;let i=Oa.default.dirname(e);At.default.existsSync(i)||At.default.mkdirSync(i,{recursive:!0}),At.default.writeFileSync(e,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}catch(r){console.error("[microi-mcp] Write token file failed:",r)}}async requestVsCodeCredentialRecovery(e){let r=this.config.authRecoveryRequestDir,n=this.config.tokenFilePath;if(!r||!n)return!1;try{At.default.existsSync(r)||At.default.mkdirSync(r,{recursive:!0});let i=this.config.apiBaseUrl.replace(/\/+$/,""),o=this.config.osClient||"",a=this.config.osClientType||"",s=this.config.osClientNetwork||"",c=`${i}|${o}|${a}|${s}`,u=`${zn.default.createHash("sha256").update(c).digest("hex").slice(0,24)}-${process.pid}-${Date.now()}-${zn.default.randomBytes(4).toString("hex")}.json`,p=Oa.default.join(r,u),f=`${p}.${process.pid}.tmp`,h={version:1,apiBaseUrl:i,osClient:o,osClientType:a,osClientNetwork:s,requestedAt:Date.now(),failedTokenHash:zn.default.createHash("sha256").update(e||"").digest("hex")};At.default.writeFileSync(f,JSON.stringify(h),{encoding:"utf-8",mode:384}),At.default.renameSync(f,p);for(let m=0;m<40;m++)if(await new Promise(g=>setTimeout(g,250)),this.reloadTokenFromFile())return console.error("[microi-mcp] Token recovered by VS Code SecretStorage broker"),!0}catch(i){console.error("[microi-mcp] VS Code credential recovery request failed:",i)}return!1}async tryRecoverFromAuthFailure(e,r=!1){if(this.token&&e&&this.token!==e)return!0;if(r){if(this.inflightCredentialRecovery)return this.inflightCredentialRecovery;let n=this.inflightAuthRecovery;this.inflightCredentialRecovery=(async()=>(n&&await n,this.token&&e&&this.token!==e?!0:this.tryRecoverFromAuthFailureCore(e,!0)))();try{return await this.inflightCredentialRecovery}finally{this.inflightCredentialRecovery=void 0}}if(this.inflightCredentialRecovery)return this.inflightCredentialRecovery;if(this.inflightAuthRecovery)return this.inflightAuthRecovery;this.inflightAuthRecovery=this.tryRecoverFromAuthFailureCore(e,!1);try{return await this.inflightAuthRecovery}finally{this.inflightAuthRecovery=void 0}}async tryRecoverFromAuthFailureCore(e,r){if(this.token&&e&&this.token!==e)return!0;if(this.reloadTokenFromFile())return console.error("[microi-mcp] Token reloaded from file after auth failure"),!0;if(!r&&await this.refreshTokenNow())return!0;if(this.reloadWorkspaceCredentials(),this.config.username&&this.config.password)try{if(this.token="",await this.login(),this.token&&this.token!==e)return this.writeTokenToFile(),console.error("[microi-mcp] Re-logged in after auth failure"),!0}catch(n){this.token=e,console.error("[microi-mcp] Re-login failed:",n)}return this.requestVsCodeCredentialRecovery(e)}reloadWorkspaceCredentials(){let e=QA({filePath:this.config.workspaceCredentialFilePath,usernameKey:this.config.workspaceCredentialUsernameKey,passwordKey:this.config.workspaceCredentialPasswordKey});return e?(this.config.username=e.username,this.config.password=e.password,!0):!1}async post(e,r,n={}){return this.requestJson("POST",e,r,void 0,"initial",n)}async get(e,r,n={}){return this.requestJson("GET",e,void 0,r,"initial",n)}async requestJson(e,r,n,i,o="initial",a={}){let s=`${this.config.apiBaseUrl}${r}`;if(e==="GET"&&i){let b=new URLSearchParams(i).toString();b&&(s+=`?${b}`)}let c=this.token,l={Authorization:`Bearer ${c}`,did:this.did};this.config.osClient&&(l.OsClient=this.config.osClient),e==="POST"&&(l["Content-Type"]="application/json");let u=Bp(a.timeoutMs,this.requestTimeoutMs,a.maxTimeoutMs),p=a.operationName||`${e} ${r}`,f=new AbortController,h=setTimeout(()=>f.abort(),u),m,g,y=e==="POST"?JSON.stringify(n??{}):void 0;try{let b=await fetch(s,{method:e,headers:l,signal:f.signal,...y!==void 0?{body:y}:{}});m=b,g=await b.text()}catch(b){if(f.signal.aborted)throw new yn(`${p} \u8BF7\u6C42\u8D85\u65F6\uFF08${u}ms\uFF09`,{kind:"timeout",requestPath:r,uncertainOutcome:e==="POST",cause:b});if(a.allowNativeFallback===!1)throw new yn(`${p} \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1Afetch=${b instanceof Error?b.message:String(b)}\uFF1B\u5DF2\u7981\u7528\u975E\u5E42\u7B49\u4F20\u8F93\u91CD\u653E`,{kind:"network",requestPath:r,uncertainOutcome:e==="POST",cause:b});try{await new Promise(S=>setTimeout(S,250));let E=await this.requestJsonNative(e,s,l,y,u);m=E.res,g=E.text}catch(E){let S=b instanceof Error?b.message:String(b),k=E instanceof Error?E.message:String(E);throw new yn(`${p} \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1Afetch=${S}\uFF1Bnative=${k}`,{kind:"network",requestPath:r,uncertainOutcome:e==="POST",cause:E})}}finally{clearTimeout(h)}let v=m.headers.get("authorization");if(v&&(this.token=vr(v),this.writeTokenToFile()),m.status===401&&o!=="credential-token"){let b=o!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestJson(e,r,n,i,Pa(o),a);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${g.slice(0,200)}`)}if(!m.ok)throw new Error(`HTTP ${m.status} ${m.statusText} \u2014 ${g.slice(0,200)}`);if(!g)throw new Error(`HTTP ${m.status} \u2014 empty response body`);let x;try{x=JSON.parse(g)}catch{throw new Error(`HTTP ${m.status} \u2014 invalid JSON: ${g.slice(0,200)}`)}if(Ob(x)&&o!=="credential-token"){console.error(`[microi-mcp] Auth expired (Code=${x.Code}: ${x.Msg||""}), attempting recovery...`);let b=o!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestJson(e,r,n,i,Pa(o),a)}return x}async requestMultipartFile(e,r,n,i,o="initial",a,s,c=!0){let l=this.token,u=s==="gzip"?{...r,ContentEncoding:"gzip"}:r,p=`----microi-mcp-${zn.default.randomBytes(24).toString("hex")}`,f=tI(u,n,i,p,s),h=new AbortController,m=eI(a),g=setTimeout(()=>h.abort(),m),y,v;try{let w=await fetch(`${this.config.apiBaseUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${p}`,...s===void 0?{"Content-Length":String(f.contentLength)}:{}},body:f.body,duplex:"half",signal:h.signal});y=w,v=await w.text()}catch(w){if(h.signal.aborted)throw new yn(`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u8D85\u65F6\uFF08${m}ms\uFF09`,{kind:"timeout",requestPath:e,uncertainOutcome:!0,cause:w});try{await new Promise(k=>setTimeout(k,250));let S=await this.requestMultipartFileNative(e,u,n,i,m,s);y=S.res,v=S.text}catch(S){let k=w instanceof Error?w.message:String(w),A=S instanceof Error?S.message:String(S);if(c&&s!=="gzip")try{return await this.requestMultipartFile(e,r,n,i,o,a,"gzip",c)}catch(R){let I=R instanceof Error?R.message:String(R);throw new yn(`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1Afetch=${k}\uFF1Bnative=${A}\uFF1Bgzip=${I}`,{kind:"network",requestPath:e,uncertainOutcome:!0,cause:R})}throw new yn(`${s==="gzip"?"\u5E94\u7528\u8D44\u4EA7 gzip":"\u539F\u59CB\u6587\u4EF6"}\u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1Afetch=${k}\uFF1Bnative=${A}`,{kind:"network",requestPath:e,uncertainOutcome:!0,cause:S})}}finally{clearTimeout(g),f.body.destroy()}let x=y.headers.get("authorization");if(x&&(this.token=vr(x),this.writeTokenToFile()),y.status===401&&o!=="credential-token"){let w=o!=="initial";if(w&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(l,w))return this.requestMultipartFile(e,r,n,i,Pa(o),a,s,c);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${v.slice(0,200)}`)}if(!y.ok)throw new Error(`HTTP ${y.status} ${y.statusText} \u2014 ${v.slice(0,200)}`);if(!v)throw new Error(`HTTP ${y.status} \u2014 empty response body`);let b;try{b=JSON.parse(v)}catch{throw new Error(`HTTP ${y.status} \u2014 invalid JSON: ${v.slice(0,200)}`)}if(Ob(b)&&o!=="credential-token"){let w=o!=="initial";if(w&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(l,w))return this.requestMultipartFile(e,r,n,i,Pa(o),a,s,c)}return b}async requestJsonNative(e,r,n,i,o){let a=new URL(r),s=a.protocol==="https:"?Hp.default:Jp.default,c=i===void 0?void 0:Buffer.from(i,"utf8");return new Promise((l,u)=>{let p=!1,f=m=>{p||(p=!0,u(m))},h=s.request({protocol:a.protocol,hostname:a.hostname,port:a.port||void 0,path:`${a.pathname}${a.search}`,method:e,timeout:o,headers:{...n,...c?{"Content-Length":String(c.length)}:{}}},m=>{let g=[];m.on("data",y=>g.push(Buffer.isBuffer(y)?y:Buffer.from(y))),m.on("end",()=>{if(p)return;p=!0;let y=m.statusCode||0,v={get(x){let b=m.headers[x.toLowerCase()];return Array.isArray(b)?b.join(", "):b===void 0?null:String(b)}};l({res:{status:y,statusText:m.statusMessage||"",ok:y>=200&&y<300,headers:v},text:Buffer.concat(g).toString("utf8")})})});h.on("error",m=>f(new Error(m.message,{cause:m}))),h.on("timeout",()=>{h.destroy(),f(new Error(`native request timeout (${o}ms)`))}),c&&h.write(c),h.end()})}async requestMultipartFileNative(e,r,n,i,o,a){let s=`----microi-mcp-native-${zn.default.randomBytes(24).toString("hex")}`,c=tI(r,n,i,s,a),l=new URL(`${this.config.apiBaseUrl}${e}`),u=l.protocol==="https:"?Hp.default:Jp.default;try{return await new Promise((p,f)=>{let h=!1,m=y=>{h||(h=!0,f(y))},g=u.request({protocol:l.protocol,hostname:l.hostname,port:l.port||void 0,path:`${l.pathname}${l.search}`,method:"POST",timeout:o,headers:{Authorization:`Bearer ${this.token}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${s}`,...a===void 0?{"Content-Length":String(c.contentLength)}:{}}},y=>{let v=[];y.on("data",x=>v.push(Buffer.isBuffer(x)?x:Buffer.from(x))),y.on("end",()=>{if(h)return;h=!0;let x=y.statusCode||0,b={get(w){let E=y.headers[w.toLowerCase()];return Array.isArray(E)?E.join(", "):E===void 0?null:String(E)}};p({res:{status:x,statusText:y.statusMessage||"",ok:x>=200&&x<300,headers:b},text:Buffer.concat(v).toString("utf8")})})});g.on("error",y=>m(new Error(y.message,{cause:y}))),g.on("timeout",()=>{g.destroy(),m(new Error(`native request timeout (${o}ms)`))}),c.body.on("error",y=>{g.destroy(),m(new Error(`local asset stream failed: ${y.message}`,{cause:y}))}),c.body.pipe(g)})}finally{c.body.destroy()}}async requestBinaryFileRange(e,r,n,i,o,a="initial",s){if(!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(o)||o<0)throw new Error("\u65AD\u70B9\u5206\u7247 start/length \u5FC5\u987B\u662F\u975E\u8D1F JavaScript \u5B89\u5168\u6574\u6570");let c=new URL(`${this.config.apiBaseUrl}${e}`);for(let[g,y]of Object.entries(r))c.searchParams.set(g,y);let l=this.token,u=eI(s),p=c.protocol==="https:"?Hp.default:Jp.default,f=await new Promise((g,y)=>{let v=!1,x=E=>{v||(v=!0,y(E))},b=p.request({protocol:c.protocol,hostname:c.hostname,port:c.port||void 0,path:`${c.pathname}${c.search}`,method:"POST",timeout:u,headers:{Authorization:`Bearer ${l}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":"application/octet-stream","Content-Length":String(o)}},E=>{let S=[];E.on("data",k=>S.push(Buffer.isBuffer(k)?k:Buffer.from(k))),E.on("end",()=>{if(v)return;v=!0;let k=E.statusCode||0,A={get(R){let I=E.headers[R.toLowerCase()];return Array.isArray(I)?I.join(", "):I===void 0?null:String(I)}};g({status:k,statusText:E.statusMessage||"",headers:A,text:Buffer.concat(S).toString("utf8")})})});if(b.on("error",E=>x(new Error(E.message,{cause:E}))),b.on("timeout",()=>{b.destroy(),x(new Error(`\u65AD\u70B9\u5206\u7247\u7F51\u7EDC\u8D85\u65F6\uFF08${u}ms\uFF09`))}),o===0){b.end();return}let w=At.default.createReadStream(n,{start:i,end:i+o-1});w.on("error",E=>{b.destroy(),x(new Error(`\u8BFB\u53D6\u672C\u5730\u5206\u7247\u5931\u8D25\uFF1A${E.message}`,{cause:E}))}),w.pipe(b)}).catch(g=>{throw new yn(`\u65AD\u70B9\u5206\u7247\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1A${g instanceof Error?g.message:String(g)}`,{kind:/超时/u.test(String(g))?"timeout":"network",requestPath:e,uncertainOutcome:!0,cause:g})}),h=f.headers.get("authorization");if(h&&(this.token=vr(h),this.writeTokenToFile()),f.status===401&&a!=="credential-token"){let g=a!=="initial";if(await this.tryRecoverFromAuthFailure(l,g))return this.requestBinaryFileRange(e,r,n,i,o,Pa(a),s);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${f.text.slice(0,200)}`)}if(f.status<200||f.status>=300)throw new Error(`HTTP ${f.status} ${f.statusText} \u2014 ${f.text.slice(0,200)}`);if(!f.text)throw new Error(`HTTP ${f.status} \u2014 empty response body`);let m;try{m=JSON.parse(f.text)}catch{throw new Error(`HTTP ${f.status} \u2014 invalid JSON: ${f.text.slice(0,200)}`)}if(Ob(m)&&a!=="credential-token"){let g=a!=="initial";if(await this.tryRecoverFromAuthFailure(l,g))return this.requestBinaryFileRange(e,r,n,i,o,Pa(a),s)}return m}isUncertainWriteError(e){return e instanceof yn&&e.uncertainOutcome}readbackOptions(e){return{timeoutMs:this.readbackRequestTimeoutMs,operationName:e}}async pollReadback(e,r){let n,i="";for(let o of dB){o>0&&await new Promise(a=>setTimeout(a,o));try{let a=await e();if(n=a,a.Code===1&&r(a.Data))return{matched:!0,response:a};i=a.Msg||`\u56DE\u8BFB Code=${a.Code}`}catch(a){i=a instanceof Error?a.message:String(a)}}return{matched:!1,response:n,lastError:i}}recoveredWriteResult(e,r,n={}){return{Code:1,Data:{...n,RecoveredAfterTransportError:!0,Verification:"readback",TransportError:r.message},Msg:`${e} \u7684\u5BA2\u6237\u7AEF\u54CD\u5E94\u5F02\u5E38\uFF0C\u4F46\u5DF2\u901A\u8FC7\u8FDC\u7AEF\u56DE\u8BFB\u786E\u8BA4\u5199\u5165\u6210\u529F\u3002`}}uncertainWriteFailure(e,r,n){return new Error(`${e} \u7684\u5BA2\u6237\u7AEF\u54CD\u5E94\u5F02\u5E38\uFF0C\u4E14\u56DE\u8BFB\u672A\u80FD\u786E\u8BA4\u5199\u5165\u7ED3\u679C\u3002\u539F\u59CB\u9519\u8BEF\uFF1A${r.message}${n?`\uFF1B\u56DE\u8BFB\u7ED3\u679C\uFF1A${n}`:""}\u3002\u8BF7\u7EE7\u7EED\u4F7F\u7528\u5BF9\u5E94\u7684\u6807\u51C6 MCP \u83B7\u53D6\u5DE5\u5177\u56DE\u8BFB\u540E\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\uFF1B\u4E0D\u8981\u6539\u8D70\u539F\u751F FormEngine\u3001\u76F4\u63A5 SQL \u6216\u4E34\u65F6\u7EF4\u62A4\u63A5\u53E3\u5F15\u64CE\u3002`,{cause:r})}async getStatus(){return this.get(O.GET_STATUS)}async getAdministrativeCapabilities(){return this.get(O.GET_ADMINISTRATIVE_CAPABILITIES)}async administerTableData(e){return this.post(O.ADMINISTER_TABLE_DATA,{OsClient:this.config.osClient,Operation:e.operation,TableName:e.tableName,...e.query?{Query:e.query}:{},...e.row?{Row:e.row}:{},...e.id?{Id:e.id}:{},...e.confirmExecution?{ConfirmExecution:e.confirmExecution}:{}})}async transitionApplicationStreamGate(e){return this.post(O.TRANSITION_APPLICATION_STREAM_GATE,e,{timeoutMs:this.writeRequestTimeoutMs,operationName:`transition application stream gate ${e.TransitionId}`})}async listMyUserAccessKeys(){return this.post(O.LIST_USER_ACCESS_KEYS,{})}async listServerPrivateSettings(){return this.post("/apiengine/platform-tenant-system-settings",{Action:"List"})}async saveServerPrivateSecret(e){return this.post("/api/TenantSystemSettings/Save",{ConfigKey:e.configKey,Value:e.value,Category:e.category||"\u7B2C\u4E09\u65B9\u670D\u52A1",Description:e.description||"",IsSecret:!0,IsPublic:!1,IsEnabled:!0,ValueType:"String"},{timeoutMs:this.writeRequestTimeoutMs,operationName:"\u4FDD\u5B58\u79DF\u6237\u540E\u7AEF Secret"})}async createMyUserAccessKey(e){return this.post(O.CREATE_USER_ACCESS_KEY,{Name:e.name,Scopes:e.scopes,AllowedRoutes:e.allowedRoutes,RedirectPath:e.redirectPath,AllowedTableNames:e.allowedTableNames,AllowedApiEngineKeys:e.allowedApiEngineKeys,AllowedDataSourceKeys:e.allowedDataSourceKeys,ExpiresAt:e.expiresAt,Remark:e.remark,Permanent:!1},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u521B\u5EFA\u5F53\u524D\u7528\u6237\u8BBF\u95EE\u5BC6\u94A5 ${e.name}`})}async revokeMyUserAccessKey(e){return this.post(O.REVOKE_USER_ACCESS_KEY,{Id:e},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u540A\u9500\u5F53\u524D\u7528\u6237\u8BBF\u95EE\u5BC6\u94A5 ${e}`})}async getDbSchema(){return this.post(O.GET_DB_SCHEMA,{OsClient:this.config.osClient})}async getTableIndexes(e,r=!1){return this.post(O.GET_TABLE_INDEXES,{OsClient:this.config.osClient,TableName:e},r?this.readbackOptions(`\u56DE\u8BFB\u8868 ${e} \u7D22\u5F15`):{})}async createTableIndex(e){let r={OsClient:this.config.osClient,...e};try{return await this.post(O.CREATE_TABLE_INDEX,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u521B\u5EFA\u7D22\u5F15 ${e.IndexName||`${e.TableName}:${e.Columns.join(",")}`}`})}catch(n){if(!this.isUncertainWriteError(n))throw n;let i=await this.pollReadback(()=>this.getTableIndexes(e.TableName,!0),o=>o.some(a=>{let s=e.IndexName?String(a.Key_name||a.Name||"").toLowerCase()===e.IndexName.toLowerCase():!0,c=a.Columns?.length?a.Columns:String(a.Column_name||"").split(",").map(u=>u.trim()).filter(Boolean),l=a.IsUnique??Number(a.Non_unique)===0;return s&&l===!!e.Unique&&c.length===e.Columns.length&&c.every((u,p)=>u.toLowerCase()===e.Columns[p].toLowerCase())}));if(i.matched)return this.recoveredWriteResult("\u521B\u5EFA\u6570\u636E\u5E93\u7D22\u5F15",n,{TableName:e.TableName,IndexName:e.IndexName,Columns:e.Columns});throw this.uncertainWriteFailure("\u521B\u5EFA\u6570\u636E\u5E93\u7D22\u5F15",n,i.lastError)}}async dropTableIndex(e,r){try{return await this.post(O.DROP_TABLE_INDEX,{OsClient:this.config.osClient,TableName:e,IndexName:r},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u5220\u9664\u7D22\u5F15 ${r}`})}catch(n){if(!this.isUncertainWriteError(n))throw n;let i=await this.pollReadback(()=>this.getTableIndexes(e,!0),o=>!o.some(a=>String(a.Key_name||a.Name||"").toLowerCase()===r.toLowerCase()));if(i.matched)return this.recoveredWriteResult("\u5220\u9664\u6570\u636E\u5E93\u7D22\u5F15",n,{TableName:e,IndexName:r});throw this.uncertainWriteFailure("\u5220\u9664\u6570\u636E\u5E93\u7D22\u5F15",n,i.lastError)}}async getSupportedDatabaseTypes(){return this.post(O.GET_SUPPORTED_DATABASE_TYPES,{})}async inspectExternalDatabase(e){return this.post(O.INSPECT_EXTERNAL_DATABASE,{OsClient:this.config.osClient,...e})}async queryExternalDatabase(e){return this.post(O.QUERY_EXTERNAL_DATABASE,{OsClient:this.config.osClient,...e})}async executeExternalDatabaseSql(e){let r=Number(e.CommandTimeoutSeconds||0),n=Number.isFinite(r)&&r>0?(r+30)*1e3:63e4;return this.post(O.EXECUTE_EXTERNAL_DATABASE_SQL,{OsClient:this.config.osClient,...e},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,this.config.writeRequestTimeoutMs??6e4,n),operationName:"execute external database sql"})}async saveDatabaseConnection(e){return this.post(O.SAVE_DATABASE_CONNECTION,{OsClient:this.config.osClient,...e},{timeoutMs:this.config.writeRequestTimeoutMs,operationName:"save database connection"})}async importExternalAttachment(e){let r=Number(e.TimeoutSeconds||0),n=Number.isFinite(r)&&r>0?(r+30)*1e3:363e4;return this.post(O.IMPORT_EXTERNAL_ATTACHMENT,{OsClient:this.config.osClient,...e},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,this.config.writeRequestTimeoutMs??6e4,n),operationName:"import external attachment"})}async getPlaywrightContext(e,r){return this.post(O.GET_PLAYWRIGHT_CONTEXT,{OsClient:this.config.osClient,...e?{Keyword:e}:{},...r?{PageSize:r}:{}})}async getEngineList(e){return this.post(O.GET_ENGINE_LIST,{OsClient:this.config.osClient,...e?{_SearchKey:e}:{}})}async getEngineCode(e,r={}){return this.post(O.GET_ENGINE_CODE,{OsClient:this.config.osClient,ApiEngineKey:e},r)}async executeEngine(e,r){return this.post(O.EXECUTE_ENGINE,{OsClient:this.config.osClient,ApiEngineKey:e,Param:r||{}})}async chat(e){return this.post(O.AI_CHAT,{UserChatMsg:e.question,AiModel:e.aiModel,...e.systemPrompt?{SystemChatMsg:e.systemPrompt}:{},...e.aiModelId?{AiModelId:e.aiModelId}:{},...e.relayModel?{RelayModel:e.relayModel}:{},...e.conversationId?{ConversationId:e.conversationId}:{},...e.reasoningEffort?{ReasoningEffort:e.reasoningEffort}:{},...e.mode?{Mode:e.mode}:{},OsClient:this.config.osClient},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,33e4),operationName:"Microi AI chat"})}async recognizeOcr(e){return this.post(O.OCR_RECOGNIZE,e,{timeoutMs:gB,operationName:`OCR recognize ${e.FileName||"unnamed file"}`})}async translateText(e){return this.post(O.TRANSLATE_TEXT,{Action:"TranslateText",...e},{timeoutMs:$a,operationName:"translate text"})}async detectLanguage(e){return this.post(O.TRANSLATE_DETECT,{Action:"Detect",SourceText:e},{timeoutMs:$a,operationName:"detect language"})}async listTranslateLanguages(){return this.post(O.TRANSLATE_LANGUAGES,{Action:"Languages"},{timeoutMs:$a,operationName:"list translation languages"})}async translateFile(e){return this.post(O.TRANSLATE_FILE,{Action:"TranslateFile",...e},{timeoutMs:$a,operationName:`translate file ${e.FileName}`})}async suggestTranslation(e){return this.post(O.TRANSLATE_SUGGEST,{Action:"Suggest",...e},{timeoutMs:$a,operationName:"suggest translation"})}async getTranslateHealth(){return this.post(O.TRANSLATE_HEALTH,{Action:"Health"},{timeoutMs:$a,operationName:"translation health"})}async saveEngineCode(e,r,n){Oc(r,`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`);let i;try{let f=await this.getEngineCode(e);i=f.Code===1?f.Data:void 0}catch{i=void 0}let o=hi(i?.ApiV8Code||i?.Code),a=hi(r);if(o.length>=8e3&&a.length<o.length*.85&&!n?.confirmLargeReduction)throw new Error(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u5DF2\u62E6\u622A\uFF1A\u65B0\u6E90\u7801 ${a.length} \u5B57\u7B26\uFF0C\u8FDC\u7AEF\u6E90\u7801 ${o.length} \u5B57\u7B26\uFF0C\u51CF\u5C11\u8D85\u8FC7 15%\u3002\u8FD9\u53EF\u80FD\u662F\u957F\u5DE5\u5177\u7ED3\u679C\u88AB\u622A\u65AD\uFF1B\u786E\u8BA4\u786E\u9700\u5927\u5E45\u5220\u51CF\u65F6\u8BF7\u4F20 confirmLargeReduction="${e}"\u3002`);let s=Nc({kind:"ApiEngine",key:e,currentCode:r,remoteCode:i?.ApiV8Code||i?.Code,remoteVersion:i?.Version,functionDescription:n?.functionDescription,changeSummary:n?.changeSummary||`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`}),c=n?.v8Limit??(n?.v8Unlimited===void 0?void 0:!n.v8Unlimited),l=Up(n?.apiRoutes),u={OsClient:this.config.osClient,ApiEngineKey:e,ApiV8CodeBase64:Buffer.from(s.code,"utf8").toString("base64"),Version:s.version,ChangeSummary:s.changeHistory,...c===void 0?{}:{V8Limit:c?1:0},...n?.responseType===void 0?{}:{ResponseType:n.responseType},...l===void 0?{}:{ApiRoutes:l}},p=f=>hi(f?.ApiV8Code||f?.Code)===hi(s.code)&&(c===void 0||Nb(f)===(c?1:0))&&(n?.responseType===void 0||String(f?.ResponseType||"JSON").toLowerCase()===n.responseType.toLowerCase())&&(l===void 0||Up(f?.ApiRoutes||"")===l);try{let f=await this.post(O.UPDATE_ENGINE_CODE,u,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`});if(f.Code!==1||c===void 0&&n?.responseType===void 0&&l===void 0)return f;let h=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`)),p);return h.matched?{...f,Data:{...f.Data&&typeof f.Data=="object"?f.Data:{},ApiEngineKey:e,...c===void 0?{}:{V8Limit:c?1:0},...n?.responseType===void 0?{}:{ResponseType:n.responseType},...l===void 0?{}:{ApiRoutes:l},Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:f.Data},Msg:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FD0\u884C\u914D\u7F6E\u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${h.lastError||"\u4EE3\u7801\u6216\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(f){if(!this.isUncertainWriteError(f))throw f;let h=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e}`)),p);if(h.matched)return this.recoveredWriteResult(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,f,{ApiEngineKey:e,Version:s.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,f,h.lastError)}}async updateEngineRuntimeLimit(e,r){let n={OsClient:this.config.osClient,ApiEngineKey:e,V8Limit:r?1:0},i=()=>this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`)),a=>Nb(a)===(r?1:0)),o=`\u66F4\u65B0\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`;try{let a=await this.post(O.UPDATE_ENGINE_CODE,n,{timeoutMs:this.writeRequestTimeoutMs,operationName:o});if(a.Code!==1)return a;let s=await i();return s.matched?{...a,Data:{...a.Data&&typeof a.Data=="object"?a.Data:{},ApiEngineKey:e,V8Limit:r?1:0,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:a.Data},Msg:`${o} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${s.lastError||"\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(a){if(!this.isUncertainWriteError(a))throw a;let s=await i();if(s.matched)return this.recoveredWriteResult(o,a,{ApiEngineKey:e,V8Limit:r?1:0,Verified:!0});throw this.uncertainWriteFailure(o,a,s.lastError)}}async updateEngineRuntimeConfig(e,r){return this.updateEngineRuntimeLimit(e,!r)}async createEngine(e){let r={OsClient:this.config.osClient,...e};r.ApiRoutes=Up(r.ApiRoutes)||"",r.V8Limit===void 0&&r.V8Unlimited!==void 0&&(r.V8Limit=Number(r.V8Unlimited)===1?0:1),delete r.V8Unlimited;let n=typeof r.Code=="string"?r.Code:typeof r.ApiV8Code=="string"?r.ApiV8Code:"";Oc(n,`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`);let i=Nc({kind:"ApiEngine",key:e.ApiEngineKey,currentCode:n,functionDescription:r.functionDescription,changeSummary:r.changeSummary||`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`,initial:!0});r.ApiV8CodeBase64=Buffer.from(i.code,"utf8").toString("base64"),r.Version=i.version,r.ChangeSummary=i.changeHistory,delete r.Code,delete r.ApiV8Code,delete r.functionDescription,delete r.changeSummary,(!r.ApiAddress||r.ApiAddress.trim().length===0)&&(r.ApiAddress=`/apiengine/${e.ApiEngineKey}`),r.IsEnable=r.IsEnable??1,r.StopHttp=r.StopHttp??0,r.AllowAnonymous=r.AllowAnonymous??0;let o=`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`,a=()=>this.pollReadback(()=>this.getEngineCode(e.ApiEngineKey,this.readbackOptions(`\u56DE\u8BFB\u65B0\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`)),s=>String(s?.ApiEngineKey||"")===e.ApiEngineKey&&hi(s?.ApiV8Code||s?.Code)===hi(i.code)&&(r.V8Limit===void 0||Nb(s)===(Number(r.V8Limit)===1?1:0))&&(r.ResponseType===void 0||String(s?.ResponseType||"JSON").toLowerCase()===String(r.ResponseType).toLowerCase())&&Up(s?.ApiRoutes||"")===r.ApiRoutes);try{let s=await this.post(O.CREATE_ENGINE,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:o});if(s.Code!==1)return s;let c=await a();return c.matched?{...s,Data:{...s.Data&&typeof s.Data=="object"?s.Data:{},ApiEngineKey:e.ApiEngineKey,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e.ApiEngineKey,CreateResponse:s.Data},Msg:`${o} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u672A\u786E\u8BA4\u65B0\u8BB0\u5F55\uFF1A${c.lastError||"\u8BB0\u5F55\u6216\u4EE3\u7801\u4E0D\u4E00\u81F4"}`}}catch(s){if(!this.isUncertainWriteError(s))throw s;let c=await a();if(c.matched)return this.recoveredWriteResult(o,s,{ApiEngineKey:e.ApiEngineKey,Version:i.version,Verified:!0});throw this.uncertainWriteFailure(o,s,c.lastError)}}async uploadFileBase64(e){return this.post(O.UPLOAD_FILE_BASE64,{OsClient:this.config.osClient,...e})}async uploadApplicationAssetStream(e){let r=Oa.default.resolve(e.FilePath),n=At.default.lstatSync(r);if(!n.isFile()||n.isSymbolicLink())throw new Error(`\u5E94\u7528\u8D44\u4EA7\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${r}`);let i=Oa.default.posix.basename(String(e.RelativePath||"").replace(/\\/g,"/"));if(!i||/[\r\n"]/u.test(i))throw new Error("RelativePath \u7684\u6587\u4EF6\u540D\u4E0D\u5408\u6CD5");if(e.ProtocolVersion===3)return this.uploadApplicationAssetResumable(e,r,n.size);if(n.size>mB)throw new Error(`\u5F53\u524D\u6587\u4EF6 ${n.size} bytes \u8D85\u8FC7\u65E7\u7248 128MiB \u5355\u8BF7\u6C42\u8FB9\u754C\uFF1B\u8BF7\u542F\u7528 ProtocolVersion=3\uFF0CMCP \u5C06\u81EA\u52A8\u4F7F\u7528 HDFS \u5206\u7247\u65AD\u70B9\u7EED\u4F20\u3002`);let o=`microi-asset-${e.ExpectedSha256.slice(0,16)}.bin`,a={};if(e.ProtocolVersion===3){let s=c=>c===null?"null":String(c??"");Object.assign(a,{ProtocolVersion:"3",PublishMode:"stage",ExpectedGateEpoch:String(e.ExpectedGateEpoch??""),RequestFingerprint:String(e.RequestFingerprint??""),DeliveryBatchId:String(e.DeliveryBatchId??""),SourceManifestHash:String(e.SourceManifestHash??""),RuntimeManifestHash:String(e.RuntimeManifestHash??""),RouteSnapshotJson:String(e.RouteSnapshotJson??""),RouteSnapshotHash:String(e.RouteSnapshotHash??""),ExpectedCurrentVersion:String(e.ExpectedCurrentVersion??""),ExpectedAppVersion:s(e.ExpectedAppVersion),ExpectedPublishFence:String(e.ExpectedPublishFence??""),ExpectedPublishRowVersion:String(e.ExpectedPublishRowVersion??""),ExpectedVersionRowVersion:s(e.ExpectedVersionRowVersion),ExpectedActivePublishVersionId:s(e.ExpectedActivePublishVersionId),ExpectedCommittedPublishVersionId:s(e.ExpectedCommittedPublishVersionId)})}return this.requestMultipartFile(O.UPLOAD_APPLICATION_ASSET_STREAM,{OsClient:this.config.osClient||"",AppIdOrKey:e.AppIdOrKey,VersionNo:e.VersionNo,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,RequestId:e.RequestId,...a},r,o,"initial",e.TimeoutMs)}async getApplicationAssetMultipartStatus(e,r){return this.post(O.GET_APPLICATION_ASSET_MULTIPART_STATUS,{OsClient:this.config.osClient,AppIdOrKey:e,SessionId:r},{timeoutMs:2*6e4,operationName:"read resumable application asset status"})}async uploadApplicationAssetResumable(e,r,n){if(!Number.isSafeInteger(n)||n<0)throw new Error("\u5E94\u7528\u8D44\u4EA7\u5927\u5C0F\u8D85\u51FA JavaScript \u5B89\u5168\u6574\u6570\u8303\u56F4");let i=vB(e),o=await this.post(O.INITIATE_APPLICATION_ASSET_MULTIPART,{OsClient:this.config.osClient,AppIdOrKey:e.AppIdOrKey,VersionNo:e.VersionNo,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,TotalSize:n,RequestedChunkSize:hB,RequestId:e.RequestId,...i},{timeoutMs:2*6e4,operationName:"initiate resumable application asset upload"});if(o.Code!==1)return o;let a=o.Data,s=String(a?.SessionId||"").trim(),c=Number(a?.ChunkSize),l=Number(a?.TotalParts);if(!/^mciau-[a-f0-9]{30}$/u.test(s)||!Number.isSafeInteger(c)||c<16*1024*1024||!Number.isSafeInteger(l)||l<0||l>1e4||l!==(n===0?0:Math.ceil(n/c)))throw new Error("\u670D\u52A1\u7AEF\u8FD4\u56DE\u7684\u65AD\u70B9\u4E0A\u4F20 SessionId/ChunkSize/TotalParts \u4E0D\u5408\u6CD5");let u=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);if(u.Code!==1||String(u.Data?.Status||"")==="Succeeded")return u;let f=new Map;for(let g of u.Data?.Parts||[]){let y=Number(g.Number);Number.isSafeInteger(y)&&y>0&&y<=l&&f.set(y,g)}let h=0,m=0;for(let g=1;g<=l;g+=1){let y=(g-1)*c,v=Math.min(c,n-y),x=await bB(r,y,v),b=f.get(g);if(b){if(Number(b.Size)!==v||String(b.Sha256||"")!==x)throw new Error(`\u65AD\u70B9\u4F1A\u8BDD\u7B2C ${g} \u5757\u4E0E\u672C\u5730\u4E0D\u53EF\u53D8\u6587\u4EF6\u4E0D\u4E00\u81F4\uFF1B\u5DF2\u62D2\u7EDD\u8986\u76D6\uFF0C\u8BF7\u6838\u5BF9\u672C\u5730\u6587\u4EF6\u662F\u5426\u5728\u4E0A\u4F20\u671F\u95F4\u53D1\u751F\u53D8\u5316\u3002`);m+=1;continue}let w;for(let E=0;E<5;E+=1)try{if(w=await this.requestBinaryFileRange(O.UPLOAD_APPLICATION_ASSET_MULTIPART_PART,{osClient:this.config.osClient||"",sessionId:s,partNumber:String(g),expectedPartSha256:x},r,y,v,"initial",e.TimeoutMs),w.Code===1)break;if(E===4)return w}catch(S){u=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);let k=(u.Data?.Parts||[]).find(A=>Number(A.Number)===g);if(u.Code===1&&k&&Number(k.Size)===v&&String(k.Sha256||"")===x){w=u;break}if(E===4)throw S;await new Promise(A=>setTimeout(A,500*(E+1)))}if(!w||w.Code!==1)return w||{Code:0,Data:null,Msg:`\u7B2C ${g} \u5757\u4E0A\u4F20\u6CA1\u6709\u8FD4\u56DE\u7EC8\u6001`};h+=1,(g===1||g%20===0||g===l)&&console.error(`[microi-mcp] Resumable HDFS asset ${e.RelativePath}: ${g}/${l}`)}try{let g=await this.post(O.COMPLETE_APPLICATION_ASSET_MULTIPART,{OsClient:this.config.osClient,AppIdOrKey:e.AppIdOrKey,SessionId:s},{timeoutMs:Mb,maxTimeoutMs:Mb,operationName:"complete resumable application asset upload"});return g.Code===1&&g.Data&&typeof g.Data=="object"?{...g,Data:{...g.Data,UploadedInThisRun:h,ResumedParts:m}}:g}catch(g){let y=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);if(y.Code===1&&String(y.Data?.Status||"")==="Succeeded")return{...y,Data:{...y.Data,RecoveredAfterTransportError:!0,UploadedInThisRun:h,ResumedParts:m},Msg:"\u5B8C\u6210\u8BF7\u6C42\u54CD\u5E94\u4E2D\u65AD\uFF0C\u4F46\u5DF2\u901A\u8FC7\u4F1A\u8BDD\u56DE\u8BFB\u786E\u8BA4\u6700\u7EC8\u5BF9\u8C61 Prepared\u3002"};throw g}}async finalizeApplicationStreamPublish(e){return this.post(O.FINALIZE_APPLICATION_STREAM_PUBLISH,{OsClient:this.config.osClient,...e},{timeoutMs:10*6e4,operationName:"finalize application stream publish"})}async getMicroService(e){return this.post(O.GET_MICRO_SERVICE,{OsClient:this.config.osClient,MsKey:e})}async listApplications(e={}){return this.post(O.LIST_APPLICATIONS,{OsClient:this.config.osClient,...e})}async getApplicationContext(e){return this.post(O.GET_APPLICATION_CONTEXT,{OsClient:this.config.osClient,...e})}async getApplicationFile(e){return this.post(O.GET_APPLICATION_FILE,{OsClient:this.config.osClient,...e})}async createMicroService(e){return this.post(O.CREATE_MICRO_SERVICE,{OsClient:this.config.osClient,...e})}async syncMicroServiceSource(e){return this.post(O.SYNC_MICRO_SERVICE_SOURCE,{OsClient:this.config.osClient,...e},{allowNativeFallback:!1,operationName:"legacy private microservice source sync"})}async stageMicroServiceSourceFile(e){let r=Oa.default.resolve(e.FilePath),n=At.default.lstatSync(r);if(!n.isFile()||n.isSymbolicLink())throw new Error(`\u5FAE\u670D\u52A1\u6E90\u7801\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${r}`);if(n.size!==e.ExpectedSize)throw new Error(`\u5FAE\u670D\u52A1\u6E90\u7801\u5927\u5C0F\u5728\u6E05\u5355\u751F\u6210\u540E\u53D1\u751F\u53D8\u5316\uFF1A${e.RelativePath}`);let i=e.MicroService||{},o={OsClient:this.config.osClient||"",AppIdOrKey:e.AppIdOrKey,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,ExpectedSize:String(e.ExpectedSize),DeliveryBatchId:e.DeliveryBatchId};for(let a of["MsKey","MicroServiceKey","AppKey","MsName","Name","AppName","ApplicationType","AppType","Category","Description","Remark"]){let s=i[a];s!=null&&(o[a]=String(s))}return this.requestMultipartFile(O.STAGE_MICRO_SERVICE_SOURCE_FILE,o,r,`microi-source-${e.ExpectedSha256.slice(0,16)}.bin`,"initial",e.TimeoutMs,void 0,!1)}async finalizeMicroServiceSourceManifest(e){return this.post(O.FINALIZE_MICRO_SERVICE_SOURCE_MANIFEST,{OsClient:this.config.osClient,...e},{timeoutMs:10*6e4,operationName:"finalize private microservice source manifest"})}async clearApplicationSource(e){return this.post(O.CLEAR_APPLICATION_SOURCE,{OsClient:this.config.osClient,...e},{timeoutMs:10*6e4,operationName:"clear application source"})}async publishMicroService(e){return this.post(O.PUBLISH_MICRO_SERVICE,{OsClient:this.config.osClient,...e})}async probeMicroAppEntry(e){let r=sB(this.config.apiBaseUrl,this.config.osClient||"",e),n=new AbortController,i=setTimeout(()=>n.abort(),1e4);try{let o=await fetch(r,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},redirect:"follow",signal:n.signal}),a=o.headers.get("content-type")||"",s=Number(o.headers.get("content-length")||0);if(Number.isFinite(s)&&s>2*1024*1024)return await o.body?.cancel(),{ok:!1,url:r,status:o.status,contentType:a,bodyBytes:s,error:"MicroApp entry exceeds the 2MB probe limit"};let c=Buffer.from(await o.arrayBuffer()),l=c.byteLength,u=c.toString("utf8"),p=/<head(?:\s|>)/iu.test(u),f=/<body(?:\s|>)/iu.test(u),h=o.ok&&a.toLowerCase().includes("text/html")&&l>0&&p&&f;return{ok:h,url:r,status:o.status,contentType:a,bodyBytes:l,hasHead:p,hasBody:f,...o.ok?h?{}:{error:"MicroApp entry is not a complete HTML document with <head> and <body>"}:{error:`HTTP ${o.status} ${o.statusText}`}}}catch(o){return{ok:!1,url:r,error:n.signal.aborted?"MicroApp entry probe timed out after 10000ms":o instanceof Error?o.message:String(o)}}finally{clearTimeout(i)}}async getTableData(e,r={}){return this.post(O.FORM_GET_TABLE_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async addFormData(e,r){return this.post(O.FORM_ADD_FORM_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async updateFormData(e,r){return this.post(O.FORM_UPT_FORM_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async getEventCode(e,r,n={}){return r=r==="DataFilterV8"?"ServerDataV8":r,this.post(O.GET_EVENT_CODE,{OsClient:this.config.osClient,FormEngineKey:e,EventType:r},n)}async saveEventCode(e,r,n,i){r=r==="DataFilterV8"?"ServerDataV8":r,Oc(n,`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`);let o;try{let c=await this.getEventCode(e,r);o=c.Code===1?c.Data:void 0}catch{o=void 0}let a=Nc({kind:"V8Event",key:e,eventType:r,currentCode:n,remoteCode:o?.V8Code||o?.Code,remoteVersion:o?.Version,functionDescription:i?.functionDescription,changeSummary:i?.changeSummary||`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`}),s={OsClient:this.config.osClient,FormEngineKey:e,EventType:r,V8Code:a.code,Version:a.version,ChangeHistory:a.changeHistory};try{return await this.post(O.UPDATE_EVENT_CODE,s,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`})}catch(c){if(!this.isUncertainWriteError(c))throw c;let l=await this.pollReadback(()=>this.getEventCode(e,r,this.readbackOptions(`\u56DE\u8BFB V8 \u4E8B\u4EF6 ${e}/${r}`)),u=>hi(u?.V8Code||u?.Code)===hi(a.code));if(l.matched)return this.recoveredWriteResult(`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`,c,{FormEngineKey:e,EventType:r,Version:a.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`,c,l.lastError)}}async getEventList(e){return this.post(O.GET_EVENT_LIST,{OsClient:this.config.osClient,...e?{_SearchKey:e}:{}})}async getWorkflowV8EventList(e){return this.post(O.GET_WORKFLOW_V8_EVENT_LIST,{OsClient:this.config.osClient,...e?{FlowDesignId:e}:{}})}async getWorkflowV8EventCode(e,r,n){return this.post(O.GET_WORKFLOW_V8_EVENT_CODE,{OsClient:this.config.osClient,...n?{FlowDesignId:n}:{},NodeId:e,EventType:r})}async saveWorkflowV8EventCode(e,r,n,i){Oc(n,`\u4FDD\u5B58\u6D41\u7A0B\u8282\u70B9 V8 ${e}/${r}`);let o;try{let c=await this.getWorkflowV8EventCode(e,r,i?.flowDesignId);o=c.Code===1?c.Data:void 0}catch{o=void 0}let a=!n.trim(),s={OsClient:this.config.osClient,...i?.flowDesignId?{FlowDesignId:i.flowDesignId}:{},NodeId:e,EventType:r};if(a)s.V8Code="";else{let c=`${i?.flowDesignId||o?.FlowDesignId||"workflow"}/${e}`,l=Nc({kind:"Workflow",key:c,eventType:r,currentCode:n,remoteCode:o?.V8Code||o?.Code,remoteVersion:o?.Version,functionDescription:i?.functionDescription,changeSummary:i?.changeSummary||`\u4FDD\u5B58\u6D41\u7A0B\u8282\u70B9 V8 ${e}/${r}`});s.V8CodeBase64=Buffer.from(l.code,"utf8").toString("base64"),s.Version=l.version,s.ChangeHistory=l.changeHistory}return this.post(O.UPDATE_WORKFLOW_V8_EVENT_CODE,s)}async createTable(e,r,n){let i={...n||{}};i.V8Limit===void 0&&i.V8Unlimited!==void 0&&(i.V8Limit=Number(i.V8Unlimited)===1?0:1),delete i.V8Unlimited;let o=i.ReadPrimary;if(o!=null&&o!==0&&o!==1)throw new Error("ReadPrimary \u53EA\u5141\u8BB8 null\u30010 \u6216 1");delete i.ReadPrimary;let a=await this.post(O.CREATE_TABLE,{OsClient:this.config.osClient,Name:e,Description:r||"",...i});if(a.Code!==1||o===void 0)return a;let s=a.Data?.TableId||a.Data?.Id;if(!s)return{Code:0,Data:null,Msg:"\u8868\u521B\u5EFA\u540E\u7F3A\u5C11 TableId\uFF0C\u672A\u914D\u7F6E ReadPrimary"};let c=await this.updateTable({Id:s,ReadPrimary:o});return c.Code!==1?c:{...a,Data:{...a.Data,ReadPrimary:o}}}async repairFixedAuditFields(e){return this.post(O.REPAIR_FIXED_AUDIT_FIELDS,{OsClient:this.config.osClient,TableId:e.tableId,TableName:e.tableName})}async addField(e){return this.post(O.ADD_FIELD,{OsClient:this.config.osClient,...e,Visible:e.Visible??1,AppVisible:e.AppVisible??1})}async deleteField(e){return this.post(O.DELETE_FIELD,{OsClient:this.config.osClient,...e})}async updateField(e){return this.post(O.UPDATE_FIELD,{OsClient:this.config.osClient,...e})}async updateFieldList(e){return this.post(O.UPDATE_FIELD_LIST,{OsClient:this.config.osClient,...e})}async getFieldList(e,r){return this.post(O.GET_FIELD_LIST,{OsClient:this.config.osClient,TableName:e,TableId:r})}async updateTable(e){return this.post(O.UPDATE_TABLE,{OsClient:this.config.osClient,...e})}async refreshSchemaCache(e){return this.post(O.REFRESH_SCHEMA_CACHE,{OsClient:this.config.osClient,Tables:e})}async setEngineAnonymous(e,r=1){return this.post(O.SET_ENGINE_ANONYMOUS,{OsClient:this.config.osClient,ApiEngineKeys:e,AllowAnonymous:r})}async setEngineRoles(e){return this.post(O.SET_ENGINE_ROLES,{OsClient:this.config.osClient,...e})}async generateMiniMaxMusic(e){return this.post(O.GENERATE_MINIMAX_MUSIC,e,{timeoutMs:10*6e4,operationName:"generate MiniMax music"})}async generateMiniMaxSpeech(e){return this.post(O.GENERATE_MINIMAX_SPEECH,e,{timeoutMs:10*6e4,operationName:"generate MiniMax speech"})}async createModule(e){let r=await this.post(O.CREATE_MODULE,{OsClient:this.config.osClient,...e,Display:e.Display??1,AppDisplay:e.AppDisplay??1});if(r.Code!==1||!!!(e.IsMicroiService===1||e.MicroServiceId||e.MicroServicePageId||e.MicroServiceRoutePath))return r;let i=r.Data&&typeof r.Data=="object"?r.Data:{},o=String(i.ModuleId||i.Id||"");if(!o)return{Code:0,Data:{CreateResponse:r.Data},Msg:"\u83DC\u5355\u5DF2\u521B\u5EFA\uFF0C\u4F46\u8FD4\u56DE\u7ED3\u679C\u7F3A\u5C11 ModuleId\uFF0C\u65E0\u6CD5\u5199\u5165\u5E76\u56DE\u8BFB\u5FAE\u670D\u52A1\u5173\u8054\u5B57\u6BB5\u3002"};let a={ModuleId:o,IsMicroiService:1,OpenType:e.OpenType||"MicroService",ComponentName:e.ComponentName||"MicroService",ComponentPath:e.ComponentPath||"/micro-app/host",Url:e.Url,MicroServiceId:e.MicroServiceId,MicroServicePageId:e.MicroServicePageId,MicroServiceRoutePath:e.MicroServiceRoutePath},s=await this.updateModule(a);return s.Code!==1?{Code:0,Data:{ModuleId:o,CreateResponse:r.Data,BindingResponse:s.Data},Msg:`\u83DC\u5355\u57FA\u7840\u8BB0\u5F55\u5DF2\u521B\u5EFA\uFF0C\u4F46\u5FAE\u670D\u52A1\u5173\u8054\u5B57\u6BB5\u5199\u5165\u6216\u56DE\u8BFB\u5931\u8D25\uFF1A${s.Msg||"\u672A\u77E5\u9519\u8BEF"}`}:{...r,Data:{...i,MicroServiceBindingVerified:!0,BindingVerification:s.Data}}}async setRolePermission(e,r){return this.post(O.SET_ROLE_PERMISSION,{OsClient:this.config.osClient,RoleId:e,MenuIds:r})}async listRoles(e){return this.post(O.LIST_ROLES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async saveRole(e){return this.post(O.SAVE_ROLE,{OsClient:this.config.osClient,...e})}async listModules(e){return this.post(O.LIST_MODULES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getModule(e,r={}){return this.post(O.GET_MODULE,{OsClient:this.config.osClient,ModuleId:e},r)}async updateModule(e){let r={OsClient:this.config.osClient,...e},n=String(r.ModuleId||r.Id||""),i=`\u66F4\u65B0\u83DC\u5355\u6A21\u5757 ${n||r.Name||""}`.trim();$c(r,i);let o=async()=>{if(!n)return{matched:!1,mismatches:["ModuleId"]};try{let a=await this.getModule(n,this.readbackOptions(`\u56DE\u8BFB\u83DC\u5355\u6A21\u5757 ${n}`));return a.Code!==1||!a.Data||typeof a.Data!="object"?{matched:!1,mismatches:["\u56DE\u8BFB\u5931\u8D25"],response:a}:{...xB(r,a.Data),response:a}}catch{return{matched:!1,mismatches:["\u56DE\u8BFB\u8BF7\u6C42\u5F02\u5E38"]}}};try{let a=await this.post(O.UPDATE_MODULE,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:i});if(a.Code!==1)return a;let s=await o();return s.matched?{...a,Data:{...a.Data&&typeof a.Data=="object"?a.Data:{},Verified:!0,Verification:"readback"}}:{Code:0,Data:{ModuleId:n,Mismatches:s.mismatches,UpdateResponse:a.Data},Msg:`${i} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${s.mismatches.join(", ")}`}}catch(a){if(!this.isUncertainWriteError(a))throw a;let s=[],c=await this.pollReadback(async()=>{let l=await o();return s=l.mismatches,{Code:l.response?.Code??(l.matched?1:0),Data:l,Msg:l.response?.Msg||""}},l=>l.matched);if(c.matched)return this.recoveredWriteResult(i,a,{ModuleId:n,Verified:!0});throw this.uncertainWriteFailure(i,a,s.length?`\u5B57\u6BB5\u4E0D\u4E00\u81F4\uFF1A${s.join(", ")}`:c.lastError)}}async listDataSources(e){return this.post(O.LIST_DATA_SOURCES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async saveDataSource(e){return this.post(O.SAVE_DATA_SOURCE,{OsClient:this.config.osClient,...e})}async runDataSource(e,r){return this.post(O.RUN_DATA_SOURCE,{OsClient:this.config.osClient,DataSourceKey:e,...r||{}})}async listPrintTemplates(e){return this.post(O.LIST_PRINT_TEMPLATES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async savePrintTemplate(e){return this.post(O.SAVE_PRINT_TEMPLATE,{OsClient:this.config.osClient,...e})}async saveWorkflowPackage(e){return this.post(O.SAVE_WORKFLOW_PACKAGE,{OsClient:this.config.osClient,...e})}async saveJob(e){return this.post(O.SAVE_JOB,{OsClient:this.config.osClient,...e})}async listDatabaseBackupTenants(){return this.post(O.LIST_DATABASE_BACKUP_TENANTS,{OsClient:this.config.osClient})}async runDatabaseBackup(e){if(!/^[A-Za-z0-9:._-]{8,128}$/.test(e?.idempotencyKey||""))throw new Error("database backup idempotencyKey is required (8-128 safe characters) and must be reused for uncertain retries");return this.post(O.RUN_DATABASE_BACKUP,{OsClient:this.config.osClient,ConfirmExecution:"DATABASE_BACKUP",RetainCount:e.retainCount??7,...e.tenantOsClients===void 0?{}:{TenantOsClients:e.tenantOsClients},IdempotencyKey:e.idempotencyKey})}async runBackgroundApiEngine(e){return this.post(O.RUN_BACKGROUND_API_ENGINE,{OsClient:this.config.osClient,Action:"RunApiEngine",TargetApiEngineKey:e.apiEngineKey,Title:e.title,Param:e.param,Options:e.options||{}},{timeoutMs:this.writeRequestTimeoutMs,operationName:`queue background API engine ${e.apiEngineKey}`})}async validateLowCodeSystem(e){return this.post(O.VALIDATE_LOW_CODE_SYSTEM,{OsClient:this.config.osClient,Manifest:e})}async writeAuditLog(e,r,n){return this.post(O.WRITE_MCP_AUDIT_LOG,{OsClient:this.config.osClient,Action:e,Target:r,Content:n})}async queryMongodbLogs(e={}){return this.post(O.QUERY_MONGODB_LOGS,{OsClient:this.config.osClient,Keyword:e.keyword,Type:e.type,Level:e.level,SearchMonth:e.searchMonth,PageIndex:e.pageIndex||1,PageSize:e.pageSize||20})}async writeMongodbLog(e){return this.post(O.WRITE_MONGODB_LOG,{OsClient:this.config.osClient,Type:e.type||"MCP",Title:e.title,Content:e.content,Level:e.level||1,Api:e.api||"microi.mcp",Param:e.param||"",Remark:e.remark||"",OtherInfo:e.otherInfo||"",Timer:e.timer,Result:e.result||"",AppId:e.appId||"microi.mcp"})}async querySystemObservability(e){return e.Action==="DatabasePools"||e.Action==="DatabasePoolRecovery"?this.post("/api/Diagnostics/database-pools",{...e,OsClient:this.config.osClient},{allowNativeFallback:!1,timeoutMs:3e4}):this.executeEngine("mci-system-observability-query",e)}async manageSystemObservability(e){return e.Action==="ResetDatabasePools"?this.post("/api/Diagnostics/database-pools",{...e,OsClient:this.config.osClient},{allowNativeFallback:!1,timeoutMs:3e4}):this.executeEngine("mci-system-observability-action",e)}async getRedisStatistics(e=0,r){return this.post(O.REDIS_STATISTICS,{Action:"RedisStatistics",Mode:r?"saved":"tenant",ConnectionId:r||"",Database:e})}async getRedisKeys(e="*",r=0,n=100,i,o){return this.post(O.REDIS_KEYS,{Action:"Keys",Mode:o?"saved":"tenant",ConnectionId:o||"",Database:r,Pattern:e,PageSize:n,Cursor:i||""})}async getRedisKey(e,r=0,n=1,i=500,o){return this.post(O.REDIS_KEY,{Action:"Key",Mode:o?"saved":"tenant",ConnectionId:o||"",Database:r,Key:e,PageIndex:n,PageSize:i})}async deleteRedisKeys(e,r=0,n){return this.post(O.REDIS_DELETE_KEYS,{Action:"DeleteKeys",Mode:n?"saved":"tenant",ConnectionId:n||"",Database:r,Keys:e})}async replaceRedisValue(e,r,n,i=0,o,a){return this.post(O.REDIS_REPLACE_VALUE,{Action:"ReplaceValue",Mode:a?"saved":"tenant",ConnectionId:a||"",Database:i,Key:e,DataType:r,Value:n,...o===void 0?{}:{TtlSeconds:o}})}async renameRedisKey(e,r,n=0,i){return this.post(O.REDIS_RENAME_KEY,{Action:"RenameKey",Mode:i?"saved":"tenant",ConnectionId:i||"",Database:n,Key:e,NewKey:r})}async setRedisTtl(e,r,n=0,i){return this.post(O.REDIS_SET_TTL,{Action:"SetTtl",Mode:i?"saved":"tenant",ConnectionId:i||"",Database:n,Key:e,TtlSeconds:r})}async getPageEngineList(e){return this.post(O.GET_PAGE_ENGINE_LIST,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getPageEngineDetail(e){return this.post(O.GET_PAGE_ENGINE_DETAIL,{OsClient:this.config.osClient,PageId:e})}async savePageEngine(e){return this.post(O.SAVE_PAGE_ENGINE,{OsClient:this.config.osClient,...e})}async listBackgroundTasks(){return this.post(O.LIST_BACKGROUND_TASKS,{OsClient:this.config.osClient,Action:"List"},{timeoutMs:this.requestTimeoutMs,operationName:"list background tasks"})}async cancelBackgroundTask(e){return this.post(O.CANCEL_BACKGROUND_TASK,{OsClient:this.config.osClient,Action:"Cancel",Id:e},{timeoutMs:this.writeRequestTimeoutMs,operationName:"cancel background task"})}async listPageEngineHistory(e,r=1,n=50){return this.post(O.LIST_PAGE_ENGINE_HISTORY,{OsClient:this.config.osClient,PageId:e,PageIndex:r,PageSize:n})}async getPageEngineHistory(e,r){return this.post(O.GET_PAGE_ENGINE_HISTORY,{OsClient:this.config.osClient,PageId:e,HistoryId:r})}async comparePageEngineVersions(e,r,n){return this.post(O.COMPARE_PAGE_ENGINE_VERSIONS,{OsClient:this.config.osClient,PageId:e,...r?{LeftHistoryId:r}:{},...n?{RightHistoryId:n}:{}})}async exportPageEngine(e){return this.post(O.EXPORT_PAGE_ENGINE,{OsClient:this.config.osClient,PageId:e})}async rollbackPageEngine(e){return this.post(O.ROLLBACK_PAGE_ENGINE,{OsClient:this.config.osClient,...e})}async listBlueprints(e){return this.post(O.LIST_BLUEPRINTS,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getBlueprint(e){return this.post(O.GET_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async listBlueprintHistory(e,r=1,n=50){return this.post(O.LIST_BLUEPRINT_HISTORY,{OsClient:this.config.osClient,BlueprintId:e,PageIndex:r,PageSize:n})}async getBlueprintHistory(e,r){return this.post(O.GET_BLUEPRINT_HISTORY,{OsClient:this.config.osClient,BlueprintId:e,HistoryId:r})}async compareBlueprintVersions(e,r,n){return this.post(O.COMPARE_BLUEPRINT_VERSIONS,{OsClient:this.config.osClient,BlueprintId:e,...r?{LeftHistoryId:r}:{},...n?{RightHistoryId:n}:{}})}async exportBlueprint(e){return this.post(O.EXPORT_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async saveBlueprint(e){return this.post(O.SAVE_BLUEPRINT,{OsClient:this.config.osClient,...e})}async rollbackBlueprint(e){return this.post(O.ROLLBACK_BLUEPRINT,{OsClient:this.config.osClient,...e})}async deleteBlueprint(e){return this.post(O.DELETE_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async validateBlueprint(e){return this.post(O.VALIDATE_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}};var d={};Sf(d,{BRAND:()=>HB,DIRTY:()=>so,EMPTY_PATH:()=>EB,INVALID:()=>G,NEVER:()=>IU,OK:()=>It,ParseStatus:()=>wt,Schema:()=>ae,ZodAny:()=>bi,ZodArray:()=>Vn,ZodBigInt:()=>lo,ZodBoolean:()=>uo,ZodBranded:()=>zc,ZodCatch:()=>_o,ZodDate:()=>po,ZodDefault:()=>wo,ZodDiscriminatedUnion:()=>Gp,ZodEffects:()=>Rr,ZodEnum:()=>vo,ZodError:()=>nr,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Yp,ZodIntersection:()=>go,ZodIssueCode:()=>N,ZodLazy:()=>yo,ZodLiteral:()=>bo,ZodMap:()=>La,ZodNaN:()=>qa,ZodNativeEnum:()=>xo,ZodNever:()=>Gr,ZodNull:()=>mo,ZodNullable:()=>xn,ZodNumber:()=>co,ZodObject:()=>or,ZodOptional:()=>ir,ZodParsedType:()=>L,ZodPipeline:()=>Lc,ZodPromise:()=>vi,ZodReadonly:()=>So,ZodRecord:()=>Xp,ZodSchema:()=>ae,ZodSet:()=>ja,ZodString:()=>yi,ZodSymbol:()=>Fa,ZodTransformer:()=>Rr,ZodTuple:()=>vn,ZodType:()=>ae,ZodUndefined:()=>fo,ZodUnion:()=>ho,ZodUnknown:()=>qn,ZodVoid:()=>za,addIssueToContext:()=>z,any:()=>tU,array:()=>oU,bigint:()=>GB,boolean:()=>gI,coerce:()=>AU,custom:()=>fI,date:()=>XB,datetimeRegex:()=>pI,defaultErrorMap:()=>Ln,discriminatedUnion:()=>cU,effect:()=>xU,enum:()=>yU,function:()=>mU,getErrorMap:()=>Na,getParsedType:()=>bn,instanceof:()=>KB,intersection:()=>lU,isAborted:()=>Kp,isAsync:()=>Ma,isDirty:()=>Wp,isValid:()=>gi,late:()=>ZB,lazy:()=>hU,literal:()=>gU,makeIssue:()=>Fc,map:()=>dU,nan:()=>WB,nativeEnum:()=>bU,never:()=>nU,null:()=>eU,nullable:()=>_U,number:()=>hI,object:()=>jb,objectUtil:()=>Fb,oboolean:()=>CU,onumber:()=>TU,optional:()=>wU,ostring:()=>kU,pipeline:()=>EU,preprocess:()=>SU,promise:()=>vU,quotelessJson:()=>wB,record:()=>pU,set:()=>fU,setErrorMap:()=>SB,strictObject:()=>aU,string:()=>mI,symbol:()=>YB,transformer:()=>xU,tuple:()=>uU,undefined:()=>QB,union:()=>sU,unknown:()=>rU,util:()=>ge,void:()=>iU});var ge;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),a={};for(let s of o)a[s]=i[s];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},t.find=(i,o)=>{for(let a of i)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ge||(ge={}));var Fb;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Fb||(Fb={}));var L=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),bn=t=>{switch(typeof t){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(t)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":return Array.isArray(t)?L.array:t===null?L.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?L.promise:typeof Map<"u"&&t instanceof Map?L.map:typeof Set<"u"&&t instanceof Set?L.set:typeof Date<"u"&&t instanceof Date?L.date:L.object;default:return L.unknown}};var N=ge.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wB=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),nr=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let s=n,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(r(a))):s[l]=s[l]||{_errors:[]},s=s[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ge.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};nr.create=t=>new nr(t);var _B=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===L.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ge.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${ge.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ge.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${ge.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ge.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,ge.assertNever(t)}return{message:r}},Ln=_B;var aI=Ln;function SB(t){aI=t}function Na(){return aI}var Fc=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let s="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)s=l(a,{data:e,defaultError:s}).message;return{...i,path:o,message:s}},EB=[];function z(t,e){let r=Na(),n=Fc({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ln?void 0:Ln].filter(i=>!!i)});t.common.issues.push(n)}var wt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return G;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,a=await i.value;n.push({key:o,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return G;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}},G=Object.freeze({status:"aborted"}),so=t=>({status:"dirty",value:t}),It=t=>({status:"valid",value:t}),Kp=t=>t.status==="aborted",Wp=t=>t.status==="dirty",gi=t=>t.status==="valid",Ma=t=>typeof Promise<"u"&&t instanceof Promise;var B;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}));var Ir=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},sI=(t,e)=>{if(gi(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new nr(t.common.issues);return this._error=r,this._error}}};function ne(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,s)=>{let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:i}}var ae=class{get description(){return this._def.description}_getType(e){return bn(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:bn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new wt,ctx:{common:e.parent.common,data:e.data,parsedType:bn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ma(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bn(e)},i=this._parseSync({data:e,path:n.path,parent:n});return sI(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bn(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return gi(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>gi(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bn(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(Ma(i)?i:Promise.resolve(i));return sI(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let a=e(i),s=()=>o.addIssue({code:N.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Rr({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ir.create(this,this._def)}nullable(){return xn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Vn.create(this)}promise(){return vi.create(this,this._def)}or(e){return ho.create([this,e],this._def)}and(e){return go.create(this,e,this._def)}transform(e){return new Rr({...ne(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new wo({...ne(this._def),innerType:this,defaultValue:r,typeName:M.ZodDefault})}brand(){return new zc({typeName:M.ZodBranded,type:this,...ne(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new _o({...ne(this._def),innerType:this,catchValue:r,typeName:M.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Lc.create(this,e)}readonly(){return So.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kB=/^c[^\s-]{8,}$/i,TB=/^[0-9a-z]+$/,CB=/^[0-9A-HJKMNP-TV-Z]{26}$/i,AB=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,IB=/^[a-z0-9_-]{21}$/i,RB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,PB=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$B=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",zb,NB=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,MB=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,DB=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,FB=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zB=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,LB=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lI="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",jB=new RegExp(`^${lI}$`);function uI(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function qB(t){return new RegExp(`^${uI(t)}$`)}function pI(t){let e=`${lI}T${uI(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function VB(t,e){return!!((e==="v4"||!e)&&NB.test(t)||(e==="v6"||!e)&&DB.test(t))}function BB(t,e){if(!RB.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function UB(t,e){return!!((e==="v4"||!e)&&MB.test(t)||(e==="v6"||!e)&&FB.test(t))}var yi=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let o=this._getOrReturnCtx(e);return z(o,{code:N.invalid_type,expected:L.string,received:o.parsedType}),G}let n=new wt,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,s=e.data.length<o.value;(a||s)&&(i=this._getOrReturnCtx(e,i),a?z(i,{code:N.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&z(i,{code:N.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")$B.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"email",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")zb||(zb=new RegExp(OB,"u")),zb.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"emoji",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")AB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"uuid",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")IB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"nanoid",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")kB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cuid",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")TB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cuid2",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")CB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"ulid",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),z(i,{validation:"url",code:N.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"regex",code:N.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?pI(o).test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?jB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?qB(o).test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?PB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"duration",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?VB(e.data,o.version)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"ip",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?BB(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"jwt",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?UB(e.data,o.version)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cidr",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?zB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"base64",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?LB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"base64url",code:N.invalid_string,message:o.message}),n.dirty()):ge.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:N.invalid_string,...B.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...B.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...B.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...B.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...B.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...B.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...B.errToObj(r)})}nonempty(e){return this.min(1,B.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};yi.create=t=>new yi({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...ne(t)});function JB(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return o%a/10**i}var co=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==L.number){let o=this._getOrReturnCtx(e);return z(o,{code:N.invalid_type,expected:L.number,received:o.parsedType}),G}let n,i=new wt;for(let o of this._def.checks)o.kind==="int"?ge.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:N.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?JB(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_finite,message:o.message}),i.dirty()):ge.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ge.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};co.create=t=>new co({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...ne(t)});var lo=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==L.bigint)return this._getInvalidInput(e);let n,i=new wt;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ge.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return z(r,{code:N.invalid_type,expected:L.bigint,received:r.parsedType}),G}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};lo.create=t=>new lo({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...ne(t)});var uo=class extends ae{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.boolean,received:n.parsedType}),G}return It(e.data)}};uo.create=t=>new uo({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...ne(t)});var po=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let o=this._getOrReturnCtx(e);return z(o,{code:N.invalid_type,expected:L.date,received:o.parsedType}),G}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return z(o,{code:N.invalid_date}),G}let n=new wt,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ge.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:B.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:B.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};po.create=t=>new po({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...ne(t)});var Fa=class extends ae{_parse(e){if(this._getType(e)!==L.symbol){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.symbol,received:n.parsedType}),G}return It(e.data)}};Fa.create=t=>new Fa({typeName:M.ZodSymbol,...ne(t)});var fo=class extends ae{_parse(e){if(this._getType(e)!==L.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.undefined,received:n.parsedType}),G}return It(e.data)}};fo.create=t=>new fo({typeName:M.ZodUndefined,...ne(t)});var mo=class extends ae{_parse(e){if(this._getType(e)!==L.null){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.null,received:n.parsedType}),G}return It(e.data)}};mo.create=t=>new mo({typeName:M.ZodNull,...ne(t)});var bi=class extends ae{constructor(){super(...arguments),this._any=!0}_parse(e){return It(e.data)}};bi.create=t=>new bi({typeName:M.ZodAny,...ne(t)});var qn=class extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(e){return It(e.data)}};qn.create=t=>new qn({typeName:M.ZodUnknown,...ne(t)});var Gr=class extends ae{_parse(e){let r=this._getOrReturnCtx(e);return z(r,{code:N.invalid_type,expected:L.never,received:r.parsedType}),G}};Gr.create=t=>new Gr({typeName:M.ZodNever,...ne(t)});var za=class extends ae{_parse(e){if(this._getType(e)!==L.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.void,received:n.parsedType}),G}return It(e.data)}};za.create=t=>new za({typeName:M.ZodVoid,...ne(t)});var Vn=class t extends ae{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==L.array)return z(r,{code:N.invalid_type,expected:L.array,received:r.parsedType}),G;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,s=r.data.length<i.exactLength.value;(a||s)&&(z(r,{code:a?N.too_big:N.too_small,minimum:s?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(z(r,{code:N.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(z(r,{code:N.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,s)=>i.type._parseAsync(new Ir(r,a,r.path,s)))).then(a=>wt.mergeArray(n,a));let o=[...r.data].map((a,s)=>i.type._parseSync(new Ir(r,a,r.path,s)));return wt.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:B.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:B.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:B.toString(r)}})}nonempty(e){return this.min(1,e)}};Vn.create=(t,e)=>new Vn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ne(e)});function Da(t){if(t instanceof or){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ir.create(Da(n))}return new or({...t._def,shape:()=>e})}else return t instanceof Vn?new Vn({...t._def,type:Da(t.element)}):t instanceof ir?ir.create(Da(t.unwrap())):t instanceof xn?xn.create(Da(t.unwrap())):t instanceof vn?vn.create(t.items.map(e=>Da(e))):t}var or=class t extends ae{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ge.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==L.object){let l=this._getOrReturnCtx(e);return z(l,{code:N.invalid_type,expected:L.object,received:l.parsedType}),G}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Gr&&this._def.unknownKeys==="strip"))for(let l in i.data)a.includes(l)||s.push(l);let c=[];for(let l of a){let u=o[l],p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ir(i,p,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof Gr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of s)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")s.length>0&&(z(i,{code:N.unrecognized_keys,keys:s}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of s){let p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ir(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,f=await u.value;l.push({key:p,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>wt.mergeObjectSync(n,l)):wt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return B.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:B.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ge.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ge.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Da(this)}partial(e){let r={};for(let n of ge.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ge.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ir;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return dI(ge.objectKeys(this.shape))}};or.create=(t,e)=>new or({shape:()=>t,unknownKeys:"strip",catchall:Gr.create(),typeName:M.ZodObject,...ne(e)});or.strictCreate=(t,e)=>new or({shape:()=>t,unknownKeys:"strict",catchall:Gr.create(),typeName:M.ZodObject,...ne(e)});or.lazycreate=(t,e)=>new or({shape:t,unknownKeys:"strip",catchall:Gr.create(),typeName:M.ZodObject,...ne(e)});var ho=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(s=>new nr(s.ctx.common.issues));return z(r,{code:N.invalid_union,unionErrors:a}),G}if(r.common.async)return Promise.all(n.map(async o=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let s=a.map(c=>new nr(c));return z(r,{code:N.invalid_union,unionErrors:s}),G}}get options(){return this._def.options}};ho.create=(t,e)=>new ho({options:t,typeName:M.ZodUnion,...ne(e)});var jn=t=>t instanceof yo?jn(t.schema):t instanceof Rr?jn(t.innerType()):t instanceof bo?[t.value]:t instanceof vo?t.options:t instanceof xo?ge.objectValues(t.enum):t instanceof wo?jn(t._def.innerType):t instanceof fo?[void 0]:t instanceof mo?[null]:t instanceof ir?[void 0,...jn(t.unwrap())]:t instanceof xn?[null,...jn(t.unwrap())]:t instanceof zc||t instanceof So?jn(t.unwrap()):t instanceof _o?jn(t._def.innerType):[],Gp=class t extends ae{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.object)return z(r,{code:N.invalid_type,expected:L.object,received:r.parsedType}),G;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(z(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let a=jn(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of a){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,o)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...ne(n)})}};function Lb(t,e){let r=bn(t),n=bn(e);if(t===e)return{valid:!0,data:t};if(r===L.object&&n===L.object){let i=ge.objectKeys(e),o=ge.objectKeys(t).filter(s=>i.indexOf(s)!==-1),a={...t,...e};for(let s of o){let c=Lb(t[s],e[s]);if(!c.valid)return{valid:!1};a[s]=c.data}return{valid:!0,data:a}}else if(r===L.array&&n===L.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let a=t[o],s=e[o],c=Lb(a,s);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===L.date&&n===L.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var go=class extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,a)=>{if(Kp(o)||Kp(a))return G;let s=Lb(o.value,a.value);return s.valid?((Wp(o)||Wp(a))&&r.dirty(),{status:r.value,value:s.data}):(z(n,{code:N.invalid_intersection_types}),G)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};go.create=(t,e,r)=>new go({left:t,right:e,typeName:M.ZodIntersection,...ne(r)});var vn=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.array)return z(n,{code:N.invalid_type,expected:L.array,received:n.parsedType}),G;if(n.data.length<this._def.items.length)return z(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G;!this._def.rest&&n.data.length>this._def.items.length&&(z(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((a,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new Ir(n,a,n.path,s)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>wt.mergeArray(r,a)):wt.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};vn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vn({items:t,typeName:M.ZodTuple,rest:null,...ne(e)})};var Xp=class t extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return z(n,{code:N.invalid_type,expected:L.object,received:n.parsedType}),G;let i=[],o=this._def.keyType,a=this._def.valueType;for(let s in n.data)i.push({key:o._parse(new Ir(n,s,n.path,s)),value:a._parse(new Ir(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?wt.mergeObjectAsync(r,i):wt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ae?new t({keyType:e,valueType:r,typeName:M.ZodRecord,...ne(n)}):new t({keyType:yi.create(),valueType:e,typeName:M.ZodRecord,...ne(r)})}},La=class extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.map)return z(n,{code:N.invalid_type,expected:L.map,received:n.parsedType}),G;let i=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([s,c],l)=>({key:i._parse(new Ir(n,s,n.path,[l,"key"])),value:o._parse(new Ir(n,c,n.path,[l,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let c of a){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return G;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of a){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return G;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}}}};La.create=(t,e,r)=>new La({valueType:e,keyType:t,typeName:M.ZodMap,...ne(r)});var ja=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.set)return z(n,{code:N.invalid_type,expected:L.set,received:n.parsedType}),G;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(z(n,{code:N.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(z(n,{code:N.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function a(c){let l=new Set;for(let u of c){if(u.status==="aborted")return G;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let s=[...n.data.values()].map((c,l)=>o._parse(new Ir(n,c,n.path,l)));return n.common.async?Promise.all(s).then(c=>a(c)):a(s)}min(e,r){return new t({...this._def,minSize:{value:e,message:B.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:B.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ja.create=(t,e)=>new ja({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...ne(e)});var Yp=class t extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.function)return z(r,{code:N.invalid_type,expected:L.function,received:r.parsedType}),G;function n(s,c){return Fc({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Na(),Ln].filter(l=>!!l),issueData:{code:N.invalid_arguments,argumentsError:c}})}function i(s,c){return Fc({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Na(),Ln].filter(l=>!!l),issueData:{code:N.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof vi){let s=this;return It(async function(...c){let l=new nr([]),u=await s._def.args.parseAsync(c,o).catch(h=>{throw l.addIssue(n(c,h)),l}),p=await Reflect.apply(a,this,u);return await s._def.returns._def.type.parseAsync(p,o).catch(h=>{throw l.addIssue(i(p,h)),l})})}else{let s=this;return It(function(...c){let l=s._def.args.safeParse(c,o);if(!l.success)throw new nr([n(c,l.error)]);let u=Reflect.apply(a,this,l.data),p=s._def.returns.safeParse(u,o);if(!p.success)throw new nr([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:vn.create(e).rest(qn.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||vn.create([]).rest(qn.create()),returns:r||qn.create(),typeName:M.ZodFunction,...ne(n)})}},yo=class extends ae{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};yo.create=(t,e)=>new yo({getter:t,typeName:M.ZodLazy,...ne(e)});var bo=class extends ae{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return z(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};bo.create=(t,e)=>new bo({value:t,typeName:M.ZodLiteral,...ne(e)});function dI(t,e){return new vo({values:t,typeName:M.ZodEnum,...ne(e)})}var vo=class t extends ae{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{expected:ge.joinValues(n),received:r.parsedType,code:N.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{received:r.data,code:N.invalid_enum_value,options:n}),G}return It(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};vo.create=dI;var xo=class extends ae{_parse(e){let r=ge.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==L.string&&n.parsedType!==L.number){let i=ge.objectValues(r);return z(n,{expected:ge.joinValues(i),received:n.parsedType,code:N.invalid_type}),G}if(this._cache||(this._cache=new Set(ge.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ge.objectValues(r);return z(n,{received:n.data,code:N.invalid_enum_value,options:i}),G}return It(e.data)}get enum(){return this._def.values}};xo.create=(t,e)=>new xo({values:t,typeName:M.ZodNativeEnum,...ne(e)});var vi=class extends ae{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.promise&&r.common.async===!1)return z(r,{code:N.invalid_type,expected:L.promise,received:r.parsedType}),G;let n=r.parsedType===L.promise?r.data:Promise.resolve(r.data);return It(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};vi.create=(t,e)=>new vi({type:t,typeName:M.ZodPromise,...ne(e)});var Rr=class extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:a=>{z(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async s=>{if(r.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?G:c.status==="dirty"?so(c.value):r.value==="dirty"?so(c.value):c});{if(r.value==="aborted")return G;let s=this._def.schema._parseSync({data:a,path:n.path,parent:n});return s.status==="aborted"?G:s.status==="dirty"?so(s.value):r.value==="dirty"?so(s.value):s}}if(i.type==="refinement"){let a=s=>{let c=i.refinement(s,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?G:(s.status==="dirty"&&r.dirty(),a(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?G:(s.status==="dirty"&&r.dirty(),a(s.value).then(()=>({status:r.value,value:s.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!gi(a))return G;let s=i.transform(a.value,o);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>gi(a)?Promise.resolve(i.transform(a.value,o)).then(s=>({status:r.value,value:s})):G);ge.assertNever(i)}};Rr.create=(t,e,r)=>new Rr({schema:t,typeName:M.ZodEffects,effect:e,...ne(r)});Rr.createWithPreprocess=(t,e,r)=>new Rr({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...ne(r)});var ir=class extends ae{_parse(e){return this._getType(e)===L.undefined?It(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ir.create=(t,e)=>new ir({innerType:t,typeName:M.ZodOptional,...ne(e)});var xn=class extends ae{_parse(e){return this._getType(e)===L.null?It(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xn.create=(t,e)=>new xn({innerType:t,typeName:M.ZodNullable,...ne(e)});var wo=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===L.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};wo.create=(t,e)=>new wo({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ne(e)});var _o=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ma(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new nr(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new nr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};_o.create=(t,e)=>new _o({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ne(e)});var qa=class extends ae{_parse(e){if(this._getType(e)!==L.nan){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.nan,received:n.parsedType}),G}return{status:"valid",value:e.data}}};qa.create=t=>new qa({typeName:M.ZodNaN,...ne(t)});var HB=Symbol("zod_brand"),zc=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Lc=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?G:o.status==="dirty"?(r.dirty(),so(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?G:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:M.ZodPipeline})}},So=class extends ae{_parse(e){let r=this._def.innerType._parse(e),n=i=>(gi(i)&&(i.value=Object.freeze(i.value)),i);return Ma(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};So.create=(t,e)=>new So({innerType:t,typeName:M.ZodReadonly,...ne(e)});function cI(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function fI(t,e={},r){return t?bi.create().superRefine((n,i)=>{let o=t(n);if(o instanceof Promise)return o.then(a=>{if(!a){let s=cI(e,n),c=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:c})}});if(!o){let a=cI(e,n),s=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:s})}}):bi.create()}var ZB={object:or.lazycreate},M;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));var KB=(t,e={message:`Input not instance of ${t.name}`})=>fI(r=>r instanceof t,e),mI=yi.create,hI=co.create,WB=qa.create,GB=lo.create,gI=uo.create,XB=po.create,YB=Fa.create,QB=fo.create,eU=mo.create,tU=bi.create,rU=qn.create,nU=Gr.create,iU=za.create,oU=Vn.create,jb=or.create,aU=or.strictCreate,sU=ho.create,cU=Gp.create,lU=go.create,uU=vn.create,pU=Xp.create,dU=La.create,fU=ja.create,mU=Yp.create,hU=yo.create,gU=bo.create,yU=vo.create,bU=xo.create,vU=vi.create,xU=Rr.create,wU=ir.create,_U=xn.create,SU=Rr.createWithPreprocess,EU=Lc.create,kU=()=>mI().optional(),TU=()=>hI().optional(),CU=()=>gI().optional(),AU={string:t=>yi.create({...t,coerce:!0}),number:t=>co.create({...t,coerce:!0}),boolean:t=>uo.create({...t,coerce:!0}),bigint:t=>lo.create({...t,coerce:!0}),date:t=>po.create({...t,coerce:!0})};var IU=G;var PU=$("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");$e.init(t,e),t.def=e,t.parse=(r,n)=>Ff(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>ji(t,r,n),t.parseAsync=async(r,n)=>Lf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>qi(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>gr(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)});var $U=$("ZodMiniObject",(t,e)=>{jl.init(t,e),PU.init(t,e),ye.defineLazy(t,"shape",()=>e.shape)});function qb(t,e){let r={type:"object",get shape(){return ye.assignProp(this,"shape",{...t}),this.shape},...ye.normalizeParams(e)};return new $U(r)}function Pr(t){return!!t._zod}function Eo(t){let e=Object.values(t);if(e.length===0)return qb({});let r=e.every(Pr),n=e.every(i=>!Pr(i));if(r)return qb(t);if(n)return jb(t);throw new Error("Mixed Zod versions detected in object shape.")}function xi(t,e){return Pr(t)?ji(t,e):t.safeParse(e)}async function Qp(t,e){return Pr(t)?await qi(t,e):await t.safeParseAsync(e)}function wi(t){if(!t)return;let e;if(Pr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Va(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(i=>typeof i=="object"&&i!==null&&(i._def!==void 0||i._zod!==void 0||typeof i.parse=="function")))return Eo(t)}}if(Pr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function ed(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function yI(t){return t.description}function bI(t){if(Pr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function td(t){if(Pr(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}function _i(t){return t==="completed"||t==="failed"||t==="cancelled"}var xI=Symbol("Let zodToJsonSchema decide on which parser to use");var vI={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},wI=t=>typeof t=="string"?{...vI,name:t}:{...vI,...t};var _I=t=>{let e=wI(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Vb(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,i){t[e]=r,Vb(t,e,n,i)}var rd=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?rd(e,t.currentPath):e.join("/")}}function SI(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==M.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function EI(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}function kI(){return{type:"boolean"}}function nd(t,e){return Y(t.type._def,e)}var TI=(t,e)=>Y(t.innerType._def,e);function Bb(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>Bb(t,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return NU(t,e)}}var NU=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r};function CI(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}function AI(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):Ke(e)}function II(t){return{type:"string",enum:Array.from(t.values)}}var MU=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function RI(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(o=>{if(MU(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:s,...c}=o;a=c}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function PI(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Ub,Xr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ub===void 0&&(Ub=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ub),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function id(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Yr(r,"email",n.message,e);break;case"format:idn-email":Yr(r,"idn-email",n.message,e);break;case"pattern:zod":Vt(r,Xr.email,n.message,e);break}break;case"url":Yr(r,"uri",n.message,e);break;case"uuid":Yr(r,"uuid",n.message,e);break;case"regex":Vt(r,n.regex,n.message,e);break;case"cuid":Vt(r,Xr.cuid,n.message,e);break;case"cuid2":Vt(r,Xr.cuid2,n.message,e);break;case"startsWith":Vt(r,RegExp(`^${Jb(n.value,e)}`),n.message,e);break;case"endsWith":Vt(r,RegExp(`${Jb(n.value,e)}$`),n.message,e);break;case"datetime":Yr(r,"date-time",n.message,e);break;case"date":Yr(r,"date",n.message,e);break;case"time":Yr(r,"time",n.message,e);break;case"duration":Yr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Vt(r,RegExp(Jb(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Yr(r,"ipv4",n.message,e),n.version!=="v4"&&Yr(r,"ipv6",n.message,e);break}case"base64url":Vt(r,Xr.base64url,n.message,e);break;case"jwt":Vt(r,Xr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Vt(r,Xr.ipv4Cidr,n.message,e),n.version!=="v4"&&Vt(r,Xr.ipv6Cidr,n.message,e);break}case"emoji":Vt(r,Xr.emoji(),n.message,e);break;case"ulid":{Vt(r,Xr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Yr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Vt(r,Xr.base64,n.message,e);break}}break}case"nanoid":Vt(r,Xr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Jb(t,e){return e.patternStrategy==="escape"?FU(t):t}var DU=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function FU(t){let e="";for(let r=0;r<t.length;r++)DU.has(t[r])||(e+="\\"),e+=t[r];return e}function Yr(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):xe(t,"format",e,r,n)}function Vt(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:$I(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",$I(e,n),r,n)}function $I(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,i="",o=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(o){i+=n[c],o=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){s?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],s=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
|
|
126
|
+
`).trim()}function Nb(t){return t?.V8Limit!==void 0&&t.V8Limit!==null?Number(t.V8Limit)===1?1:0:t?.V8Unlimited!==void 0&&t.V8Unlimited!==null?Number(t.V8Unlimited)===1?0:1:0}function Up(t){if(t===void 0)return;let e=(Array.isArray(t)?t:String(t).split(";")).map(r=>String(r||"").trim()).filter(Boolean);return Array.from(new Set(e.map(r=>r.toLowerCase()))).map(r=>e.find(n=>n.toLowerCase()===r)||r).join(";")}function Db(t){if(Array.isArray(t))return t.map(Db);if(!t||typeof t!="object")return t;let e=Object.entries(t).filter(([r])=>!r.startsWith("_")).sort(([r],[n])=>r.localeCompare(n));return Object.fromEntries(e.map(([r,n])=>[r,Db(n)]))}function rI(t){try{let e=typeof t=="string"?JSON.parse(t):t;return JSON.stringify(Db(e))}catch{return}}function xB(t,e){let r=new Set(["OsClient","ModuleId","Id"]),n=[];for(let[i,o]of Object.entries(t)){if(r.has(i)||o===void 0)continue;let a=e[i];if(yB.has(i)||i==="ViewSchema"){let s=rI(o),c=rI(a);(!s||!c||s!==c)&&n.push(i);continue}String(o??"")!==String(a??"")&&n.push(i)}return{matched:n.length===0,mismatches:n}}var Dc=class{config;token="";refreshTimer;rsaPublicKey;did;requestTimeoutMs;writeRequestTimeoutMs;readbackRequestTimeoutMs;inflightRefresh;inflightAuthRecovery;inflightCredentialRecovery;constructor(e){this.config=e,this.reloadWorkspaceCredentials(),this.rsaPublicKey=e.rsaPublicKey||aB,this.did=LA(process.env.MICROI_MCP_DID,nI.default.hostname()),this.requestTimeoutMs=Bp(e.requestTimeoutMs??process.env.MICROI_MCP_HTTP_TIMEOUT_MS,lB),this.writeRequestTimeoutMs=Bp(e.writeRequestTimeoutMs??process.env.MICROI_MCP_WRITE_TIMEOUT_MS,uB),this.readbackRequestTimeoutMs=Bp(e.readbackRequestTimeoutMs??process.env.MICROI_MCP_READBACK_TIMEOUT_MS,pB),e.token&&(this.token=vr(e.token))}rsaEncrypt(e){let r=(this.rsaPublicKey||"").trim();return r?zn.default.publicEncrypt({key:r,padding:zn.default.constants.RSA_PKCS1_PADDING},Buffer.from(e,"utf-8")).toString("base64"):e}updateToken(e){this.token=vr(e)}async login(e){if(this.token){this.startAutoRefresh(),console.error("[microi-mcp] Using provided token (auto-refresh enabled)");return}if(this.reloadWorkspaceCredentials(),!this.config.username||!this.config.password)throw new Error("Login credentials are unavailable from environment or workspace protected storage");let r=this.rsaEncrypt(this.config.password),n=new URLSearchParams;n.append("Account",this.config.username),n.append("Pwd",r),this.config.osClient&&n.append("OsClient",this.config.osClient),n.append("_ClientType","MCP");let i=await fetch(`${this.config.apiBaseUrl}${O.LOGIN}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{}},body:n.toString()}),o=i.headers.get("authorization")||"",a=await i.text();if(!i.ok||!a)throw new Error(`Login failed: HTTP ${i.status} \u2014 ${a?.slice(0,200)||"empty response"}`);let s;try{s=JSON.parse(a)}catch{throw new Error(`Login failed: invalid JSON \u2014 ${a.slice(0,200)}`)}if(s.Code!==1)throw new Error(`Login failed: ${s.Msg||"Unknown error"}`);if(!o)throw new Error("Login succeeded but no token in response header");this.token=vr(o),this.startAutoRefresh(),console.error("[microi-mcp] Login successful")}startAutoRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=setInterval(()=>{qA(this.token)&&this.refreshTokenNow().catch(e=>console.error("[microi-mcp] Token refresh failed:",e))},60*60*1e3)}async refreshTokenNow(){return this.inflightRefresh?this.inflightRefresh:this.token?(this.inflightRefresh=(async()=>{try{let e=await fetch(`${this.config.apiBaseUrl}${O.REFRESH_TOKEN}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{}},body:JSON.stringify({authorization:this.token,OsClient:this.config.osClient||void 0,_ClientType:"MCP"})}),r=e.headers.get("authorization"),n=await e.text(),i=null;try{i=JSON.parse(n)}catch{}return r&&i?.Code===1?(this.token=vr(r),this.writeTokenToFile(),console.error("[microi-mcp] Token refreshed"),!0):(console.error(`[microi-mcp] Refresh rejected: Code=${i?.Code} Msg=${i?.Msg||""}`),!1)}catch(e){return console.error("[microi-mcp] Refresh request error:",e),!1}finally{this.inflightRefresh=void 0}})(),this.inflightRefresh):!1}reloadTokenFromFile(){let e=this.config.tokenFilePath;if(!e)return!1;try{let r=JSON.parse(At.default.readFileSync(e,"utf-8")),n=Zp(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork),i=String(this.config.apiBaseUrl||"").replace(/\/+$/,""),o=this.config.osClient?n.filter(c=>c!==i):n,a=Lp(o.map(c=>Ra(r[c])))||Ra(r[i]),s=vr(a);if(s&&s!==this.token)return this.token=s,!0}catch{}return!1}writeTokenToFile(){let e=this.config.tokenFilePath;if(!(!e||!this.token))try{let r={};try{r=JSON.parse(At.default.readFileSync(e,"utf-8"))}catch{}let n=Zp(this.config.apiBaseUrl,this.config.osClient,this.config.osClientType,this.config.osClientNetwork),i=n[0];if(!i)return;r[i]=n.some(a=>Vp(r[a]))?YA(this.token):this.token;let o=Oa.default.dirname(e);At.default.existsSync(o)||At.default.mkdirSync(o,{recursive:!0}),At.default.writeFileSync(e,JSON.stringify(r,null,2),{encoding:"utf-8",mode:384})}catch(r){console.error("[microi-mcp] Write token file failed:",r)}}async requestVsCodeCredentialRecovery(e){let r=this.config.authRecoveryRequestDir,n=this.config.tokenFilePath;if(!r||!n)return!1;try{At.default.existsSync(r)||At.default.mkdirSync(r,{recursive:!0});let i=this.config.apiBaseUrl.replace(/\/+$/,""),o=this.config.osClient||"",a=this.config.osClientType||"",s=this.config.osClientNetwork||"",c=`${i}|${o}|${a}|${s}`,u=`${zn.default.createHash("sha256").update(c).digest("hex").slice(0,24)}-${process.pid}-${Date.now()}-${zn.default.randomBytes(4).toString("hex")}.json`,p=Oa.default.join(r,u),f=`${p}.${process.pid}.tmp`,h={version:1,apiBaseUrl:i,osClient:o,osClientType:a,osClientNetwork:s,requestedAt:Date.now(),failedTokenHash:zn.default.createHash("sha256").update(e||"").digest("hex")};At.default.writeFileSync(f,JSON.stringify(h),{encoding:"utf-8",mode:384}),At.default.renameSync(f,p);for(let m=0;m<40;m++)if(await new Promise(g=>setTimeout(g,250)),this.reloadTokenFromFile())return console.error("[microi-mcp] Token recovered by VS Code SecretStorage broker"),!0}catch(i){console.error("[microi-mcp] VS Code credential recovery request failed:",i)}return!1}async tryRecoverFromAuthFailure(e,r=!1){if(this.token&&e&&this.token!==e)return!0;if(r){if(this.inflightCredentialRecovery)return this.inflightCredentialRecovery;let n=this.inflightAuthRecovery;this.inflightCredentialRecovery=(async()=>(n&&await n,this.token&&e&&this.token!==e?!0:this.tryRecoverFromAuthFailureCore(e,!0)))();try{return await this.inflightCredentialRecovery}finally{this.inflightCredentialRecovery=void 0}}if(this.inflightCredentialRecovery)return this.inflightCredentialRecovery;if(this.inflightAuthRecovery)return this.inflightAuthRecovery;this.inflightAuthRecovery=this.tryRecoverFromAuthFailureCore(e,!1);try{return await this.inflightAuthRecovery}finally{this.inflightAuthRecovery=void 0}}async tryRecoverFromAuthFailureCore(e,r){if(this.token&&e&&this.token!==e)return!0;if(this.reloadTokenFromFile())return console.error("[microi-mcp] Token reloaded from file after auth failure"),!0;if(!r&&await this.refreshTokenNow())return!0;if(this.reloadWorkspaceCredentials(),this.config.username&&this.config.password)try{if(this.token="",await this.login(),this.token&&this.token!==e)return this.writeTokenToFile(),console.error("[microi-mcp] Re-logged in after auth failure"),!0}catch(n){this.token=e,console.error("[microi-mcp] Re-login failed:",n)}return this.requestVsCodeCredentialRecovery(e)}reloadWorkspaceCredentials(){let e=QA({filePath:this.config.workspaceCredentialFilePath,usernameKey:this.config.workspaceCredentialUsernameKey,passwordKey:this.config.workspaceCredentialPasswordKey});return e?(this.config.username=e.username,this.config.password=e.password,!0):!1}async post(e,r,n={}){return this.requestJson("POST",e,r,void 0,"initial",n)}async get(e,r,n={}){return this.requestJson("GET",e,void 0,r,"initial",n)}async requestJson(e,r,n,i,o="initial",a={}){let s=`${this.config.apiBaseUrl}${r}`;if(e==="GET"&&i){let b=new URLSearchParams(i).toString();b&&(s+=`?${b}`)}let c=this.token,l={Authorization:`Bearer ${c}`,did:this.did};this.config.osClient&&(l.OsClient=this.config.osClient),e==="POST"&&(l["Content-Type"]="application/json");let u=Bp(a.timeoutMs,this.requestTimeoutMs,a.maxTimeoutMs),p=a.operationName||`${e} ${r}`,f=new AbortController,h=setTimeout(()=>f.abort(),u),m,g,y=e==="POST"?JSON.stringify(n??{}):void 0;try{let b=await fetch(s,{method:e,headers:l,signal:f.signal,...y!==void 0?{body:y}:{}});m=b,g=await b.text()}catch(b){if(f.signal.aborted)throw new yn(`${p} \u8BF7\u6C42\u8D85\u65F6\uFF08${u}ms\uFF09`,{kind:"timeout",requestPath:r,uncertainOutcome:e==="POST",cause:b});if(a.allowNativeFallback===!1)throw new yn(`${p} \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1Afetch=${b instanceof Error?b.message:String(b)}\uFF1B\u5DF2\u7981\u7528\u975E\u5E42\u7B49\u4F20\u8F93\u91CD\u653E`,{kind:"network",requestPath:r,uncertainOutcome:e==="POST",cause:b});try{await new Promise(S=>setTimeout(S,250));let E=await this.requestJsonNative(e,s,l,y,u);m=E.res,g=E.text}catch(E){let S=b instanceof Error?b.message:String(b),k=E instanceof Error?E.message:String(E);throw new yn(`${p} \u7F51\u7EDC\u8BF7\u6C42\u5931\u8D25\uFF1Afetch=${S}\uFF1Bnative=${k}`,{kind:"network",requestPath:r,uncertainOutcome:e==="POST",cause:E})}}finally{clearTimeout(h)}let v=m.headers.get("authorization");if(v&&(this.token=vr(v),this.writeTokenToFile()),m.status===401&&o!=="credential-token"){let b=o!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestJson(e,r,n,i,Pa(o),a);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${g.slice(0,200)}`)}if(!m.ok)throw new Error(`HTTP ${m.status} ${m.statusText} \u2014 ${g.slice(0,200)}`);if(!g)throw new Error(`HTTP ${m.status} \u2014 empty response body`);let x;try{x=JSON.parse(g)}catch{throw new Error(`HTTP ${m.status} \u2014 invalid JSON: ${g.slice(0,200)}`)}if(Ob(x)&&o!=="credential-token"){console.error(`[microi-mcp] Auth expired (Code=${x.Code}: ${x.Msg||""}), attempting recovery...`);let b=o!=="initial";if(b&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(c,b))return this.requestJson(e,r,n,i,Pa(o),a)}return x}async requestMultipartFile(e,r,n,i,o="initial",a,s,c=!0){let l=this.token,u=s==="gzip"?{...r,ContentEncoding:"gzip"}:r,p=`----microi-mcp-${zn.default.randomBytes(24).toString("hex")}`,f=tI(u,n,i,p,s),h=new AbortController,m=eI(a),g=setTimeout(()=>h.abort(),m),y,v;try{let w=await fetch(`${this.config.apiBaseUrl}${e}`,{method:"POST",headers:{Authorization:`Bearer ${l}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${p}`,...s===void 0?{"Content-Length":String(f.contentLength)}:{}},body:f.body,duplex:"half",signal:h.signal});y=w,v=await w.text()}catch(w){if(h.signal.aborted)throw new yn(`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u8D85\u65F6\uFF08${m}ms\uFF09`,{kind:"timeout",requestPath:e,uncertainOutcome:!0,cause:w});try{await new Promise(k=>setTimeout(k,250));let S=await this.requestMultipartFileNative(e,u,n,i,m,s);y=S.res,v=S.text}catch(S){let k=w instanceof Error?w.message:String(w),A=S instanceof Error?S.message:String(S);if(c&&s!=="gzip")try{return await this.requestMultipartFile(e,r,n,i,o,a,"gzip",c)}catch(R){let I=R instanceof Error?R.message:String(R);throw new yn(`\u5E94\u7528\u8D44\u4EA7\u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1Afetch=${k}\uFF1Bnative=${A}\uFF1Bgzip=${I}`,{kind:"network",requestPath:e,uncertainOutcome:!0,cause:R})}throw new yn(`${s==="gzip"?"\u5E94\u7528\u8D44\u4EA7 gzip":"\u539F\u59CB\u6587\u4EF6"}\u6D41\u5F0F\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1Afetch=${k}\uFF1Bnative=${A}`,{kind:"network",requestPath:e,uncertainOutcome:!0,cause:S})}}finally{clearTimeout(g),f.body.destroy()}let x=y.headers.get("authorization");if(x&&(this.token=vr(x),this.writeTokenToFile()),y.status===401&&o!=="credential-token"){let w=o!=="initial";if(w&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(l,w))return this.requestMultipartFile(e,r,n,i,Pa(o),a,s,c);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${v.slice(0,200)}`)}if(!y.ok)throw new Error(`HTTP ${y.status} ${y.statusText} \u2014 ${v.slice(0,200)}`);if(!v)throw new Error(`HTTP ${y.status} \u2014 empty response body`);let b;try{b=JSON.parse(v)}catch{throw new Error(`HTTP ${y.status} \u2014 invalid JSON: ${v.slice(0,200)}`)}if(Ob(b)&&o!=="credential-token"){let w=o!=="initial";if(w&&console.error("[microi-mcp] Replacement token was rejected; escalating to credential recovery"),await this.tryRecoverFromAuthFailure(l,w))return this.requestMultipartFile(e,r,n,i,Pa(o),a,s,c)}return b}async requestJsonNative(e,r,n,i,o){let a=new URL(r),s=a.protocol==="https:"?Hp.default:Jp.default,c=i===void 0?void 0:Buffer.from(i,"utf8");return new Promise((l,u)=>{let p=!1,f=m=>{p||(p=!0,u(m))},h=s.request({protocol:a.protocol,hostname:a.hostname,port:a.port||void 0,path:`${a.pathname}${a.search}`,method:e,timeout:o,headers:{...n,...c?{"Content-Length":String(c.length)}:{}}},m=>{let g=[];m.on("data",y=>g.push(Buffer.isBuffer(y)?y:Buffer.from(y))),m.on("end",()=>{if(p)return;p=!0;let y=m.statusCode||0,v={get(x){let b=m.headers[x.toLowerCase()];return Array.isArray(b)?b.join(", "):b===void 0?null:String(b)}};l({res:{status:y,statusText:m.statusMessage||"",ok:y>=200&&y<300,headers:v},text:Buffer.concat(g).toString("utf8")})})});h.on("error",m=>f(new Error(m.message,{cause:m}))),h.on("timeout",()=>{h.destroy(),f(new Error(`native request timeout (${o}ms)`))}),c&&h.write(c),h.end()})}async requestMultipartFileNative(e,r,n,i,o,a){let s=`----microi-mcp-native-${zn.default.randomBytes(24).toString("hex")}`,c=tI(r,n,i,s,a),l=new URL(`${this.config.apiBaseUrl}${e}`),u=l.protocol==="https:"?Hp.default:Jp.default;try{return await new Promise((p,f)=>{let h=!1,m=y=>{h||(h=!0,f(y))},g=u.request({protocol:l.protocol,hostname:l.hostname,port:l.port||void 0,path:`${l.pathname}${l.search}`,method:"POST",timeout:o,headers:{Authorization:`Bearer ${this.token}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":`multipart/form-data; boundary=${s}`,...a===void 0?{"Content-Length":String(c.contentLength)}:{}}},y=>{let v=[];y.on("data",x=>v.push(Buffer.isBuffer(x)?x:Buffer.from(x))),y.on("end",()=>{if(h)return;h=!0;let x=y.statusCode||0,b={get(w){let E=y.headers[w.toLowerCase()];return Array.isArray(E)?E.join(", "):E===void 0?null:String(E)}};p({res:{status:x,statusText:y.statusMessage||"",ok:x>=200&&x<300,headers:b},text:Buffer.concat(v).toString("utf8")})})});g.on("error",y=>m(new Error(y.message,{cause:y}))),g.on("timeout",()=>{g.destroy(),m(new Error(`native request timeout (${o}ms)`))}),c.body.on("error",y=>{g.destroy(),m(new Error(`local asset stream failed: ${y.message}`,{cause:y}))}),c.body.pipe(g)})}finally{c.body.destroy()}}async requestBinaryFileRange(e,r,n,i,o,a="initial",s){if(!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(o)||o<0)throw new Error("\u65AD\u70B9\u5206\u7247 start/length \u5FC5\u987B\u662F\u975E\u8D1F JavaScript \u5B89\u5168\u6574\u6570");let c=new URL(`${this.config.apiBaseUrl}${e}`);for(let[g,y]of Object.entries(r))c.searchParams.set(g,y);let l=this.token,u=eI(s),p=c.protocol==="https:"?Hp.default:Jp.default,f=await new Promise((g,y)=>{let v=!1,x=E=>{v||(v=!0,y(E))},b=p.request({protocol:c.protocol,hostname:c.hostname,port:c.port||void 0,path:`${c.pathname}${c.search}`,method:"POST",timeout:u,headers:{Authorization:`Bearer ${l}`,did:this.did,...this.config.osClient?{OsClient:this.config.osClient}:{},"Content-Type":"application/octet-stream","Content-Length":String(o)}},E=>{let S=[];E.on("data",k=>S.push(Buffer.isBuffer(k)?k:Buffer.from(k))),E.on("end",()=>{if(v)return;v=!0;let k=E.statusCode||0,A={get(R){let I=E.headers[R.toLowerCase()];return Array.isArray(I)?I.join(", "):I===void 0?null:String(I)}};g({status:k,statusText:E.statusMessage||"",headers:A,text:Buffer.concat(S).toString("utf8")})})});if(b.on("error",E=>x(new Error(E.message,{cause:E}))),b.on("timeout",()=>{b.destroy(),x(new Error(`\u65AD\u70B9\u5206\u7247\u7F51\u7EDC\u8D85\u65F6\uFF08${u}ms\uFF09`))}),o===0){b.end();return}let w=At.default.createReadStream(n,{start:i,end:i+o-1});w.on("error",E=>{b.destroy(),x(new Error(`\u8BFB\u53D6\u672C\u5730\u5206\u7247\u5931\u8D25\uFF1A${E.message}`,{cause:E}))}),w.pipe(b)}).catch(g=>{throw new yn(`\u65AD\u70B9\u5206\u7247\u4E0A\u4F20\u7F51\u7EDC\u5931\u8D25\uFF1A${g instanceof Error?g.message:String(g)}`,{kind:/超时/u.test(String(g))?"timeout":"network",requestPath:e,uncertainOutcome:!0,cause:g})}),h=f.headers.get("authorization");if(h&&(this.token=vr(h),this.writeTokenToFile()),f.status===401&&a!=="credential-token"){let g=a!=="initial";if(await this.tryRecoverFromAuthFailure(l,g))return this.requestBinaryFileRange(e,r,n,i,o,Pa(a),s);throw new Error(`HTTP 401 Unauthorized \u2014 token recovery failed: ${f.text.slice(0,200)}`)}if(f.status<200||f.status>=300)throw new Error(`HTTP ${f.status} ${f.statusText} \u2014 ${f.text.slice(0,200)}`);if(!f.text)throw new Error(`HTTP ${f.status} \u2014 empty response body`);let m;try{m=JSON.parse(f.text)}catch{throw new Error(`HTTP ${f.status} \u2014 invalid JSON: ${f.text.slice(0,200)}`)}if(Ob(m)&&a!=="credential-token"){let g=a!=="initial";if(await this.tryRecoverFromAuthFailure(l,g))return this.requestBinaryFileRange(e,r,n,i,o,Pa(a),s)}return m}isUncertainWriteError(e){return e instanceof yn&&e.uncertainOutcome}readbackOptions(e){return{timeoutMs:this.readbackRequestTimeoutMs,operationName:e}}async pollReadback(e,r){let n,i="";for(let o of dB){o>0&&await new Promise(a=>setTimeout(a,o));try{let a=await e();if(n=a,a.Code===1&&r(a.Data))return{matched:!0,response:a};i=a.Msg||`\u56DE\u8BFB Code=${a.Code}`}catch(a){i=a instanceof Error?a.message:String(a)}}return{matched:!1,response:n,lastError:i}}recoveredWriteResult(e,r,n={}){return{Code:1,Data:{...n,RecoveredAfterTransportError:!0,Verification:"readback",TransportError:r.message},Msg:`${e} \u7684\u5BA2\u6237\u7AEF\u54CD\u5E94\u5F02\u5E38\uFF0C\u4F46\u5DF2\u901A\u8FC7\u8FDC\u7AEF\u56DE\u8BFB\u786E\u8BA4\u5199\u5165\u6210\u529F\u3002`}}uncertainWriteFailure(e,r,n){return new Error(`${e} \u7684\u5BA2\u6237\u7AEF\u54CD\u5E94\u5F02\u5E38\uFF0C\u4E14\u56DE\u8BFB\u672A\u80FD\u786E\u8BA4\u5199\u5165\u7ED3\u679C\u3002\u539F\u59CB\u9519\u8BEF\uFF1A${r.message}${n?`\uFF1B\u56DE\u8BFB\u7ED3\u679C\uFF1A${n}`:""}\u3002\u8BF7\u7EE7\u7EED\u4F7F\u7528\u5BF9\u5E94\u7684\u6807\u51C6 MCP \u83B7\u53D6\u5DE5\u5177\u56DE\u8BFB\u540E\u518D\u51B3\u5B9A\u662F\u5426\u91CD\u8BD5\uFF1B\u4E0D\u8981\u6539\u8D70\u539F\u751F FormEngine\u3001\u76F4\u63A5 SQL \u6216\u4E34\u65F6\u7EF4\u62A4\u63A5\u53E3\u5F15\u64CE\u3002`,{cause:r})}async getStatus(){return this.get(O.GET_STATUS)}async getAdministrativeCapabilities(){return this.get(O.GET_ADMINISTRATIVE_CAPABILITIES)}async administerTableData(e){return this.post(O.ADMINISTER_TABLE_DATA,{OsClient:this.config.osClient,Operation:e.operation,TableName:e.tableName,...e.query?{Query:e.query}:{},...e.row?{Row:e.row}:{},...e.id?{Id:e.id}:{},...e.confirmExecution?{ConfirmExecution:e.confirmExecution}:{}})}async transitionApplicationStreamGate(e){return this.post(O.TRANSITION_APPLICATION_STREAM_GATE,e,{timeoutMs:this.writeRequestTimeoutMs,operationName:`transition application stream gate ${e.TransitionId}`})}async listMyUserAccessKeys(){return this.post(O.LIST_USER_ACCESS_KEYS,{})}async listServerPrivateSettings(){return this.post("/apiengine/platform-tenant-system-settings",{Action:"List"})}async saveServerPrivateSecret(e){return this.post("/api/TenantSystemSettings/Save",{ConfigKey:e.configKey,Value:e.value,Category:e.category||"\u7B2C\u4E09\u65B9\u670D\u52A1",Description:e.description||"",IsSecret:!0,IsPublic:!1,IsEnabled:!0,ValueType:"String"},{timeoutMs:this.writeRequestTimeoutMs,operationName:"\u4FDD\u5B58\u79DF\u6237\u540E\u7AEF Secret"})}async createMyUserAccessKey(e){return this.post(O.CREATE_USER_ACCESS_KEY,{Name:e.name,Scopes:e.scopes,AllowedRoutes:e.allowedRoutes,RedirectPath:e.redirectPath,AllowedTableNames:e.allowedTableNames,AllowedApiEngineKeys:e.allowedApiEngineKeys,AllowedDataSourceKeys:e.allowedDataSourceKeys,ExpiresAt:e.expiresAt,Remark:e.remark,Permanent:!1},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u521B\u5EFA\u5F53\u524D\u7528\u6237\u8BBF\u95EE\u5BC6\u94A5 ${e.name}`})}async revokeMyUserAccessKey(e){return this.post(O.REVOKE_USER_ACCESS_KEY,{Id:e},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u540A\u9500\u5F53\u524D\u7528\u6237\u8BBF\u95EE\u5BC6\u94A5 ${e}`})}async getDbSchema(){return this.post(O.GET_DB_SCHEMA,{OsClient:this.config.osClient})}async getTableIndexes(e,r=!1){return this.post(O.GET_TABLE_INDEXES,{OsClient:this.config.osClient,TableName:e},r?this.readbackOptions(`\u56DE\u8BFB\u8868 ${e} \u7D22\u5F15`):{})}async createTableIndex(e){let r={OsClient:this.config.osClient,...e};try{return await this.post(O.CREATE_TABLE_INDEX,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u521B\u5EFA\u7D22\u5F15 ${e.IndexName||`${e.TableName}:${e.Columns.join(",")}`}`})}catch(n){if(!this.isUncertainWriteError(n))throw n;let i=await this.pollReadback(()=>this.getTableIndexes(e.TableName,!0),o=>o.some(a=>{let s=e.IndexName?String(a.Key_name||a.Name||"").toLowerCase()===e.IndexName.toLowerCase():!0,c=a.Columns?.length?a.Columns:String(a.Column_name||"").split(",").map(u=>u.trim()).filter(Boolean),l=a.IsUnique??Number(a.Non_unique)===0;return s&&l===!!e.Unique&&c.length===e.Columns.length&&c.every((u,p)=>u.toLowerCase()===e.Columns[p].toLowerCase())}));if(i.matched)return this.recoveredWriteResult("\u521B\u5EFA\u6570\u636E\u5E93\u7D22\u5F15",n,{TableName:e.TableName,IndexName:e.IndexName,Columns:e.Columns});throw this.uncertainWriteFailure("\u521B\u5EFA\u6570\u636E\u5E93\u7D22\u5F15",n,i.lastError)}}async dropTableIndex(e,r){try{return await this.post(O.DROP_TABLE_INDEX,{OsClient:this.config.osClient,TableName:e,IndexName:r},{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u5220\u9664\u7D22\u5F15 ${r}`})}catch(n){if(!this.isUncertainWriteError(n))throw n;let i=await this.pollReadback(()=>this.getTableIndexes(e,!0),o=>!o.some(a=>String(a.Key_name||a.Name||"").toLowerCase()===r.toLowerCase()));if(i.matched)return this.recoveredWriteResult("\u5220\u9664\u6570\u636E\u5E93\u7D22\u5F15",n,{TableName:e,IndexName:r});throw this.uncertainWriteFailure("\u5220\u9664\u6570\u636E\u5E93\u7D22\u5F15",n,i.lastError)}}async getSupportedDatabaseTypes(){return this.post(O.GET_SUPPORTED_DATABASE_TYPES,{})}async inspectExternalDatabase(e){return this.post(O.INSPECT_EXTERNAL_DATABASE,{OsClient:this.config.osClient,...e})}async queryExternalDatabase(e){return this.post(O.QUERY_EXTERNAL_DATABASE,{OsClient:this.config.osClient,...e})}async executeExternalDatabaseSql(e){let r=Number(e.CommandTimeoutSeconds||0),n=Number.isFinite(r)&&r>0?(r+30)*1e3:63e4;return this.post(O.EXECUTE_EXTERNAL_DATABASE_SQL,{OsClient:this.config.osClient,...e},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,this.config.writeRequestTimeoutMs??6e4,n),operationName:"execute external database sql"})}async saveDatabaseConnection(e){return this.post(O.SAVE_DATABASE_CONNECTION,{OsClient:this.config.osClient,...e},{timeoutMs:this.config.writeRequestTimeoutMs,operationName:"save database connection"})}async importExternalAttachment(e){let r=Number(e.TimeoutSeconds||0),n=Number.isFinite(r)&&r>0?(r+30)*1e3:363e4;return this.post(O.IMPORT_EXTERNAL_ATTACHMENT,{OsClient:this.config.osClient,...e},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,this.config.writeRequestTimeoutMs??6e4,n),operationName:"import external attachment"})}async getPlaywrightContext(e,r){return this.post(O.GET_PLAYWRIGHT_CONTEXT,{OsClient:this.config.osClient,...e?{Keyword:e}:{},...r?{PageSize:r}:{}})}async getEngineList(e){return this.post(O.GET_ENGINE_LIST,{OsClient:this.config.osClient,...e?{_SearchKey:e}:{}})}async getEngineCode(e,r={}){return this.post(O.GET_ENGINE_CODE,{OsClient:this.config.osClient,ApiEngineKey:e},r)}async executeEngine(e,r){return this.post(O.EXECUTE_ENGINE,{OsClient:this.config.osClient,ApiEngineKey:e,Param:r||{}})}async chat(e){return this.post(O.AI_CHAT,{UserChatMsg:e.question,AiModel:e.aiModel,...e.systemPrompt?{SystemChatMsg:e.systemPrompt}:{},...e.aiModelId?{AiModelId:e.aiModelId}:{},...e.relayModel?{RelayModel:e.relayModel}:{},...e.conversationId?{ConversationId:e.conversationId}:{},...e.reasoningEffort?{ReasoningEffort:e.reasoningEffort}:{},...e.mode?{Mode:e.mode}:{},OsClient:this.config.osClient},{timeoutMs:Math.max(this.config.requestTimeoutMs??12e4,33e4),operationName:"Microi AI chat"})}async recognizeOcr(e){return this.post(O.OCR_RECOGNIZE,e,{timeoutMs:gB,operationName:`OCR recognize ${e.FileName||"unnamed file"}`})}async translateText(e){return this.post(O.TRANSLATE_TEXT,{Action:"TranslateText",...e},{timeoutMs:$a,operationName:"translate text"})}async detectLanguage(e){return this.post(O.TRANSLATE_DETECT,{Action:"Detect",SourceText:e},{timeoutMs:$a,operationName:"detect language"})}async listTranslateLanguages(){return this.post(O.TRANSLATE_LANGUAGES,{Action:"Languages"},{timeoutMs:$a,operationName:"list translation languages"})}async translateFile(e){return this.post(O.TRANSLATE_FILE,{Action:"TranslateFile",...e},{timeoutMs:$a,operationName:`translate file ${e.FileName}`})}async suggestTranslation(e){return this.post(O.TRANSLATE_SUGGEST,{Action:"Suggest",...e},{timeoutMs:$a,operationName:"suggest translation"})}async getTranslateHealth(){return this.post(O.TRANSLATE_HEALTH,{Action:"Health"},{timeoutMs:$a,operationName:"translation health"})}async saveEngineCode(e,r,n){Oc(r,`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`);let i;try{let f=await this.getEngineCode(e);i=f.Code===1?f.Data:void 0}catch{i=void 0}let o=hi(i?.ApiV8Code||i?.Code),a=hi(r);if(o.length>=8e3&&a.length<o.length*.85&&!n?.confirmLargeReduction)throw new Error(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u5DF2\u62E6\u622A\uFF1A\u65B0\u6E90\u7801 ${a.length} \u5B57\u7B26\uFF0C\u8FDC\u7AEF\u6E90\u7801 ${o.length} \u5B57\u7B26\uFF0C\u51CF\u5C11\u8D85\u8FC7 15%\u3002\u8FD9\u53EF\u80FD\u662F\u957F\u5DE5\u5177\u7ED3\u679C\u88AB\u622A\u65AD\uFF1B\u786E\u8BA4\u786E\u9700\u5927\u5E45\u5220\u51CF\u65F6\u8BF7\u4F20 confirmLargeReduction="${e}"\u3002`);let s=Nc({kind:"ApiEngine",key:e,currentCode:r,remoteCode:i?.ApiV8Code||i?.Code,remoteVersion:i?.Version,functionDescription:n?.functionDescription,changeSummary:n?.changeSummary||`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`}),c=n?.v8Limit??(n?.v8Unlimited===void 0?void 0:!n.v8Unlimited),l=Up(n?.apiRoutes),u={OsClient:this.config.osClient,ApiEngineKey:e,ApiV8CodeBase64:Buffer.from(s.code,"utf8").toString("base64"),Version:s.version,ChangeSummary:s.changeHistory,...c===void 0?{}:{V8Limit:c?1:0},...n?.responseType===void 0?{}:{ResponseType:n.responseType},...l===void 0?{}:{ApiRoutes:l}},p=f=>hi(f?.ApiV8Code||f?.Code)===hi(s.code)&&(c===void 0||Nb(f)===(c?1:0))&&(n?.responseType===void 0||String(f?.ResponseType||"JSON").toLowerCase()===n.responseType.toLowerCase())&&(l===void 0||Up(f?.ApiRoutes||"")===l);try{let f=await this.post(O.UPDATE_ENGINE_CODE,u,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`});if(f.Code!==1||c===void 0&&n?.responseType===void 0&&l===void 0)return f;let h=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`)),p);return h.matched?{...f,Data:{...f.Data&&typeof f.Data=="object"?f.Data:{},ApiEngineKey:e,...c===void 0?{}:{V8Limit:c?1:0},...n?.responseType===void 0?{}:{ResponseType:n.responseType},...l===void 0?{}:{ApiRoutes:l},Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:f.Data},Msg:`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e} \u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FD0\u884C\u914D\u7F6E\u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${h.lastError||"\u4EE3\u7801\u6216\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(f){if(!this.isUncertainWriteError(f))throw f;let h=await this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e}`)),p);if(h.matched)return this.recoveredWriteResult(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,f,{ApiEngineKey:e,Version:s.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58\u63A5\u53E3\u5F15\u64CE ${e}`,f,h.lastError)}}async updateEngineRuntimeLimit(e,r){let n={OsClient:this.config.osClient,ApiEngineKey:e,V8Limit:r?1:0},i=()=>this.pollReadback(()=>this.getEngineCode(e,this.readbackOptions(`\u56DE\u8BFB\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`)),a=>Nb(a)===(r?1:0)),o=`\u66F4\u65B0\u63A5\u53E3\u5F15\u64CE ${e} V8Limit`;try{let a=await this.post(O.UPDATE_ENGINE_CODE,n,{timeoutMs:this.writeRequestTimeoutMs,operationName:o});if(a.Code!==1)return a;let s=await i();return s.matched?{...a,Data:{...a.Data&&typeof a.Data=="object"?a.Data:{},ApiEngineKey:e,V8Limit:r?1:0,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e,UpdateResponse:a.Data},Msg:`${o} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u5199\u540E\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${s.lastError||"\u914D\u7F6E\u4E0D\u4E00\u81F4"}`}}catch(a){if(!this.isUncertainWriteError(a))throw a;let s=await i();if(s.matched)return this.recoveredWriteResult(o,a,{ApiEngineKey:e,V8Limit:r?1:0,Verified:!0});throw this.uncertainWriteFailure(o,a,s.lastError)}}async updateEngineRuntimeConfig(e,r){return this.updateEngineRuntimeLimit(e,!r)}async createEngine(e){let r={OsClient:this.config.osClient,...e};r.ApiRoutes=Up(r.ApiRoutes)||"",r.V8Limit===void 0&&r.V8Unlimited!==void 0&&(r.V8Limit=Number(r.V8Unlimited)===1?0:1),delete r.V8Unlimited;let n=typeof r.Code=="string"?r.Code:typeof r.ApiV8Code=="string"?r.ApiV8Code:"";Oc(n,`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`);let i=Nc({kind:"ApiEngine",key:e.ApiEngineKey,currentCode:n,functionDescription:r.functionDescription,changeSummary:r.changeSummary||`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`,initial:!0});r.ApiV8CodeBase64=Buffer.from(i.code,"utf8").toString("base64"),r.Version=i.version,r.ChangeSummary=i.changeHistory,delete r.Code,delete r.ApiV8Code,delete r.functionDescription,delete r.changeSummary,(!r.ApiAddress||r.ApiAddress.trim().length===0)&&(r.ApiAddress=`/apiengine/${e.ApiEngineKey}`),r.IsEnable=r.IsEnable??1,r.StopHttp=r.StopHttp??0,r.AllowAnonymous=r.AllowAnonymous??0;let o=`\u521B\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`,a=()=>this.pollReadback(()=>this.getEngineCode(e.ApiEngineKey,this.readbackOptions(`\u56DE\u8BFB\u65B0\u5EFA\u63A5\u53E3\u5F15\u64CE ${e.ApiEngineKey}`)),s=>String(s?.ApiEngineKey||"")===e.ApiEngineKey&&hi(s?.ApiV8Code||s?.Code)===hi(i.code)&&(r.V8Limit===void 0||Nb(s)===(Number(r.V8Limit)===1?1:0))&&(r.ResponseType===void 0||String(s?.ResponseType||"JSON").toLowerCase()===String(r.ResponseType).toLowerCase())&&Up(s?.ApiRoutes||"")===r.ApiRoutes);try{let s=await this.post(O.CREATE_ENGINE,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:o});if(s.Code!==1)return s;let c=await a();return c.matched?{...s,Data:{...s.Data&&typeof s.Data=="object"?s.Data:{},ApiEngineKey:e.ApiEngineKey,Verified:!0,Verification:"readback"}}:{Code:0,Data:{ApiEngineKey:e.ApiEngineKey,CreateResponse:s.Data},Msg:`${o} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u672A\u786E\u8BA4\u65B0\u8BB0\u5F55\uFF1A${c.lastError||"\u8BB0\u5F55\u6216\u4EE3\u7801\u4E0D\u4E00\u81F4"}`}}catch(s){if(!this.isUncertainWriteError(s))throw s;let c=await a();if(c.matched)return this.recoveredWriteResult(o,s,{ApiEngineKey:e.ApiEngineKey,Version:i.version,Verified:!0});throw this.uncertainWriteFailure(o,s,c.lastError)}}async uploadFileBase64(e){return this.post(O.UPLOAD_FILE_BASE64,{OsClient:this.config.osClient,...e})}async uploadApplicationAssetStream(e){let r=Oa.default.resolve(e.FilePath),n=At.default.lstatSync(r);if(!n.isFile()||n.isSymbolicLink())throw new Error(`\u5E94\u7528\u8D44\u4EA7\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${r}`);let i=Oa.default.posix.basename(String(e.RelativePath||"").replace(/\\/g,"/"));if(!i||/[\r\n"]/u.test(i))throw new Error("RelativePath \u7684\u6587\u4EF6\u540D\u4E0D\u5408\u6CD5");if(e.ProtocolVersion===3)return this.uploadApplicationAssetResumable(e,r,n.size);if(n.size>mB)throw new Error(`\u5F53\u524D\u6587\u4EF6 ${n.size} bytes \u8D85\u8FC7\u65E7\u7248 128MiB \u5355\u8BF7\u6C42\u8FB9\u754C\uFF1B\u8BF7\u542F\u7528 ProtocolVersion=3\uFF0CMCP \u5C06\u81EA\u52A8\u4F7F\u7528 HDFS \u5206\u7247\u65AD\u70B9\u7EED\u4F20\u3002`);let o=`microi-asset-${e.ExpectedSha256.slice(0,16)}.bin`,a={};if(e.ProtocolVersion===3){let s=c=>c===null?"null":String(c??"");Object.assign(a,{ProtocolVersion:"3",PublishMode:"stage",ExpectedGateEpoch:String(e.ExpectedGateEpoch??""),RequestFingerprint:String(e.RequestFingerprint??""),DeliveryBatchId:String(e.DeliveryBatchId??""),SourceManifestHash:String(e.SourceManifestHash??""),RuntimeManifestHash:String(e.RuntimeManifestHash??""),RouteSnapshotJson:String(e.RouteSnapshotJson??""),RouteSnapshotHash:String(e.RouteSnapshotHash??""),ExpectedCurrentVersion:String(e.ExpectedCurrentVersion??""),ExpectedAppVersion:s(e.ExpectedAppVersion),ExpectedPublishFence:String(e.ExpectedPublishFence??""),ExpectedPublishRowVersion:String(e.ExpectedPublishRowVersion??""),ExpectedVersionRowVersion:s(e.ExpectedVersionRowVersion),ExpectedActivePublishVersionId:s(e.ExpectedActivePublishVersionId),ExpectedCommittedPublishVersionId:s(e.ExpectedCommittedPublishVersionId)})}return this.requestMultipartFile(O.UPLOAD_APPLICATION_ASSET_STREAM,{OsClient:this.config.osClient||"",AppIdOrKey:e.AppIdOrKey,VersionNo:e.VersionNo,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,RequestId:e.RequestId,...a},r,o,"initial",e.TimeoutMs)}async getApplicationAssetMultipartStatus(e,r){return this.post(O.GET_APPLICATION_ASSET_MULTIPART_STATUS,{OsClient:this.config.osClient,AppIdOrKey:e,SessionId:r},{timeoutMs:2*6e4,operationName:"read resumable application asset status"})}async uploadApplicationAssetResumable(e,r,n){if(!Number.isSafeInteger(n)||n<0)throw new Error("\u5E94\u7528\u8D44\u4EA7\u5927\u5C0F\u8D85\u51FA JavaScript \u5B89\u5168\u6574\u6570\u8303\u56F4");let i=vB(e),o=await this.post(O.INITIATE_APPLICATION_ASSET_MULTIPART,{OsClient:this.config.osClient,AppIdOrKey:e.AppIdOrKey,VersionNo:e.VersionNo,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,TotalSize:n,RequestedChunkSize:hB,RequestId:e.RequestId,...i},{timeoutMs:2*6e4,operationName:"initiate resumable application asset upload"});if(o.Code!==1)return o;let a=o.Data,s=String(a?.SessionId||"").trim(),c=Number(a?.ChunkSize),l=Number(a?.TotalParts);if(!/^mciau-[a-f0-9]{30}$/u.test(s)||!Number.isSafeInteger(c)||c<16*1024*1024||!Number.isSafeInteger(l)||l<0||l>1e4||l!==(n===0?0:Math.ceil(n/c)))throw new Error("\u670D\u52A1\u7AEF\u8FD4\u56DE\u7684\u65AD\u70B9\u4E0A\u4F20 SessionId/ChunkSize/TotalParts \u4E0D\u5408\u6CD5");let u=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);if(u.Code!==1||String(u.Data?.Status||"")==="Succeeded")return u;let f=new Map;for(let g of u.Data?.Parts||[]){let y=Number(g.Number);Number.isSafeInteger(y)&&y>0&&y<=l&&f.set(y,g)}let h=0,m=0;for(let g=1;g<=l;g+=1){let y=(g-1)*c,v=Math.min(c,n-y),x=await bB(r,y,v),b=f.get(g);if(b){if(Number(b.Size)!==v||String(b.Sha256||"")!==x)throw new Error(`\u65AD\u70B9\u4F1A\u8BDD\u7B2C ${g} \u5757\u4E0E\u672C\u5730\u4E0D\u53EF\u53D8\u6587\u4EF6\u4E0D\u4E00\u81F4\uFF1B\u5DF2\u62D2\u7EDD\u8986\u76D6\uFF0C\u8BF7\u6838\u5BF9\u672C\u5730\u6587\u4EF6\u662F\u5426\u5728\u4E0A\u4F20\u671F\u95F4\u53D1\u751F\u53D8\u5316\u3002`);m+=1;continue}let w;for(let E=0;E<5;E+=1)try{if(w=await this.requestBinaryFileRange(O.UPLOAD_APPLICATION_ASSET_MULTIPART_PART,{osClient:this.config.osClient||"",sessionId:s,partNumber:String(g),expectedPartSha256:x},r,y,v,"initial",e.TimeoutMs),w.Code===1)break;if(E===4)return w}catch(S){u=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);let k=(u.Data?.Parts||[]).find(A=>Number(A.Number)===g);if(u.Code===1&&k&&Number(k.Size)===v&&String(k.Sha256||"")===x){w=u;break}if(E===4)throw S;await new Promise(A=>setTimeout(A,500*(E+1)))}if(!w||w.Code!==1)return w||{Code:0,Data:null,Msg:`\u7B2C ${g} \u5757\u4E0A\u4F20\u6CA1\u6709\u8FD4\u56DE\u7EC8\u6001`};h+=1,(g===1||g%20===0||g===l)&&console.error(`[microi-mcp] Resumable HDFS asset ${e.RelativePath}: ${g}/${l}`)}try{let g=await this.post(O.COMPLETE_APPLICATION_ASSET_MULTIPART,{OsClient:this.config.osClient,AppIdOrKey:e.AppIdOrKey,SessionId:s},{timeoutMs:Mb,maxTimeoutMs:Mb,operationName:"complete resumable application asset upload"});return g.Code===1&&g.Data&&typeof g.Data=="object"?{...g,Data:{...g.Data,UploadedInThisRun:h,ResumedParts:m}}:g}catch(g){let y=await this.getApplicationAssetMultipartStatus(e.AppIdOrKey,s);if(y.Code===1&&String(y.Data?.Status||"")==="Succeeded")return{...y,Data:{...y.Data,RecoveredAfterTransportError:!0,UploadedInThisRun:h,ResumedParts:m},Msg:"\u5B8C\u6210\u8BF7\u6C42\u54CD\u5E94\u4E2D\u65AD\uFF0C\u4F46\u5DF2\u901A\u8FC7\u4F1A\u8BDD\u56DE\u8BFB\u786E\u8BA4\u6700\u7EC8\u5BF9\u8C61 Prepared\u3002"};throw g}}async finalizeApplicationStreamPublish(e){return this.post(O.FINALIZE_APPLICATION_STREAM_PUBLISH,{OsClient:this.config.osClient,...e},{timeoutMs:10*6e4,operationName:"finalize application stream publish"})}async getMicroService(e){return this.post(O.GET_MICRO_SERVICE,{OsClient:this.config.osClient,MsKey:e})}async listApplications(e={}){return this.post(O.LIST_APPLICATIONS,{OsClient:this.config.osClient,...e})}async getApplicationContext(e){return this.post(O.GET_APPLICATION_CONTEXT,{OsClient:this.config.osClient,...e})}async getApplicationFile(e){return this.post(O.GET_APPLICATION_FILE,{OsClient:this.config.osClient,...e})}async createMicroService(e){return this.post(O.CREATE_MICRO_SERVICE,{OsClient:this.config.osClient,...e})}async syncMicroServiceSource(e){return this.post(O.SYNC_MICRO_SERVICE_SOURCE,{OsClient:this.config.osClient,...e},{allowNativeFallback:!1,operationName:"legacy private microservice source sync"})}async stageMicroServiceSourceFile(e){let r=Oa.default.resolve(e.FilePath),n=At.default.lstatSync(r);if(!n.isFile()||n.isSymbolicLink())throw new Error(`\u5FAE\u670D\u52A1\u6E90\u7801\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u4E14\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${r}`);if(n.size!==e.ExpectedSize)throw new Error(`\u5FAE\u670D\u52A1\u6E90\u7801\u5927\u5C0F\u5728\u6E05\u5355\u751F\u6210\u540E\u53D1\u751F\u53D8\u5316\uFF1A${e.RelativePath}`);let i=e.MicroService||{},o={OsClient:this.config.osClient||"",AppIdOrKey:e.AppIdOrKey,RelativePath:e.RelativePath,ExpectedSha256:e.ExpectedSha256,ExpectedSize:String(e.ExpectedSize),DeliveryBatchId:e.DeliveryBatchId};for(let a of["MsKey","MicroServiceKey","AppKey","MsName","Name","AppName","ApplicationType","AppType","Category","Description","Remark"]){let s=i[a];s!=null&&(o[a]=String(s))}return this.requestMultipartFile(O.STAGE_MICRO_SERVICE_SOURCE_FILE,o,r,`microi-source-${e.ExpectedSha256.slice(0,16)}.bin`,"initial",e.TimeoutMs,void 0,!1)}async finalizeMicroServiceSourceManifest(e){return this.post(O.FINALIZE_MICRO_SERVICE_SOURCE_MANIFEST,{OsClient:this.config.osClient,...e},{timeoutMs:10*6e4,operationName:"finalize private microservice source manifest"})}async clearApplicationSource(e){return this.post(O.CLEAR_APPLICATION_SOURCE,{OsClient:this.config.osClient,...e},{timeoutMs:10*6e4,operationName:"clear application source"})}async publishMicroService(e){return this.post(O.PUBLISH_MICRO_SERVICE,{OsClient:this.config.osClient,...e})}async probeMicroAppEntry(e){let r=sB(this.config.apiBaseUrl,this.config.osClient||"",e),n=new AbortController,i=setTimeout(()=>n.abort(),1e4);try{let o=await fetch(r,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml"},redirect:"follow",signal:n.signal}),a=o.headers.get("content-type")||"",s=Number(o.headers.get("content-length")||0);if(Number.isFinite(s)&&s>2*1024*1024)return await o.body?.cancel(),{ok:!1,url:r,status:o.status,contentType:a,bodyBytes:s,error:"MicroApp entry exceeds the 2MB probe limit"};let c=Buffer.from(await o.arrayBuffer()),l=c.byteLength,u=c.toString("utf8"),p=/<head(?:\s|>)/iu.test(u),f=/<body(?:\s|>)/iu.test(u),h=o.ok&&a.toLowerCase().includes("text/html")&&l>0&&p&&f;return{ok:h,url:r,status:o.status,contentType:a,bodyBytes:l,hasHead:p,hasBody:f,...o.ok?h?{}:{error:"MicroApp entry is not a complete HTML document with <head> and <body>"}:{error:`HTTP ${o.status} ${o.statusText}`}}}catch(o){return{ok:!1,url:r,error:n.signal.aborted?"MicroApp entry probe timed out after 10000ms":o instanceof Error?o.message:String(o)}}finally{clearTimeout(i)}}async getTableData(e,r={}){return this.post(O.FORM_GET_TABLE_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async addFormData(e,r){return this.post(O.FORM_ADD_FORM_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async updateFormData(e,r){return this.post(O.FORM_UPT_FORM_DATA,{OsClient:this.config.osClient,FormEngineKey:e,...r})}async getEventCode(e,r,n={}){return r=r==="DataFilterV8"?"ServerDataV8":r,this.post(O.GET_EVENT_CODE,{OsClient:this.config.osClient,FormEngineKey:e,EventType:r},n)}async saveEventCode(e,r,n,i){r=r==="DataFilterV8"?"ServerDataV8":r,Oc(n,`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`);let o;try{let c=await this.getEventCode(e,r);o=c.Code===1?c.Data:void 0}catch{o=void 0}let a=Nc({kind:"V8Event",key:e,eventType:r,currentCode:n,remoteCode:o?.V8Code||o?.Code,remoteVersion:o?.Version,functionDescription:i?.functionDescription,changeSummary:i?.changeSummary||`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`}),s={OsClient:this.config.osClient,FormEngineKey:e,EventType:r,V8Code:a.code,Version:a.version,ChangeHistory:a.changeHistory};try{return await this.post(O.UPDATE_EVENT_CODE,s,{timeoutMs:this.writeRequestTimeoutMs,operationName:`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`})}catch(c){if(!this.isUncertainWriteError(c))throw c;let l=await this.pollReadback(()=>this.getEventCode(e,r,this.readbackOptions(`\u56DE\u8BFB V8 \u4E8B\u4EF6 ${e}/${r}`)),u=>hi(u?.V8Code||u?.Code)===hi(a.code));if(l.matched)return this.recoveredWriteResult(`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`,c,{FormEngineKey:e,EventType:r,Version:a.version});throw this.uncertainWriteFailure(`\u4FDD\u5B58 V8 \u4E8B\u4EF6 ${e}/${r}`,c,l.lastError)}}async getEventList(e){return this.post(O.GET_EVENT_LIST,{OsClient:this.config.osClient,...e?{_SearchKey:e}:{}})}async getWorkflowV8EventList(e){return this.post(O.GET_WORKFLOW_V8_EVENT_LIST,{OsClient:this.config.osClient,...e?{FlowDesignId:e}:{}})}async getWorkflowV8EventCode(e,r,n){return this.post(O.GET_WORKFLOW_V8_EVENT_CODE,{OsClient:this.config.osClient,...n?{FlowDesignId:n}:{},NodeId:e,EventType:r})}async saveWorkflowV8EventCode(e,r,n,i){Oc(n,`\u4FDD\u5B58\u6D41\u7A0B\u8282\u70B9 V8 ${e}/${r}`);let o;try{let c=await this.getWorkflowV8EventCode(e,r,i?.flowDesignId);o=c.Code===1?c.Data:void 0}catch{o=void 0}let a=!n.trim(),s={OsClient:this.config.osClient,...i?.flowDesignId?{FlowDesignId:i.flowDesignId}:{},NodeId:e,EventType:r};if(a)s.V8Code="";else{let c=`${i?.flowDesignId||o?.FlowDesignId||"workflow"}/${e}`,l=Nc({kind:"Workflow",key:c,eventType:r,currentCode:n,remoteCode:o?.V8Code||o?.Code,remoteVersion:o?.Version,functionDescription:i?.functionDescription,changeSummary:i?.changeSummary||`\u4FDD\u5B58\u6D41\u7A0B\u8282\u70B9 V8 ${e}/${r}`});s.V8CodeBase64=Buffer.from(l.code,"utf8").toString("base64"),s.Version=l.version,s.ChangeHistory=l.changeHistory}return this.post(O.UPDATE_WORKFLOW_V8_EVENT_CODE,s)}async createTable(e,r,n){let i={...n||{}};i.V8Limit===void 0&&i.V8Unlimited!==void 0&&(i.V8Limit=Number(i.V8Unlimited)===1?0:1),delete i.V8Unlimited;let o=i.ReadPrimary;if(o!=null&&o!==0&&o!==1)throw new Error("ReadPrimary \u53EA\u5141\u8BB8 null\u30010 \u6216 1");delete i.ReadPrimary;let a=await this.post(O.CREATE_TABLE,{OsClient:this.config.osClient,Name:e,Description:r||"",...i});if(a.Code!==1||o===void 0)return a;let s=a.Data?.TableId||a.Data?.Id;if(!s)return{Code:0,Data:null,Msg:"\u8868\u521B\u5EFA\u540E\u7F3A\u5C11 TableId\uFF0C\u672A\u914D\u7F6E ReadPrimary"};let c=await this.updateTable({Id:s,ReadPrimary:o});return c.Code!==1?c:{...a,Data:{...a.Data,ReadPrimary:o}}}async repairFixedAuditFields(e){return this.post(O.REPAIR_FIXED_AUDIT_FIELDS,{OsClient:this.config.osClient,TableId:e.tableId,TableName:e.tableName})}async addField(e){return this.post(O.ADD_FIELD,{OsClient:this.config.osClient,...e,Visible:e.Visible??1,AppVisible:e.AppVisible??1})}async deleteField(e){return this.post(O.DELETE_FIELD,{OsClient:this.config.osClient,...e})}async updateField(e){return this.post(O.UPDATE_FIELD,{OsClient:this.config.osClient,...e})}async updateFieldList(e){return this.post(O.UPDATE_FIELD_LIST,{OsClient:this.config.osClient,...e})}async getFieldList(e,r){return this.post(O.GET_FIELD_LIST,{OsClient:this.config.osClient,TableName:e,TableId:r})}async updateTable(e){return this.post(O.UPDATE_TABLE,{OsClient:this.config.osClient,...e})}async refreshSchemaCache(e){return this.post(O.REFRESH_SCHEMA_CACHE,{OsClient:this.config.osClient,Tables:e})}async setEngineAnonymous(e,r=1){return this.post(O.SET_ENGINE_ANONYMOUS,{OsClient:this.config.osClient,ApiEngineKeys:e,AllowAnonymous:r})}async setEngineRoles(e){return this.post(O.SET_ENGINE_ROLES,{OsClient:this.config.osClient,...e})}async generateMiniMaxMusic(e){return this.post(O.GENERATE_MINIMAX_MUSIC,e,{timeoutMs:10*6e4,operationName:"generate MiniMax music"})}async generateMiniMaxSpeech(e){return this.post(O.GENERATE_MINIMAX_SPEECH,e,{timeoutMs:10*6e4,operationName:"generate MiniMax speech"})}async createModule(e){let r=await this.post(O.CREATE_MODULE,{OsClient:this.config.osClient,...e,Display:e.Display??1,AppDisplay:e.AppDisplay??1});if(r.Code!==1||!!!(e.IsMicroiService===1||e.MicroServiceId||e.MicroServicePageId||e.MicroServiceRoutePath))return r;let i=r.Data&&typeof r.Data=="object"?r.Data:{},o=String(i.ModuleId||i.Id||"");if(!o)return{Code:0,Data:{CreateResponse:r.Data},Msg:"\u83DC\u5355\u5DF2\u521B\u5EFA\uFF0C\u4F46\u8FD4\u56DE\u7ED3\u679C\u7F3A\u5C11 ModuleId\uFF0C\u65E0\u6CD5\u5199\u5165\u5E76\u56DE\u8BFB\u5FAE\u670D\u52A1\u5173\u8054\u5B57\u6BB5\u3002"};let a={ModuleId:o,IsMicroiService:1,OpenType:e.OpenType||"MicroService",ComponentName:e.ComponentName||"MicroService",ComponentPath:e.ComponentPath||"/micro-app/host",Url:e.Url,MicroServiceId:e.MicroServiceId,MicroServicePageId:e.MicroServicePageId,MicroServiceRoutePath:e.MicroServiceRoutePath},s=await this.updateModule(a);return s.Code!==1?{Code:0,Data:{ModuleId:o,CreateResponse:r.Data,BindingResponse:s.Data},Msg:`\u83DC\u5355\u57FA\u7840\u8BB0\u5F55\u5DF2\u521B\u5EFA\uFF0C\u4F46\u5FAE\u670D\u52A1\u5173\u8054\u5B57\u6BB5\u5199\u5165\u6216\u56DE\u8BFB\u5931\u8D25\uFF1A${s.Msg||"\u672A\u77E5\u9519\u8BEF"}`}:{...r,Data:{...i,MicroServiceBindingVerified:!0,BindingVerification:s.Data}}}async setRolePermission(e,r){return this.post(O.SET_ROLE_PERMISSION,{OsClient:this.config.osClient,RoleId:e,MenuIds:r})}async listRoles(e){return this.post(O.LIST_ROLES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async saveRole(e){return this.post(O.SAVE_ROLE,{OsClient:this.config.osClient,...e})}async listModules(e){return this.post(O.LIST_MODULES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getModule(e,r={}){return this.post(O.GET_MODULE,{OsClient:this.config.osClient,ModuleId:e},r)}async updateModule(e){let r={OsClient:this.config.osClient,...e},n=String(r.ModuleId||r.Id||""),i=`\u66F4\u65B0\u83DC\u5355\u6A21\u5757 ${n||r.Name||""}`.trim();$c(r,i);let o=async()=>{if(!n)return{matched:!1,mismatches:["ModuleId"]};try{let a=await this.getModule(n,this.readbackOptions(`\u56DE\u8BFB\u83DC\u5355\u6A21\u5757 ${n}`));return a.Code!==1||!a.Data||typeof a.Data!="object"?{matched:!1,mismatches:["\u56DE\u8BFB\u5931\u8D25"],response:a}:{...xB(r,a.Data),response:a}}catch{return{matched:!1,mismatches:["\u56DE\u8BFB\u8BF7\u6C42\u5F02\u5E38"]}}};try{let a=await this.post(O.UPDATE_MODULE,r,{timeoutMs:this.writeRequestTimeoutMs,operationName:i});if(a.Code!==1)return a;let s=await o();return s.matched?{...a,Data:{...a.Data&&typeof a.Data=="object"?a.Data:{},Verified:!0,Verification:"readback"}}:{Code:0,Data:{ModuleId:n,Mismatches:s.mismatches,UpdateResponse:a.Data},Msg:`${i} \u63A5\u53E3\u8FD4\u56DE\u6210\u529F\uFF0C\u4F46\u8FDC\u7AEF\u56DE\u8BFB\u4E0D\u4E00\u81F4\uFF1A${s.mismatches.join(", ")}`}}catch(a){if(!this.isUncertainWriteError(a))throw a;let s=[],c=await this.pollReadback(async()=>{let l=await o();return s=l.mismatches,{Code:l.response?.Code??(l.matched?1:0),Data:l,Msg:l.response?.Msg||""}},l=>l.matched);if(c.matched)return this.recoveredWriteResult(i,a,{ModuleId:n,Verified:!0});throw this.uncertainWriteFailure(i,a,s.length?`\u5B57\u6BB5\u4E0D\u4E00\u81F4\uFF1A${s.join(", ")}`:c.lastError)}}async listDataSources(e){return this.post(O.LIST_DATA_SOURCES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async saveDataSource(e){return this.post(O.SAVE_DATA_SOURCE,{OsClient:this.config.osClient,...e})}async runDataSource(e,r){return this.post(O.RUN_DATA_SOURCE,{OsClient:this.config.osClient,DataSourceKey:e,...r||{}})}async listPrintTemplates(e){return this.post(O.LIST_PRINT_TEMPLATES,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async savePrintTemplate(e){return this.post(O.SAVE_PRINT_TEMPLATE,{OsClient:this.config.osClient,...e})}async saveWorkflowPackage(e){return this.post(O.SAVE_WORKFLOW_PACKAGE,{OsClient:this.config.osClient,...e})}async saveJob(e){return this.post(O.SAVE_JOB,{OsClient:this.config.osClient,...e})}async listDatabaseBackupTenants(){return this.post(O.LIST_DATABASE_BACKUP_TENANTS,{OsClient:this.config.osClient})}async runDatabaseBackup(e){if(!/^[A-Za-z0-9:._-]{8,128}$/.test(e?.idempotencyKey||""))throw new Error("database backup idempotencyKey is required (8-128 safe characters) and must be reused for uncertain retries");return this.post(O.RUN_DATABASE_BACKUP,{OsClient:this.config.osClient,ConfirmExecution:"DATABASE_BACKUP",RetainCount:e.retainCount??7,...e.tenantOsClients===void 0?{}:{TenantOsClients:e.tenantOsClients},IdempotencyKey:e.idempotencyKey})}async runBackgroundApiEngine(e){return this.post(O.RUN_BACKGROUND_API_ENGINE,{OsClient:this.config.osClient,Action:"RunApiEngine",TargetApiEngineKey:e.apiEngineKey,Title:e.title,Param:e.param,Options:e.options||{}},{timeoutMs:this.writeRequestTimeoutMs,operationName:`queue background API engine ${e.apiEngineKey}`})}async validateLowCodeSystem(e){return this.post(O.VALIDATE_LOW_CODE_SYSTEM,{OsClient:this.config.osClient,Manifest:e})}async writeAuditLog(e,r,n){return this.post(O.WRITE_MCP_AUDIT_LOG,{OsClient:this.config.osClient,Action:e,Target:r,Content:n})}async queryMongodbLogs(e={}){return this.post(O.QUERY_MONGODB_LOGS,{OsClient:this.config.osClient,Keyword:e.keyword,Type:e.type,Level:e.level,SearchMonth:e.searchMonth,PageIndex:e.pageIndex||1,PageSize:e.pageSize||20})}async writeMongodbLog(e){return this.post(O.WRITE_MONGODB_LOG,{OsClient:this.config.osClient,Type:e.type||"MCP",Title:e.title,Content:e.content,Level:e.level||1,Api:e.api||"microi.mcp",Param:e.param||"",Remark:e.remark||"",OtherInfo:e.otherInfo||"",Timer:e.timer,Result:e.result||"",AppId:e.appId||"microi.mcp"})}async querySystemObservability(e){return e.Action==="DatabasePools"||e.Action==="DatabasePoolRecovery"?this.post("/api/Diagnostics/database-pools",{...e,OsClient:this.config.osClient},{allowNativeFallback:!1,timeoutMs:3e4}):this.executeEngine("mci-system-observability-query",e)}async manageSystemObservability(e){return e.Action==="ResetDatabasePools"?this.post("/api/Diagnostics/database-pools",{...e,OsClient:this.config.osClient},{allowNativeFallback:!1,timeoutMs:3e4}):this.executeEngine("mci-system-observability-action",e)}async getRedisStatistics(e=0,r){return this.post(O.REDIS_STATISTICS,{Action:"RedisStatistics",Mode:r?"saved":"tenant",ConnectionId:r||"",Database:e})}async getRedisKeys(e="*",r=0,n=100,i,o){return this.post(O.REDIS_KEYS,{Action:"Keys",Mode:o?"saved":"tenant",ConnectionId:o||"",Database:r,Pattern:e,PageSize:n,Cursor:i||""})}async getRedisKey(e,r=0,n=1,i=500,o){return this.post(O.REDIS_KEY,{Action:"Key",Mode:o?"saved":"tenant",ConnectionId:o||"",Database:r,Key:e,PageIndex:n,PageSize:i})}async deleteRedisKeys(e,r=0,n){return this.post(O.REDIS_DELETE_KEYS,{Action:"DeleteKeys",Mode:n?"saved":"tenant",ConnectionId:n||"",Database:r,Keys:e})}async replaceRedisValue(e,r,n,i=0,o,a){return this.post(O.REDIS_REPLACE_VALUE,{Action:"ReplaceValue",Mode:a?"saved":"tenant",ConnectionId:a||"",Database:i,Key:e,DataType:r,Value:n,...o===void 0?{}:{TtlSeconds:o}})}async renameRedisKey(e,r,n=0,i){return this.post(O.REDIS_RENAME_KEY,{Action:"RenameKey",Mode:i?"saved":"tenant",ConnectionId:i||"",Database:n,Key:e,NewKey:r})}async setRedisTtl(e,r,n=0,i){return this.post(O.REDIS_SET_TTL,{Action:"SetTtl",Mode:i?"saved":"tenant",ConnectionId:i||"",Database:n,Key:e,TtlSeconds:r})}async getPageEngineList(e){return this.post(O.GET_PAGE_ENGINE_LIST,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getPageEngineDetail(e){return this.post(O.GET_PAGE_ENGINE_DETAIL,{OsClient:this.config.osClient,PageId:e})}async savePageEngine(e){return this.post(O.SAVE_PAGE_ENGINE,{OsClient:this.config.osClient,...e})}async listBackgroundTasks(){return this.post(O.LIST_BACKGROUND_TASKS,{OsClient:this.config.osClient,Action:"List"},{timeoutMs:this.requestTimeoutMs,operationName:"list background tasks"})}async cancelBackgroundTask(e){return this.post(O.CANCEL_BACKGROUND_TASK,{OsClient:this.config.osClient,Action:"Cancel",Id:e},{timeoutMs:this.writeRequestTimeoutMs,operationName:"cancel background task"})}async listPageEngineHistory(e,r=1,n=50){return this.post(O.LIST_PAGE_ENGINE_HISTORY,{OsClient:this.config.osClient,PageId:e,PageIndex:r,PageSize:n})}async getPageEngineHistory(e,r){return this.post(O.GET_PAGE_ENGINE_HISTORY,{OsClient:this.config.osClient,PageId:e,HistoryId:r})}async comparePageEngineVersions(e,r,n){return this.post(O.COMPARE_PAGE_ENGINE_VERSIONS,{OsClient:this.config.osClient,PageId:e,...r?{LeftHistoryId:r}:{},...n?{RightHistoryId:n}:{}})}async exportPageEngine(e){return this.post(O.EXPORT_PAGE_ENGINE,{OsClient:this.config.osClient,PageId:e})}async rollbackPageEngine(e){return this.post(O.ROLLBACK_PAGE_ENGINE,{OsClient:this.config.osClient,...e})}async listBlueprints(e){return this.post(O.LIST_BLUEPRINTS,{OsClient:this.config.osClient,...e?{Keyword:e}:{}})}async getBlueprint(e){return this.post(O.GET_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async listBlueprintHistory(e,r=1,n=50){return this.post(O.LIST_BLUEPRINT_HISTORY,{OsClient:this.config.osClient,BlueprintId:e,PageIndex:r,PageSize:n})}async getBlueprintHistory(e,r){return this.post(O.GET_BLUEPRINT_HISTORY,{OsClient:this.config.osClient,BlueprintId:e,HistoryId:r})}async compareBlueprintVersions(e,r,n){return this.post(O.COMPARE_BLUEPRINT_VERSIONS,{OsClient:this.config.osClient,BlueprintId:e,...r?{LeftHistoryId:r}:{},...n?{RightHistoryId:n}:{}})}async exportBlueprint(e){return this.post(O.EXPORT_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async saveBlueprint(e){return this.post(O.SAVE_BLUEPRINT,{OsClient:this.config.osClient,...e})}async rollbackBlueprint(e){return this.post(O.ROLLBACK_BLUEPRINT,{OsClient:this.config.osClient,...e})}async deleteBlueprint(e){return this.post(O.DELETE_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}async validateBlueprint(e){return this.post(O.VALIDATE_BLUEPRINT,{OsClient:this.config.osClient,BlueprintId:e})}destroy(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}};var d={};Sf(d,{BRAND:()=>HB,DIRTY:()=>so,EMPTY_PATH:()=>EB,INVALID:()=>G,NEVER:()=>IU,OK:()=>It,ParseStatus:()=>wt,Schema:()=>ae,ZodAny:()=>bi,ZodArray:()=>Vn,ZodBigInt:()=>lo,ZodBoolean:()=>uo,ZodBranded:()=>zc,ZodCatch:()=>_o,ZodDate:()=>po,ZodDefault:()=>wo,ZodDiscriminatedUnion:()=>Gp,ZodEffects:()=>Rr,ZodEnum:()=>vo,ZodError:()=>nr,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Yp,ZodIntersection:()=>go,ZodIssueCode:()=>N,ZodLazy:()=>yo,ZodLiteral:()=>bo,ZodMap:()=>La,ZodNaN:()=>qa,ZodNativeEnum:()=>xo,ZodNever:()=>Gr,ZodNull:()=>mo,ZodNullable:()=>xn,ZodNumber:()=>co,ZodObject:()=>or,ZodOptional:()=>ir,ZodParsedType:()=>L,ZodPipeline:()=>Lc,ZodPromise:()=>vi,ZodReadonly:()=>So,ZodRecord:()=>Xp,ZodSchema:()=>ae,ZodSet:()=>ja,ZodString:()=>yi,ZodSymbol:()=>Fa,ZodTransformer:()=>Rr,ZodTuple:()=>vn,ZodType:()=>ae,ZodUndefined:()=>fo,ZodUnion:()=>ho,ZodUnknown:()=>qn,ZodVoid:()=>za,addIssueToContext:()=>z,any:()=>tU,array:()=>oU,bigint:()=>GB,boolean:()=>gI,coerce:()=>AU,custom:()=>fI,date:()=>XB,datetimeRegex:()=>pI,defaultErrorMap:()=>Ln,discriminatedUnion:()=>cU,effect:()=>xU,enum:()=>yU,function:()=>mU,getErrorMap:()=>Na,getParsedType:()=>bn,instanceof:()=>KB,intersection:()=>lU,isAborted:()=>Kp,isAsync:()=>Ma,isDirty:()=>Wp,isValid:()=>gi,late:()=>ZB,lazy:()=>hU,literal:()=>gU,makeIssue:()=>Fc,map:()=>dU,nan:()=>WB,nativeEnum:()=>bU,never:()=>nU,null:()=>eU,nullable:()=>_U,number:()=>hI,object:()=>jb,objectUtil:()=>Fb,oboolean:()=>CU,onumber:()=>TU,optional:()=>wU,ostring:()=>kU,pipeline:()=>EU,preprocess:()=>SU,promise:()=>vU,quotelessJson:()=>wB,record:()=>pU,set:()=>fU,setErrorMap:()=>SB,strictObject:()=>aU,string:()=>mI,symbol:()=>YB,transformer:()=>xU,tuple:()=>uU,undefined:()=>QB,union:()=>sU,unknown:()=>rU,util:()=>ge,void:()=>iU});var ge;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),a={};for(let s of o)a[s]=i[s];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},t.find=(i,o)=>{for(let a of i)if(o(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}t.joinValues=n,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(ge||(ge={}));var Fb;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Fb||(Fb={}));var L=ge.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),bn=t=>{switch(typeof t){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(t)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":return Array.isArray(t)?L.array:t===null?L.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?L.promise:typeof Map<"u"&&t instanceof Map?L.map:typeof Set<"u"&&t instanceof Set?L.set:typeof Date<"u"&&t instanceof Date?L.date:L.object;default:return L.unknown}};var N=ge.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),wB=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),nr=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let s=n,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(r(a))):s[l]=s[l]||{_errors:[]},s=s[l],c++}}};return i(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ge.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(e(i))}else n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};nr.create=t=>new nr(t);var _B=(t,e)=>{let r;switch(t.code){case N.invalid_type:t.received===L.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case N.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ge.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:r=`Unrecognized key(s) in object: ${ge.joinValues(t.keys,", ")}`;break;case N.invalid_union:r="Invalid input";break;case N.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ge.joinValues(t.options)}`;break;case N.invalid_enum_value:r=`Invalid enum value. Expected ${ge.joinValues(t.options)}, received '${t.received}'`;break;case N.invalid_arguments:r="Invalid function arguments";break;case N.invalid_return_type:r="Invalid function return type";break;case N.invalid_date:r="Invalid date";break;case N.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ge.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case N.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case N.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case N.custom:r="Invalid input";break;case N.invalid_intersection_types:r="Intersection results could not be merged";break;case N.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case N.not_finite:r="Number must be finite";break;default:r=e.defaultError,ge.assertNever(t)}return{message:r}},Ln=_B;var aI=Ln;function SB(t){aI=t}function Na(){return aI}var Fc=t=>{let{data:e,path:r,errorMaps:n,issueData:i}=t,o=[...r,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let s="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)s=l(a,{data:e,defaultError:s}).message;return{...i,path:o,message:s}},EB=[];function z(t,e){let r=Na(),n=Fc({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Ln?void 0:Ln].filter(i=>!!i)});t.common.issues.push(n)}var wt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let i of r){if(i.status==="aborted")return G;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let i of r){let o=await i.key,a=await i.value;n.push({key:o,value:a})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let i of r){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return G;o.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[o.value]=a.value)}return{status:e.value,value:n}}},G=Object.freeze({status:"aborted"}),so=t=>({status:"dirty",value:t}),It=t=>({status:"valid",value:t}),Kp=t=>t.status==="aborted",Wp=t=>t.status==="dirty",gi=t=>t.status==="valid",Ma=t=>typeof Promise<"u"&&t instanceof Promise;var B;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(B||(B={}));var Ir=class{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},sI=(t,e)=>{if(gi(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new nr(t.common.issues);return this._error=r,this._error}}};function ne(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,s)=>{let{message:c}=t;return a.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:i}}var ae=class{get description(){return this._def.description}_getType(e){return bn(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:bn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new wt,ctx:{common:e.parent.common,data:e.data,parsedType:bn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ma(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bn(e)},i=this._parseSync({data:e,path:n.path,parent:n});return sI(n,i)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bn(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return gi(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>gi(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:bn(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(Ma(i)?i:Promise.resolve(i));return sI(n,o)}refine(e,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let a=e(i),s=()=>o.addIssue({code:N.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new Rr({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return ir.create(this,this._def)}nullable(){return xn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Vn.create(this)}promise(){return vi.create(this,this._def)}or(e){return ho.create([this,e],this._def)}and(e){return go.create(this,e,this._def)}transform(e){return new Rr({...ne(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new wo({...ne(this._def),innerType:this,defaultValue:r,typeName:M.ZodDefault})}brand(){return new zc({typeName:M.ZodBranded,type:this,...ne(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new _o({...ne(this._def),innerType:this,catchValue:r,typeName:M.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Lc.create(this,e)}readonly(){return So.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kB=/^c[^\s-]{8,}$/i,TB=/^[0-9a-z]+$/,CB=/^[0-9A-HJKMNP-TV-Z]{26}$/i,AB=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,IB=/^[a-z0-9_-]{21}$/i,RB=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,PB=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,$B=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OB="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",zb,NB=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,MB=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,DB=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,FB=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zB=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,LB=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lI="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",jB=new RegExp(`^${lI}$`);function uI(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function qB(t){return new RegExp(`^${uI(t)}$`)}function pI(t){let e=`${lI}T${uI(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function VB(t,e){return!!((e==="v4"||!e)&&NB.test(t)||(e==="v6"||!e)&&DB.test(t))}function BB(t,e){if(!RB.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function UB(t,e){return!!((e==="v4"||!e)&&MB.test(t)||(e==="v6"||!e)&&FB.test(t))}var yi=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==L.string){let o=this._getOrReturnCtx(e);return z(o,{code:N.invalid_type,expected:L.string,received:o.parsedType}),G}let n=new wt,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let a=e.data.length>o.value,s=e.data.length<o.value;(a||s)&&(i=this._getOrReturnCtx(e,i),a?z(i,{code:N.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&z(i,{code:N.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")$B.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"email",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")zb||(zb=new RegExp(OB,"u")),zb.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"emoji",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")AB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"uuid",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")IB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"nanoid",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")kB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cuid",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")TB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cuid2",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")CB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"ulid",code:N.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),z(i,{validation:"url",code:N.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"regex",code:N.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?pI(o).test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?jB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?qB(o).test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{code:N.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?PB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"duration",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?VB(e.data,o.version)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"ip",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?BB(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"jwt",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?UB(e.data,o.version)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"cidr",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?zB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"base64",code:N.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?LB.test(e.data)||(i=this._getOrReturnCtx(e,i),z(i,{validation:"base64url",code:N.invalid_string,message:o.message}),n.dirty()):ge.assertNever(o);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(i=>e.test(i),{validation:r,code:N.invalid_string,...B.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...B.errToObj(e)})}url(e){return this._addCheck({kind:"url",...B.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...B.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...B.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...B.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...B.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...B.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...B.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...B.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...B.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...B.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...B.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...B.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...B.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...B.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...B.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...B.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...B.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...B.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...B.errToObj(r)})}nonempty(e){return this.min(1,B.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};yi.create=t=>new yi({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...ne(t)});function JB(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return o%a/10**i}var co=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==L.number){let o=this._getOrReturnCtx(e);return z(o,{code:N.invalid_type,expected:L.number,received:o.parsedType}),G}let n,i=new wt;for(let o of this._def.checks)o.kind==="int"?ge.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:N.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?JB(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_finite,message:o.message}),i.dirty()):ge.assertNever(o);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:B.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:B.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:B.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:B.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ge.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};co.create=t=>new co({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...ne(t)});var lo=class t extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==L.bigint)return this._getInvalidInput(e);let n,i=new wt;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),z(n,{code:N.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):ge.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return z(r,{code:N.invalid_type,expected:L.bigint,received:r.parsedType}),G}gte(e,r){return this.setLimit("min",e,!0,B.toString(r))}gt(e,r){return this.setLimit("min",e,!1,B.toString(r))}lte(e,r){return this.setLimit("max",e,!0,B.toString(r))}lt(e,r){return this.setLimit("max",e,!1,B.toString(r))}setLimit(e,r,n,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:B.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:B.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};lo.create=t=>new lo({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...ne(t)});var uo=class extends ae{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==L.boolean){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.boolean,received:n.parsedType}),G}return It(e.data)}};uo.create=t=>new uo({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...ne(t)});var po=class t extends ae{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==L.date){let o=this._getOrReturnCtx(e);return z(o,{code:N.invalid_type,expected:L.date,received:o.parsedType}),G}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return z(o,{code:N.invalid_date}),G}let n=new wt,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),z(i,{code:N.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):ge.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:B.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:B.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};po.create=t=>new po({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...ne(t)});var Fa=class extends ae{_parse(e){if(this._getType(e)!==L.symbol){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.symbol,received:n.parsedType}),G}return It(e.data)}};Fa.create=t=>new Fa({typeName:M.ZodSymbol,...ne(t)});var fo=class extends ae{_parse(e){if(this._getType(e)!==L.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.undefined,received:n.parsedType}),G}return It(e.data)}};fo.create=t=>new fo({typeName:M.ZodUndefined,...ne(t)});var mo=class extends ae{_parse(e){if(this._getType(e)!==L.null){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.null,received:n.parsedType}),G}return It(e.data)}};mo.create=t=>new mo({typeName:M.ZodNull,...ne(t)});var bi=class extends ae{constructor(){super(...arguments),this._any=!0}_parse(e){return It(e.data)}};bi.create=t=>new bi({typeName:M.ZodAny,...ne(t)});var qn=class extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(e){return It(e.data)}};qn.create=t=>new qn({typeName:M.ZodUnknown,...ne(t)});var Gr=class extends ae{_parse(e){let r=this._getOrReturnCtx(e);return z(r,{code:N.invalid_type,expected:L.never,received:r.parsedType}),G}};Gr.create=t=>new Gr({typeName:M.ZodNever,...ne(t)});var za=class extends ae{_parse(e){if(this._getType(e)!==L.undefined){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.void,received:n.parsedType}),G}return It(e.data)}};za.create=t=>new za({typeName:M.ZodVoid,...ne(t)});var Vn=class t extends ae{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==L.array)return z(r,{code:N.invalid_type,expected:L.array,received:r.parsedType}),G;if(i.exactLength!==null){let a=r.data.length>i.exactLength.value,s=r.data.length<i.exactLength.value;(a||s)&&(z(r,{code:a?N.too_big:N.too_small,minimum:s?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(z(r,{code:N.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(z(r,{code:N.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,s)=>i.type._parseAsync(new Ir(r,a,r.path,s)))).then(a=>wt.mergeArray(n,a));let o=[...r.data].map((a,s)=>i.type._parseSync(new Ir(r,a,r.path,s)));return wt.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:B.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:B.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:B.toString(r)}})}nonempty(e){return this.min(1,e)}};Vn.create=(t,e)=>new Vn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...ne(e)});function Da(t){if(t instanceof or){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=ir.create(Da(n))}return new or({...t._def,shape:()=>e})}else return t instanceof Vn?new Vn({...t._def,type:Da(t.element)}):t instanceof ir?ir.create(Da(t.unwrap())):t instanceof xn?xn.create(Da(t.unwrap())):t instanceof vn?vn.create(t.items.map(e=>Da(e))):t}var or=class t extends ae{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ge.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==L.object){let l=this._getOrReturnCtx(e);return z(l,{code:N.invalid_type,expected:L.object,received:l.parsedType}),G}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof Gr&&this._def.unknownKeys==="strip"))for(let l in i.data)a.includes(l)||s.push(l);let c=[];for(let l of a){let u=o[l],p=i.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Ir(i,p,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof Gr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of s)c.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(l==="strict")s.length>0&&(z(i,{code:N.unrecognized_keys,keys:s}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of s){let p=i.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Ir(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,f=await u.value;l.push({key:p,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>wt.mergeObjectSync(n,l)):wt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return B.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:B.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ge.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ge.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Da(this)}partial(e){let r={};for(let n of ge.objectKeys(this.shape)){let i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ge.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof ir;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return dI(ge.objectKeys(this.shape))}};or.create=(t,e)=>new or({shape:()=>t,unknownKeys:"strip",catchall:Gr.create(),typeName:M.ZodObject,...ne(e)});or.strictCreate=(t,e)=>new or({shape:()=>t,unknownKeys:"strict",catchall:Gr.create(),typeName:M.ZodObject,...ne(e)});or.lazycreate=(t,e)=>new or({shape:t,unknownKeys:"strip",catchall:Gr.create(),typeName:M.ZodObject,...ne(e)});var ho=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function i(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(s=>new nr(s.ctx.common.issues));return z(r,{code:N.invalid_union,unionErrors:a}),G}if(r.common.async)return Promise.all(n.map(async o=>{let a={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let s=a.map(c=>new nr(c));return z(r,{code:N.invalid_union,unionErrors:s}),G}}get options(){return this._def.options}};ho.create=(t,e)=>new ho({options:t,typeName:M.ZodUnion,...ne(e)});var jn=t=>t instanceof yo?jn(t.schema):t instanceof Rr?jn(t.innerType()):t instanceof bo?[t.value]:t instanceof vo?t.options:t instanceof xo?ge.objectValues(t.enum):t instanceof wo?jn(t._def.innerType):t instanceof fo?[void 0]:t instanceof mo?[null]:t instanceof ir?[void 0,...jn(t.unwrap())]:t instanceof xn?[null,...jn(t.unwrap())]:t instanceof zc||t instanceof So?jn(t.unwrap()):t instanceof _o?jn(t._def.innerType):[],Gp=class t extends ae{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.object)return z(r,{code:N.invalid_type,expected:L.object,received:r.parsedType}),G;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(z(r,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),G)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let i=new Map;for(let o of r){let a=jn(o.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let s of a){if(i.has(s))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(s)}`);i.set(s,o)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...ne(n)})}};function Lb(t,e){let r=bn(t),n=bn(e);if(t===e)return{valid:!0,data:t};if(r===L.object&&n===L.object){let i=ge.objectKeys(e),o=ge.objectKeys(t).filter(s=>i.indexOf(s)!==-1),a={...t,...e};for(let s of o){let c=Lb(t[s],e[s]);if(!c.valid)return{valid:!1};a[s]=c.data}return{valid:!0,data:a}}else if(r===L.array&&n===L.array){if(t.length!==e.length)return{valid:!1};let i=[];for(let o=0;o<t.length;o++){let a=t[o],s=e[o],c=Lb(a,s);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===L.date&&n===L.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var go=class extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=(o,a)=>{if(Kp(o)||Kp(a))return G;let s=Lb(o.value,a.value);return s.valid?((Wp(o)||Wp(a))&&r.dirty(),{status:r.value,value:s.data}):(z(n,{code:N.invalid_intersection_types}),G)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};go.create=(t,e,r)=>new go({left:t,right:e,typeName:M.ZodIntersection,...ne(r)});var vn=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.array)return z(n,{code:N.invalid_type,expected:L.array,received:n.parsedType}),G;if(n.data.length<this._def.items.length)return z(n,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),G;!this._def.rest&&n.data.length>this._def.items.length&&(z(n,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((a,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new Ir(n,a,n.path,s)):null}).filter(a=>!!a);return n.common.async?Promise.all(o).then(a=>wt.mergeArray(r,a)):wt.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};vn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new vn({items:t,typeName:M.ZodTuple,rest:null,...ne(e)})};var Xp=class t extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.object)return z(n,{code:N.invalid_type,expected:L.object,received:n.parsedType}),G;let i=[],o=this._def.keyType,a=this._def.valueType;for(let s in n.data)i.push({key:o._parse(new Ir(n,s,n.path,s)),value:a._parse(new Ir(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?wt.mergeObjectAsync(r,i):wt.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ae?new t({keyType:e,valueType:r,typeName:M.ZodRecord,...ne(n)}):new t({keyType:yi.create(),valueType:e,typeName:M.ZodRecord,...ne(r)})}},La=class extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.map)return z(n,{code:N.invalid_type,expected:L.map,received:n.parsedType}),G;let i=this._def.keyType,o=this._def.valueType,a=[...n.data.entries()].map(([s,c],l)=>({key:i._parse(new Ir(n,s,n.path,[l,"key"])),value:o._parse(new Ir(n,c,n.path,[l,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let c of a){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return G;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of a){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return G;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(l.value,u.value)}return{status:r.value,value:s}}}};La.create=(t,e,r)=>new La({valueType:e,keyType:t,typeName:M.ZodMap,...ne(r)});var ja=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==L.set)return z(n,{code:N.invalid_type,expected:L.set,received:n.parsedType}),G;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(z(n,{code:N.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(z(n,{code:N.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function a(c){let l=new Set;for(let u of c){if(u.status==="aborted")return G;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let s=[...n.data.values()].map((c,l)=>o._parse(new Ir(n,c,n.path,l)));return n.common.async?Promise.all(s).then(c=>a(c)):a(s)}min(e,r){return new t({...this._def,minSize:{value:e,message:B.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:B.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};ja.create=(t,e)=>new ja({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...ne(e)});var Yp=class t extends ae{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.function)return z(r,{code:N.invalid_type,expected:L.function,received:r.parsedType}),G;function n(s,c){return Fc({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Na(),Ln].filter(l=>!!l),issueData:{code:N.invalid_arguments,argumentsError:c}})}function i(s,c){return Fc({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Na(),Ln].filter(l=>!!l),issueData:{code:N.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof vi){let s=this;return It(async function(...c){let l=new nr([]),u=await s._def.args.parseAsync(c,o).catch(h=>{throw l.addIssue(n(c,h)),l}),p=await Reflect.apply(a,this,u);return await s._def.returns._def.type.parseAsync(p,o).catch(h=>{throw l.addIssue(i(p,h)),l})})}else{let s=this;return It(function(...c){let l=s._def.args.safeParse(c,o);if(!l.success)throw new nr([n(c,l.error)]);let u=Reflect.apply(a,this,l.data),p=s._def.returns.safeParse(u,o);if(!p.success)throw new nr([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:vn.create(e).rest(qn.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||vn.create([]).rest(qn.create()),returns:r||qn.create(),typeName:M.ZodFunction,...ne(n)})}},yo=class extends ae{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};yo.create=(t,e)=>new yo({getter:t,typeName:M.ZodLazy,...ne(e)});var bo=class extends ae{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return z(r,{received:r.data,code:N.invalid_literal,expected:this._def.value}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};bo.create=(t,e)=>new bo({value:t,typeName:M.ZodLiteral,...ne(e)});function dI(t,e){return new vo({values:t,typeName:M.ZodEnum,...ne(e)})}var vo=class t extends ae{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{expected:ge.joinValues(n),received:r.parsedType,code:N.invalid_type}),G}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return z(r,{received:r.data,code:N.invalid_enum_value,options:n}),G}return It(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};vo.create=dI;var xo=class extends ae{_parse(e){let r=ge.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==L.string&&n.parsedType!==L.number){let i=ge.objectValues(r);return z(n,{expected:ge.joinValues(i),received:n.parsedType,code:N.invalid_type}),G}if(this._cache||(this._cache=new Set(ge.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=ge.objectValues(r);return z(n,{received:n.data,code:N.invalid_enum_value,options:i}),G}return It(e.data)}get enum(){return this._def.values}};xo.create=(t,e)=>new xo({values:t,typeName:M.ZodNativeEnum,...ne(e)});var vi=class extends ae{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==L.promise&&r.common.async===!1)return z(r,{code:N.invalid_type,expected:L.promise,received:r.parsedType}),G;let n=r.parsedType===L.promise?r.data:Promise.resolve(r.data);return It(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};vi.create=(t,e)=>new vi({type:t,typeName:M.ZodPromise,...ne(e)});var Rr=class extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:a=>{z(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(n.data,o);if(n.common.async)return Promise.resolve(a).then(async s=>{if(r.value==="aborted")return G;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?G:c.status==="dirty"?so(c.value):r.value==="dirty"?so(c.value):c});{if(r.value==="aborted")return G;let s=this._def.schema._parseSync({data:a,path:n.path,parent:n});return s.status==="aborted"?G:s.status==="dirty"?so(s.value):r.value==="dirty"?so(s.value):s}}if(i.type==="refinement"){let a=s=>{let c=i.refinement(s,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?G:(s.status==="dirty"&&r.dirty(),a(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?G:(s.status==="dirty"&&r.dirty(),a(s.value).then(()=>({status:r.value,value:s.value}))))}if(i.type==="transform")if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!gi(a))return G;let s=i.transform(a.value,o);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>gi(a)?Promise.resolve(i.transform(a.value,o)).then(s=>({status:r.value,value:s})):G);ge.assertNever(i)}};Rr.create=(t,e,r)=>new Rr({schema:t,typeName:M.ZodEffects,effect:e,...ne(r)});Rr.createWithPreprocess=(t,e,r)=>new Rr({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...ne(r)});var ir=class extends ae{_parse(e){return this._getType(e)===L.undefined?It(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ir.create=(t,e)=>new ir({innerType:t,typeName:M.ZodOptional,...ne(e)});var xn=class extends ae{_parse(e){return this._getType(e)===L.null?It(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xn.create=(t,e)=>new xn({innerType:t,typeName:M.ZodNullable,...ne(e)});var wo=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===L.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};wo.create=(t,e)=>new wo({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ne(e)});var _o=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ma(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new nr(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new nr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};_o.create=(t,e)=>new _o({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ne(e)});var qa=class extends ae{_parse(e){if(this._getType(e)!==L.nan){let n=this._getOrReturnCtx(e);return z(n,{code:N.invalid_type,expected:L.nan,received:n.parsedType}),G}return{status:"valid",value:e.data}}};qa.create=t=>new qa({typeName:M.ZodNaN,...ne(t)});var HB=Symbol("zod_brand"),zc=class extends ae{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Lc=class t extends ae{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?G:o.status==="dirty"?(r.dirty(),so(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?G:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:M.ZodPipeline})}},So=class extends ae{_parse(e){let r=this._def.innerType._parse(e),n=i=>(gi(i)&&(i.value=Object.freeze(i.value)),i);return Ma(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};So.create=(t,e)=>new So({innerType:t,typeName:M.ZodReadonly,...ne(e)});function cI(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function fI(t,e={},r){return t?bi.create().superRefine((n,i)=>{let o=t(n);if(o instanceof Promise)return o.then(a=>{if(!a){let s=cI(e,n),c=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:c})}});if(!o){let a=cI(e,n),s=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:s})}}):bi.create()}var ZB={object:or.lazycreate},M;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));var KB=(t,e={message:`Input not instance of ${t.name}`})=>fI(r=>r instanceof t,e),mI=yi.create,hI=co.create,WB=qa.create,GB=lo.create,gI=uo.create,XB=po.create,YB=Fa.create,QB=fo.create,eU=mo.create,tU=bi.create,rU=qn.create,nU=Gr.create,iU=za.create,oU=Vn.create,jb=or.create,aU=or.strictCreate,sU=ho.create,cU=Gp.create,lU=go.create,uU=vn.create,pU=Xp.create,dU=La.create,fU=ja.create,mU=Yp.create,hU=yo.create,gU=bo.create,yU=vo.create,bU=xo.create,vU=vi.create,xU=Rr.create,wU=ir.create,_U=xn.create,SU=Rr.createWithPreprocess,EU=Lc.create,kU=()=>mI().optional(),TU=()=>hI().optional(),CU=()=>gI().optional(),AU={string:t=>yi.create({...t,coerce:!0}),number:t=>co.create({...t,coerce:!0}),boolean:t=>uo.create({...t,coerce:!0}),bigint:t=>lo.create({...t,coerce:!0}),date:t=>po.create({...t,coerce:!0})};var IU=G;var PU=$("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");$e.init(t,e),t.def=e,t.parse=(r,n)=>Ff(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>ji(t,r,n),t.parseAsync=async(r,n)=>Lf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>qi(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>gr(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)});var $U=$("ZodMiniObject",(t,e)=>{jl.init(t,e),PU.init(t,e),ye.defineLazy(t,"shape",()=>e.shape)});function qb(t,e){let r={type:"object",get shape(){return ye.assignProp(this,"shape",{...t}),this.shape},...ye.normalizeParams(e)};return new $U(r)}function Pr(t){return!!t._zod}function Eo(t){let e=Object.values(t);if(e.length===0)return qb({});let r=e.every(Pr),n=e.every(i=>!Pr(i));if(r)return qb(t);if(n)return jb(t);throw new Error("Mixed Zod versions detected in object shape.")}function xi(t,e){return Pr(t)?ji(t,e):t.safeParse(e)}async function Qp(t,e){return Pr(t)?await qi(t,e):await t.safeParseAsync(e)}function wi(t){if(!t)return;let e;if(Pr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Va(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(i=>typeof i=="object"&&i!==null&&(i._def!==void 0||i._zod!==void 0||typeof i.parse=="function")))return Eo(t)}}if(Pr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function ed(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function yI(t){return t.description}function bI(t){if(Pr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function td(t){if(Pr(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}function _i(t){return t==="completed"||t==="failed"||t==="cancelled"}var xI=Symbol("Let zodToJsonSchema decide on which parser to use");var vI={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},wI=t=>typeof t=="string"?{...vI,name:t}:{...vI,...t};var _I=t=>{let e=wI(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Vb(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,i){t[e]=r,Vb(t,e,n,i)}var rd=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?rd(e,t.currentPath):e.join("/")}}function SI(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==M.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function EI(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}function kI(){return{type:"boolean"}}function nd(t,e){return Y(t.type._def,e)}var TI=(t,e)=>Y(t.innerType._def,e);function Bb(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((i,o)=>Bb(t,e,i))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return NU(t,e)}}var NU=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r};function CI(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}function AI(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):Ke(e)}function II(t){return{type:"string",enum:Array.from(t.values)}}var MU=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function RI(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,i=[];return r.forEach(o=>{if(MU(o))i.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let a=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:s,...c}=o;a=c}else n=void 0;i.push(a)}}),i.length?{allOf:i,...n}:void 0}function PI(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Ub,Xr={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ub===void 0&&(Ub=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ub),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function id(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Yr(r,"email",n.message,e);break;case"format:idn-email":Yr(r,"idn-email",n.message,e);break;case"pattern:zod":Vt(r,Xr.email,n.message,e);break}break;case"url":Yr(r,"uri",n.message,e);break;case"uuid":Yr(r,"uuid",n.message,e);break;case"regex":Vt(r,n.regex,n.message,e);break;case"cuid":Vt(r,Xr.cuid,n.message,e);break;case"cuid2":Vt(r,Xr.cuid2,n.message,e);break;case"startsWith":Vt(r,RegExp(`^${Jb(n.value,e)}`),n.message,e);break;case"endsWith":Vt(r,RegExp(`${Jb(n.value,e)}$`),n.message,e);break;case"datetime":Yr(r,"date-time",n.message,e);break;case"date":Yr(r,"date",n.message,e);break;case"time":Yr(r,"time",n.message,e);break;case"duration":Yr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Vt(r,RegExp(Jb(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Yr(r,"ipv4",n.message,e),n.version!=="v4"&&Yr(r,"ipv6",n.message,e);break}case"base64url":Vt(r,Xr.base64url,n.message,e);break;case"jwt":Vt(r,Xr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Vt(r,Xr.ipv4Cidr,n.message,e),n.version!=="v4"&&Vt(r,Xr.ipv6Cidr,n.message,e);break}case"emoji":Vt(r,Xr.emoji(),n.message,e);break;case"ulid":{Vt(r,Xr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Yr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Vt(r,Xr.base64,n.message,e);break}}break}case"nanoid":Vt(r,Xr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Jb(t,e){return e.patternStrategy==="escape"?FU(t):t}var DU=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function FU(t){let e="";for(let r=0;r<t.length;r++)DU.has(t[r])||(e+="\\"),e+=t[r];return e}function Yr(t,e,r,n){t.format||t.anyOf?.some(i=>i.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):xe(t,"format",e,r,n)}function Vt(t,e,r,n){t.pattern||t.allOf?.some(i=>i.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:$I(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",$I(e,n),r,n)}function $I(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,i="",o=!1,a=!1,s=!1;for(let c=0;c<n.length;c++){if(o){i+=n[c],o=!1;continue}if(r.i){if(a){if(n[c].match(/[a-z]/)){s?(i+=n[c],i+=`${n[c-2]}-${n[c]}`.toUpperCase(),s=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(i+=n[c],s=!0):i+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){i+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){i+=`(^|(?<=[\r
|
|
127
127
|
]))`;continue}else if(n[c]==="$"){i+=`($|(?=[\r
|
|
128
128
|
]))`;continue}}if(r.s&&n[c]==="."){i+=a?`${n[c]}\r
|
|
129
129
|
`:`[${n[c]}\r
|