mcp-server-wom-call 0.0.11 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/config/constants.d.ts +17 -0
  2. package/dist/config/constants.d.ts.map +1 -0
  3. package/dist/config/index.d.ts +37 -0
  4. package/dist/config/index.d.ts.map +1 -0
  5. package/dist/config/s3.d.ts +20 -0
  6. package/dist/config/s3.d.ts.map +1 -0
  7. package/dist/config/systems.d.ts +40 -0
  8. package/dist/config/systems.d.ts.map +1 -0
  9. package/dist/index.d.ts +1 -1
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +3 -3
  12. package/dist/index.js.map +1 -1
  13. package/dist/server.d.ts +14 -0
  14. package/dist/server.d.ts.map +1 -0
  15. package/dist/services/esb.d.ts +8 -0
  16. package/dist/services/esb.d.ts.map +1 -0
  17. package/dist/services/s3.d.ts +20 -0
  18. package/dist/services/s3.d.ts.map +1 -0
  19. package/dist/services/workorder.d.ts +15 -0
  20. package/dist/services/workorder.d.ts.map +1 -0
  21. package/dist/tools/base.d.ts +13 -0
  22. package/dist/tools/base.d.ts.map +1 -0
  23. package/dist/tools/index.d.ts +31 -0
  24. package/dist/tools/index.d.ts.map +1 -0
  25. package/dist/tools/upload/index.d.ts +4 -0
  26. package/dist/tools/upload/index.d.ts.map +1 -0
  27. package/dist/tools/upload/multiple.d.ts +10 -0
  28. package/dist/tools/upload/multiple.d.ts.map +1 -0
  29. package/dist/tools/upload/schema.d.ts +4 -0
  30. package/dist/tools/upload/schema.d.ts.map +1 -0
  31. package/dist/tools/upload/single.d.ts +10 -0
  32. package/dist/tools/upload/single.d.ts.map +1 -0
  33. package/dist/tools/workorder/create.d.ts +10 -0
  34. package/dist/tools/workorder/create.d.ts.map +1 -0
  35. package/dist/tools/workorder/index.d.ts +3 -0
  36. package/dist/tools/workorder/index.d.ts.map +1 -0
  37. package/dist/tools/workorder/schema.d.ts +3 -0
  38. package/dist/tools/workorder/schema.d.ts.map +1 -0
  39. package/dist/types/esb.d.ts +30 -0
  40. package/dist/types/esb.d.ts.map +1 -0
  41. package/dist/types/index.d.ts +4 -0
  42. package/dist/types/index.d.ts.map +1 -0
  43. package/dist/types/upload.d.ts +33 -0
  44. package/dist/types/upload.d.ts.map +1 -0
  45. package/dist/types/workorder.d.ts +23 -0
  46. package/dist/types/workorder.d.ts.map +1 -0
  47. package/dist/utils/formatter.d.ts +6 -0
  48. package/dist/utils/formatter.d.ts.map +1 -0
  49. package/dist/utils/logger.d.ts +7 -0
  50. package/dist/utils/logger.d.ts.map +1 -0
  51. package/dist/validators/index.d.ts +4 -0
  52. package/dist/validators/index.d.ts.map +1 -0
  53. package/dist/validators/input.d.ts +20 -0
  54. package/dist/validators/input.d.ts.map +1 -0
  55. package/dist/validators/response.d.ts +16 -0
  56. package/dist/validators/response.d.ts.map +1 -0
  57. package/dist/validators/upload.d.ts +16 -0
  58. package/dist/validators/upload.d.ts.map +1 -0
  59. package/package.json +2 -1
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Server configuration
3
+ */
4
+ export declare const SERVER_CONFIG: {
5
+ readonly name: "mcp-server-wom-call";
6
+ readonly description: "MCP Server for Work Order Management System Integration";
7
+ };
8
+ /**
9
+ * Validation limits
10
+ */
11
+ export declare const VALIDATION_LIMITS: {
12
+ readonly TITLE_MAX_LENGTH: 100;
13
+ readonly CONTENT_MAX_LENGTH: 5000;
14
+ readonly NAME_MAX_LENGTH: 100;
15
+ readonly MAX_FILE_SIZE: number;
16
+ };
17
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/config/constants.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,aAAa;;;CAGhB,CAAA;AAEV;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;CAKpB,CAAA"}
@@ -0,0 +1,37 @@
1
+ import 'dotenv/config';
2
+ import { S3Config } from './s3';
3
+ /**
4
+ * Application configuration
5
+ */
6
+ export declare class Config {
7
+ private static instance;
8
+ private _esbUrl;
9
+ private _s3Config;
10
+ private constructor();
11
+ static getInstance(): Config;
12
+ /**
13
+ * Load configuration from environment variables
14
+ */
15
+ private loadFromEnv;
16
+ /**
17
+ * Get ESB URL
18
+ */
19
+ get esbUrl(): string;
20
+ /**
21
+ * Set ESB URL (for testing or runtime configuration)
22
+ */
23
+ setEsbUrl(url: string): void;
24
+ /**
25
+ * Get S3 configuration
26
+ */
27
+ get s3(): S3Config;
28
+ /**
29
+ * Validate configuration
30
+ */
31
+ validate(): void;
32
+ }
33
+ export declare const config: Config;
34
+ export * from './constants';
35
+ export * from './systems';
36
+ export * from './s3';
37
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/config/index.ts"],"names":[],"mappings":"AAAA,OAAO,eAAe,CAAA;AACtB,OAAO,EAAE,QAAQ,EAAgB,MAAM,MAAM,CAAA;AAE7C;;GAEG;AACH,qBAAa,MAAM;IACjB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAQ;IAE/B,OAAO,CAAC,OAAO,CAAa;IAC5B,OAAO,CAAC,SAAS,CAAU;IAE3B,OAAO;IAKP,MAAM,CAAC,WAAW,IAAI,MAAM;IAO5B;;OAEG;IACH,OAAO,CAAC,WAAW;IAInB;;OAEG;IACH,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED;;OAEG;IACH,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAI5B;;OAEG;IACH,IAAI,EAAE,IAAI,QAAQ,CAEjB;IAED;;OAEG;IACH,QAAQ,IAAI,IAAI;CAOjB;AAED,eAAO,MAAM,MAAM,QAAuB,CAAA;AAG1C,cAAc,aAAa,CAAA;AAC3B,cAAc,WAAW,CAAA;AACzB,cAAc,MAAM,CAAA"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * S3 configuration
3
+ */
4
+ export interface S3Config {
5
+ endpoint: string;
6
+ region: string;
7
+ accessKey: string;
8
+ secretKey: string;
9
+ bucket: string;
10
+ publicUrl: string;
11
+ }
12
+ /**
13
+ * Load S3 configuration from environment
14
+ */
15
+ export declare function loadS3Config(): S3Config;
16
+ /**
17
+ * Validate S3 configuration
18
+ */
19
+ export declare function validateS3Config(config: S3Config): void;
20
+ //# sourceMappingURL=s3.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"s3.d.ts","sourceRoot":"","sources":["../../src/config/s3.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,QAAQ,EAAE,MAAM,CAAA;IAChB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,MAAM,CAAA;IACjB,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,MAAM,CAAA;CAClB;AAED;;GAEG;AACH,wBAAgB,YAAY,IAAI,QAAQ,CASvC;AAED;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,QAAQ,GAAG,IAAI,CASvD"}
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Supported system codes and their descriptions
3
+ */
4
+ export declare const SUPPORTED_SYSTEMS: {
5
+ readonly SRM: "Supplier Relationship Management - 供应商管理、采购流程、供应商评估";
6
+ readonly SPMS: "Spare Parts Management System - 备件管理、库存查询、备件申领";
7
+ readonly POS: "Legacy Warehouse Management System - 仓库出入库、库存盘点、物料管理";
8
+ readonly SAP: "SAP ERP System - ERP 核心业务、财务、生产、销售";
9
+ readonly MDM: "Master Data Management - 主数据维护、数据质量、数据同步";
10
+ readonly WOM: "Work Order Management - 工单管理、任务跟踪、工单审批";
11
+ readonly OA: "Office Automation System - 办公自动化、审批流程、公文管理";
12
+ readonly ESB: "Enterprise Service Bus - 系统集成、接口管理、数据交换";
13
+ readonly TMS: "Transportation Management System - 运输调度、物流跟踪、配送管理";
14
+ readonly '\u7F51\u7EDC/\u786C\u4EF6': "Network & Hardware Support - 网络故障、硬件报修、IT 基础设施";
15
+ readonly CRM: "Customer Relationship Management - 客户管理、销售跟进、客户服务";
16
+ readonly QMS: "Quality Management System - 质量检验、不合格品处理、质量追溯";
17
+ readonly VOSA: "Digital Product Platform - 数字化平台、创新项目、新产品功能";
18
+ readonly EAM: "Enterprise Asset Management - 资产管理、设备维护、资源调配";
19
+ };
20
+ /**
21
+ * System code type
22
+ */
23
+ export type SystemCode = keyof typeof SUPPORTED_SYSTEMS;
24
+ /**
25
+ * Get formatted system list description for tool schema
26
+ */
27
+ export declare function getSystemListDescription(): string;
28
+ /**
29
+ * Validate system code
30
+ */
31
+ export declare function isValidSystemCode(code: string): code is SystemCode;
32
+ /**
33
+ * Get system description
34
+ */
35
+ export declare function getSystemDescription(code: SystemCode): string;
36
+ /**
37
+ * Get all system codes
38
+ */
39
+ export declare function getAllSystemCodes(): SystemCode[];
40
+ //# sourceMappingURL=systems.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"systems.d.ts","sourceRoot":"","sources":["../../src/config/systems.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;;;;;;;;;CAepB,CAAA;AAEV;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG,MAAM,OAAO,iBAAiB,CAAA;AAEvD;;GAEG;AACH,wBAAgB,wBAAwB,IAAI,MAAM,CAsBjD;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,IAAI,UAAU,CAElE;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,CAE7D;AAED;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,UAAU,EAAE,CAEhD"}
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import 'dotenv/config';
1
+ export {};
2
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,eAAe,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * mcp-server-wom-call v0.0.11
4
- * Build Date: 2025-12-22T09:33:23.053Z
3
+ * mcp-server-wom-call v0.0.12
4
+ * Build Date: 2025-12-24T03:50:15.523Z
5
5
  * Author: Twyford Ltd.
6
6
  * @license MIT
7
7
  */
8
- import e from"fs";import t from"path";import s from"os";import r from"crypto";import n from"node:process";var a,i,o,d,c,u,l,h,p={exports:{}};u||(u=1,function(){if(a)return p.exports;a=1;const n=e,i=t,o=s,d=r,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function u(e){}function l(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function h(e,t){let s;try{s=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const r=s.password;if(!r){const e=Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const n=s.searchParams.get("environment");if(!n){const e=Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const a="DOTENV_VAULT_"+n.toUpperCase(),i=e.parsed[a];if(!i){const e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${a} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:i,key:r}}function m(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const s of e.path)n.existsSync(s)&&(t=s.endsWith(".vault")?s:s+".vault");else t=e.path.endsWith(".vault")?e.path:e.path+".vault";else t=i.resolve(process.cwd(),".env.vault");return n.existsSync(t)?t:null}function f(e){return"~"===e[0]?i.join(o.homedir(),e.slice(1)):e}const _={configDotenv:function(e){const t=i.resolve(process.cwd(),".env");let s="utf8";const r=!(!e||!e.debug),a=!e||!("quiet"in e)||e.quiet;e&&e.encoding&&(s=e.encoding);let o,d=[t];if(e&&e.path)if(Array.isArray(e.path)){d=[];for(const t of e.path)d.push(f(t))}else d=[f(e.path)];const c={};for(const t of d)try{const r=_.parse(n.readFileSync(t,{encoding:s}));_.populate(c,r,e)}catch(e){r&&u(e.message),o=e}let l=process.env;if(e&&null!=e.processEnv&&(l=e.processEnv),_.populate(l,c,e),r||!a){Object.keys(c).length;const e=[];for(const t of d)try{const s=i.relative(process.cwd(),t);e.push(s)}catch(e){r&&u(e.message),o=e}e.join(",")}return o?{parsed:c,error:o}:{parsed:c}},_configVault:function(e){!e||e.debug,!e||!("quiet"in e)||e.quiet;const t=_._parseVault(e);let s=process.env;return e&&null!=e.processEnv&&(s=e.processEnv),_.populate(s,t,e),{parsed:t}},_parseVault:function(e){const t=m(e=e||{});e.path=t;const s=_.configDotenv(e);if(!s.parsed){const e=Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const r=l(e).split(","),n=r.length;let a;for(let e=0;e<n;e++)try{const t=h(s,r[e].trim());a=_.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=n)throw t}return _.parse(a)},config:function(e){return 0===l(e).length?_.configDotenv(e):m(e)?_._configVault(e):_.configDotenv(e)},decrypt:function(e,t){const s=Buffer.from(t.slice(-64),"hex");let r=Buffer.from(e,"base64");const n=r.subarray(0,12),a=r.subarray(-16);r=r.subarray(12,-16);try{const e=d.createDecipheriv("aes-256-gcm",s,n);return e.setAuthTag(a),`${e.update(r)}${e.final()}`}catch(e){const t=e instanceof RangeError,s="Invalid key length"===e.message,r="Unsupported state or unable to authenticate data"===e.message;if(t||s){const e=Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(r){const e=Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let s,r=e.toString();for(r=r.replace(/\r\n?/gm,"\n");null!=(s=c.exec(r));){const e=s[1];let r=s[2]||"";r=r.trim();const n=r[0];r=r.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===n&&(r=r.replace(/\\n/g,"\n"),r=r.replace(/\\r/g,"\r")),t[e]=r}return t},populate:function(e,t,s={}){const r=!(!s||!s.debug),n=!(!s||!s.override);if("object"!=typeof t){const e=Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const s of Object.keys(t))!{}.hasOwnProperty.call(e,s)?e[s]=t[s]:(!0===n&&(e[s]=t[s]),r&&u())}};return p.exports.configDotenv=_.configDotenv,p.exports._configVault=_._configVault,p.exports._parseVault=_._parseVault,p.exports.config=_.config,p.exports.decrypt=_.decrypt,p.exports.parse=_.parse,p.exports.populate=_.populate,p.exports=_,p.exports}().config(Object.assign({},function(){if(o)return i;o=1;const e={};return null!=process.env.DOTENV_CONFIG_ENCODING&&(e.encoding=process.env.DOTENV_CONFIG_ENCODING),null!=process.env.DOTENV_CONFIG_PATH&&(e.path=process.env.DOTENV_CONFIG_PATH),null!=process.env.DOTENV_CONFIG_QUIET&&(e.quiet=process.env.DOTENV_CONFIG_QUIET),null!=process.env.DOTENV_CONFIG_DEBUG&&(e.debug=process.env.DOTENV_CONFIG_DEBUG),null!=process.env.DOTENV_CONFIG_OVERRIDE&&(e.override=process.env.DOTENV_CONFIG_OVERRIDE),null!=process.env.DOTENV_CONFIG_DOTENV_KEY&&(e.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY),i=e}(),function(){if(c)return d;c=1;const e=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;return d=function(t){const s=t.reduce(function(t,s){const r=s.match(e);return r&&(t[r[1]]=r[2]),t},{});return"quiet"in s||(s.quiet="true"),s}}()(process.argv)))),function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw Error()},e.arrayToEnum=e=>{const t={};for(const s of e)t[s]=s;return t},e.getValidEnumValues=t=>{const s=e.objectKeys(t).filter(e=>"number"!=typeof t[t[e]]),r={};for(const e of s)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const s in e)({}).hasOwnProperty.call(e,s)&&t.push(s);return t},e.find=(e,t)=>{for(const s of e)if(t(s))return s},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map(e=>"string"==typeof e?`'${e}'`:e).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(l||(l={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(h||(h={}));const m=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),f=e=>{switch(typeof e){case"undefined":return m.undefined;case"string":return m.string;case"number":return Number.isNaN(e)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(e)?m.array:null===e?m.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?m.promise:"undefined"!=typeof Map&&e instanceof Map?m.map:"undefined"!=typeof Set&&e instanceof Set?m.set:void 0!==Date&&e instanceof Date?m.date:m.object;default:return m.unknown}},_=l.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"]);class g extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},s={_errors:[]},r=e=>{for(const n of e.issues)if("invalid_union"===n.code)n.unionErrors.map(r);else if("invalid_return_type"===n.code)r(n.returnTypeError);else if("invalid_arguments"===n.code)r(n.argumentsError);else if(0===n.path.length)s._errors.push(t(n));else{let e=s,r=0;for(;r<n.path.length;){const s=n.path[r];r===n.path.length-1?(e[s]=e[s]||{_errors:[]},e[s]._errors.push(t(n))):e[s]=e[s]||{_errors:[]},e=e[s],r++}}};return r(this),s}static assert(e){if(!(e instanceof g))throw Error("Not a ZodError: "+e)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},s=[];for(const r of this.issues)if(r.path.length>0){const s=r.path[0];t[s]=t[s]||[],t[s].push(e(r))}else s.push(e(r));return{formErrors:s,fieldErrors:t}}get formErrors(){return this.flatten()}}g.create=e=>new g(e);const y=(e,t)=>{let s;switch(e.code){case _.invalid_type:s=e.received===m.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case _.invalid_literal:s="Invalid literal value, expected "+JSON.stringify(e.expected,l.jsonStringifyReplacer);break;case _.unrecognized_keys:s="Unrecognized key(s) in object: "+l.joinValues(e.keys,", ");break;case _.invalid_union:s="Invalid input";break;case _.invalid_union_discriminator:s="Invalid discriminator value. Expected "+l.joinValues(e.options);break;case _.invalid_enum_value:s=`Invalid enum value. Expected ${l.joinValues(e.options)}, received '${e.received}'`;break;case _.invalid_arguments:s="Invalid function arguments";break;case _.invalid_return_type:s="Invalid function return type";break;case _.invalid_date:s="Invalid date";break;case _.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(s=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(s=`${s} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?s=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?s=`Invalid input: must end with "${e.validation.endsWith}"`:l.assertNever(e.validation):s="regex"!==e.validation?"Invalid "+e.validation:"Invalid";break;case _.too_small:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type||"bigint"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(+e.minimum)}`:"Invalid input";break;case _.too_big:s="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(+e.maximum)}`:"Invalid input";break;case _.custom:s="Invalid input";break;case _.invalid_intersection_types:s="Intersection results could not be merged";break;case _.not_multiple_of:s="Number must be a multiple of "+e.multipleOf;break;case _.not_finite:s="Number must be finite";break;default:s=t.defaultError,l.assertNever(e)}return{message:s}};let v=y;function x(e,t){const s=v,r=(e=>{const{data:t,path:s,errorMaps:r,issueData:n}=e,a=[...s,...n.path||[]],i={...n,path:a};if(void 0!==n.message)return{...n,path:a,message:n.message};let o="";const d=r.filter(e=>!!e).slice().reverse();for(const e of d)o=e(i,{data:t,defaultError:o}).message;return{...n,path:a,message:o}})({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,s,s===y?void 0:y].filter(e=>!!e)});e.common.issues.push(r)}class E{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const s=[];for(const r of t){if("aborted"===r.status)return b;"dirty"===r.status&&e.dirty(),s.push(r.value)}return{status:e.value,value:s}}static async mergeObjectAsync(e,t){const s=[];for(const e of t){const t=await e.key,r=await e.value;s.push({key:t,value:r})}return E.mergeObjectSync(e,s)}static mergeObjectSync(e,t){const s={};for(const r of t){const{key:t,value:n}=r;if("aborted"===t.status)return b;if("aborted"===n.status)return b;"dirty"===t.status&&e.dirty(),"dirty"===n.status&&e.dirty(),"__proto__"===t.value||void 0===n.value&&!r.alwaysSet||(s[t.value]=n.value)}return{status:e.value,value:s}}}const b=Object.freeze({status:"aborted"}),T=e=>({status:"dirty",value:e}),k=e=>({status:"valid",value:e}),S=e=>"aborted"===e.status,w=e=>"dirty"===e.status,O=e=>"valid"===e.status,A=e=>"undefined"!=typeof Promise&&e instanceof Promise;var N;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(N||(N={}));class R{constructor(e,t,s,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=r}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}}const I=(e,t)=>{if(O(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new g(e.common.issues);return this._error=t,this._error}}};function C(e){if(!e)return{};const{errorMap:t,invalid_type_error:s,required_error:r,description:n}=e;if(t&&(s||r))throw Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');return t?{errorMap:t,description:n}:{errorMap:(t,n)=>{const{message:a}=e;return"invalid_enum_value"===t.code?{message:a??n.defaultError}:void 0===n.data?{message:a??r??n.defaultError}:"invalid_type"!==t.code?{message:n.defaultError}:{message:a??s??n.defaultError}},description:n}}class D{get description(){return this._def.description}_getType(e){return f(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:f(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new E,ctx:{common:e.parent.common,data:e.data,parsedType:f(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(A(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:f(e)},r=this._parseSync({data:e,path:s.path,parent:s});return I(s,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:f(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return O(s)?{value:s.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>O(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:f(e)},r=this._parse({data:e,path:s.path,parent:s}),n=await(A(r)?r:Promise.resolve(r));return I(s,n)}refine(e,t){const s=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement((t,r)=>{const n=e(t),a=()=>r.addIssue({code:_.custom,...s(t)});return"undefined"!=typeof Promise&&n instanceof Promise?n.then(e=>!!e||(a(),!1)):!!n||(a(),!1)})}refinement(e,t){return this._refinement((s,r)=>!!e(s)||(r.addIssue("function"==typeof t?t(s,r):t),!1))}_refinement(e){return new Ze({schema:this,typeName:Fe.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:e=>this["~validate"](e)}}optional(){return je.create(this,this._def)}nullable(){return Pe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _e.create(this)}promise(){return De.create(this,this._def)}or(e){return ve.create([this,e],this._def)}and(e){return Te.create(this,e,this._def)}transform(e){return new Ze({...C(this._def),schema:this,typeName:Fe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new $e({...C(this._def),innerType:this,defaultValue:t,typeName:Fe.ZodDefault})}brand(){return new qe({typeName:Fe.ZodBranded,type:this,...C(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new Ue({...C(this._def),innerType:this,catchValue:t,typeName:Fe.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return Ve.create(this,e)}readonly(){return Le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Z=/^c[^\s-]{8,}$/i,j=/^[0-9a-z]+$/,P=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$=/^[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,U=/^[a-z0-9_-]{21}$/i,M=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,q=/^[-+]?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)?)??$/,V=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let L;const F=/^(?:(?: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])$/,H=/^(?:(?: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])$/,B=/^(([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]))$/,z=/^(([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])$/,Q=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,K=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,W="((\\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])))",Y=RegExp(`^${W}$`);function J(e){let t="[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t+="(\\.\\d+)?"),`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function G(e){return RegExp(`^${J(e)}$`)}function X(e){let t=`${W}T${J(e)}`;const s=[];return s.push(e.local?"Z?":"Z"),e.offset&&s.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${s.join("|")})`,RegExp(`^${t}$`)}function ee(e,t){return!("v4"!==t&&t||!F.test(e))||!("v6"!==t&&t||!B.test(e))}function te(e,t){if(!M.test(e))return!1;try{const[s]=e.split(".");if(!s)return!1;const r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(r));return!("object"!=typeof n||null===n||"typ"in n&&"JWT"!==n?.typ||!n.alg||t&&n.alg!==t)}catch{return!1}}function se(e,t){return!("v4"!==t&&t||!H.test(e))||!("v6"!==t&&t||!z.test(e))}class re extends D{_parse(e){if(this._def.coerce&&(e.data=e.data+""),this._getType(e)!==m.string){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.string,received:t.parsedType}),b}const t=new E;let s;for(const r of this._def.checks)if("min"===r.kind)e.data.length<r.value&&(s=this._getOrReturnCtx(e,s),x(s,{code:_.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("max"===r.kind)e.data.length>r.value&&(s=this._getOrReturnCtx(e,s),x(s,{code:_.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),t.dirty());else if("length"===r.kind){const n=e.data.length>r.value,a=e.data.length<r.value;(n||a)&&(s=this._getOrReturnCtx(e,s),n?x(s,{code:_.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):a&&x(s,{code:_.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if("email"===r.kind)V.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"email",code:_.invalid_string,message:r.message}),t.dirty());else if("emoji"===r.kind)L||(L=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),L.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"emoji",code:_.invalid_string,message:r.message}),t.dirty());else if("uuid"===r.kind)$.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"uuid",code:_.invalid_string,message:r.message}),t.dirty());else if("nanoid"===r.kind)U.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"nanoid",code:_.invalid_string,message:r.message}),t.dirty());else if("cuid"===r.kind)Z.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"cuid",code:_.invalid_string,message:r.message}),t.dirty());else if("cuid2"===r.kind)j.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"cuid2",code:_.invalid_string,message:r.message}),t.dirty());else if("ulid"===r.kind)P.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"ulid",code:_.invalid_string,message:r.message}),t.dirty());else if("url"===r.kind)try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),x(s,{validation:"url",code:_.invalid_string,message:r.message}),t.dirty()}else"regex"===r.kind?(r.regex.lastIndex=0,r.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"regex",code:_.invalid_string,message:r.message}),t.dirty())):"trim"===r.kind?e.data=e.data.trim():"includes"===r.kind?e.data.includes(r.value,r.position)||(s=this._getOrReturnCtx(e,s),x(s,{code:_.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):"toLowerCase"===r.kind?e.data=e.data.toLowerCase():"toUpperCase"===r.kind?e.data=e.data.toUpperCase():"startsWith"===r.kind?e.data.startsWith(r.value)||(s=this._getOrReturnCtx(e,s),x(s,{code:_.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):"endsWith"===r.kind?e.data.endsWith(r.value)||(s=this._getOrReturnCtx(e,s),x(s,{code:_.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):"datetime"===r.kind?X(r).test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{code:_.invalid_string,validation:"datetime",message:r.message}),t.dirty()):"date"===r.kind?Y.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{code:_.invalid_string,validation:"date",message:r.message}),t.dirty()):"time"===r.kind?G(r).test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{code:_.invalid_string,validation:"time",message:r.message}),t.dirty()):"duration"===r.kind?q.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"duration",code:_.invalid_string,message:r.message}),t.dirty()):"ip"===r.kind?ee(e.data,r.version)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"ip",code:_.invalid_string,message:r.message}),t.dirty()):"jwt"===r.kind?te(e.data,r.alg)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"jwt",code:_.invalid_string,message:r.message}),t.dirty()):"cidr"===r.kind?se(e.data,r.version)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"cidr",code:_.invalid_string,message:r.message}),t.dirty()):"base64"===r.kind?Q.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"base64",code:_.invalid_string,message:r.message}),t.dirty()):"base64url"===r.kind?K.test(e.data)||(s=this._getOrReturnCtx(e,s),x(s,{validation:"base64url",code:_.invalid_string,message:r.message}),t.dirty()):l.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(t=>e.test(t),{validation:t,code:_.invalid_string,...N.errToObj(s)})}_addCheck(e){return new re({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.errToObj(e)})}datetime(e){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...N.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===e?.precision?null:e?.precision,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...N.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...N.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...N.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...N.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...N.errToObj(t)})}nonempty(e){return this.min(1,N.errToObj(e))}trim(){return new re({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new re({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new re({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>"datetime"===e.kind)}get isDate(){return!!this._def.checks.find(e=>"date"===e.kind)}get isTime(){return!!this._def.checks.find(e=>"time"===e.kind)}get isDuration(){return!!this._def.checks.find(e=>"duration"===e.kind)}get isEmail(){return!!this._def.checks.find(e=>"email"===e.kind)}get isURL(){return!!this._def.checks.find(e=>"url"===e.kind)}get isEmoji(){return!!this._def.checks.find(e=>"emoji"===e.kind)}get isUUID(){return!!this._def.checks.find(e=>"uuid"===e.kind)}get isNANOID(){return!!this._def.checks.find(e=>"nanoid"===e.kind)}get isCUID(){return!!this._def.checks.find(e=>"cuid"===e.kind)}get isCUID2(){return!!this._def.checks.find(e=>"cuid2"===e.kind)}get isULID(){return!!this._def.checks.find(e=>"ulid"===e.kind)}get isIP(){return!!this._def.checks.find(e=>"ip"===e.kind)}get isCIDR(){return!!this._def.checks.find(e=>"cidr"===e.kind)}get isBase64(){return!!this._def.checks.find(e=>"base64"===e.kind)}get isBase64url(){return!!this._def.checks.find(e=>"base64url"===e.kind)}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function ne(e,t){const s=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,n=s>r?s:r;return Number.parseInt(e.toFixed(n).replace(".",""))%Number.parseInt(t.toFixed(n).replace(".",""))/10**n}re.create=e=>new re({checks:[],typeName:Fe.ZodString,coerce:e?.coerce??!1,...C(e)});class ae extends D{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=+e.data),this._getType(e)!==m.number){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.number,received:t.parsedType}),b}let t;const s=new E;for(const r of this._def.checks)"int"===r.kind?l.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),x(t,{code:_.invalid_type,expected:"integer",received:"float",message:r.message}),s.dirty()):"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:_.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:_.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),s.dirty()):"multipleOf"===r.kind?0!==ne(e.data,r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:_.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):"finite"===r.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),x(t,{code:_.not_finite,message:r.message}),s.dirty()):l.assertNever(r);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,s,r){return new ae({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:N.toString(r)}]})}_addCheck(e){return new ae({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>"int"===e.kind||"multipleOf"===e.kind&&l.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if("finite"===s.kind||"int"===s.kind||"multipleOf"===s.kind)return!0;"min"===s.kind?(null===t||s.value>t)&&(t=s.value):"max"===s.kind&&(null===e||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ae.create=e=>new ae({checks:[],typeName:Fe.ZodNumber,coerce:e?.coerce||!1,...C(e)});class ie extends D{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)!==m.bigint)return this._getInvalidInput(e);let t;const s=new E;for(const r of this._def.checks)"min"===r.kind?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:_.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()):"max"===r.kind?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),x(t,{code:_.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),s.dirty()):"multipleOf"===r.kind?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),x(t,{code:_.not_multiple_of,multipleOf:r.value,message:r.message}),s.dirty()):l.assertNever(r);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.bigint,received:t.parsedType}),b}gte(e,t){return this.setLimit("min",e,!0,N.toString(t))}gt(e,t){return this.setLimit("min",e,!1,N.toString(t))}lte(e,t){return this.setLimit("max",e,!0,N.toString(t))}lt(e,t){return this.setLimit("max",e,!1,N.toString(t))}setLimit(e,t,s,r){return new ie({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:N.toString(r)}]})}_addCheck(e){return new ie({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ie.create=e=>new ie({checks:[],typeName:Fe.ZodBigInt,coerce:e?.coerce??!1,...C(e)});class oe extends D{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.boolean,received:t.parsedType}),b}return k(e.data)}}oe.create=e=>new oe({typeName:Fe.ZodBoolean,coerce:e?.coerce||!1,...C(e)});class de extends D{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.date,received:t.parsedType}),b}if(Number.isNaN(e.data.getTime()))return x(this._getOrReturnCtx(e),{code:_.invalid_date}),b;const t=new E;let s;for(const r of this._def.checks)"min"===r.kind?e.data.getTime()<r.value&&(s=this._getOrReturnCtx(e,s),x(s,{code:_.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),t.dirty()):"max"===r.kind?e.data.getTime()>r.value&&(s=this._getOrReturnCtx(e,s),x(s,{code:_.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),t.dirty()):l.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:N.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}de.create=e=>new de({checks:[],coerce:e?.coerce||!1,typeName:Fe.ZodDate,...C(e)});class ce extends D{_parse(e){if(this._getType(e)!==m.symbol){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.symbol,received:t.parsedType}),b}return k(e.data)}}ce.create=e=>new ce({typeName:Fe.ZodSymbol,...C(e)});class ue extends D{_parse(e){if(this._getType(e)!==m.undefined){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.undefined,received:t.parsedType}),b}return k(e.data)}}ue.create=e=>new ue({typeName:Fe.ZodUndefined,...C(e)});class le extends D{_parse(e){if(this._getType(e)!==m.null){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.null,received:t.parsedType}),b}return k(e.data)}}le.create=e=>new le({typeName:Fe.ZodNull,...C(e)});class he extends D{constructor(){super(...arguments),this._any=!0}_parse(e){return k(e.data)}}he.create=e=>new he({typeName:Fe.ZodAny,...C(e)});class pe extends D{constructor(){super(...arguments),this._unknown=!0}_parse(e){return k(e.data)}}pe.create=e=>new pe({typeName:Fe.ZodUnknown,...C(e)});class me extends D{_parse(e){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.never,received:t.parsedType}),b}}me.create=e=>new me({typeName:Fe.ZodNever,...C(e)});class fe extends D{_parse(e){if(this._getType(e)!==m.undefined){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.void,received:t.parsedType}),b}return k(e.data)}}fe.create=e=>new fe({typeName:Fe.ZodVoid,...C(e)});class _e extends D{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),r=this._def;if(t.parsedType!==m.array)return x(t,{code:_.invalid_type,expected:m.array,received:t.parsedType}),b;if(null!==r.exactLength){const e=t.data.length>r.exactLength.value,n=t.data.length<r.exactLength.value;(e||n)&&(x(t,{code:e?_.too_big:_.too_small,minimum:n?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),s.dirty())}if(null!==r.minLength&&t.data.length<r.minLength.value&&(x(t,{code:_.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),s.dirty()),null!==r.maxLength&&t.data.length>r.maxLength.value&&(x(t,{code:_.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((e,s)=>r.type._parseAsync(new R(t,e,t.path,s)))).then(e=>E.mergeArray(s,e));const n=[...t.data].map((e,s)=>r.type._parseSync(new R(t,e,t.path,s)));return E.mergeArray(s,n)}get element(){return this._def.type}min(e,t){return new _e({...this._def,minLength:{value:e,message:N.toString(t)}})}max(e,t){return new _e({...this._def,maxLength:{value:e,message:N.toString(t)}})}length(e,t){return new _e({...this._def,exactLength:{value:e,message:N.toString(t)}})}nonempty(e){return this.min(1,e)}}function ge(e){if(e instanceof ye){const t={};for(const s in e.shape){const r=e.shape[s];t[s]=je.create(ge(r))}return new ye({...e._def,shape:()=>t})}return e instanceof _e?new _e({...e._def,type:ge(e.element)}):e instanceof je?je.create(ge(e.unwrap())):e instanceof Pe?Pe.create(ge(e.unwrap())):e instanceof ke?ke.create(e.items.map(e=>ge(e))):e}_e.create=(e,t)=>new _e({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Fe.ZodArray,...C(t)});class ye extends D{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=l.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==m.object){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.object,received:t.parsedType}),b}const{status:t,ctx:s}=this._processInputParams(e),{shape:r,keys:n}=this._getCached(),a=[];if(!(this._def.catchall instanceof me&&"strip"===this._def.unknownKeys))for(const e in s.data)n.includes(e)||a.push(e);const i=[];for(const e of n){const t=r[e],n=s.data[e];i.push({key:{status:"valid",value:e},value:t._parse(new R(s,n,s.path,e)),alwaysSet:e in s.data})}if(this._def.catchall instanceof me){const e=this._def.unknownKeys;if("passthrough"===e)for(const e of a)i.push({key:{status:"valid",value:e},value:{status:"valid",value:s.data[e]}});else if("strict"===e)a.length>0&&(x(s,{code:_.unrecognized_keys,keys:a}),t.dirty());else if("strip"!==e)throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of a){const r=s.data[t];i.push({key:{status:"valid",value:t},value:e._parse(new R(s,r,s.path,t)),alwaysSet:t in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const e=[];for(const t of i){const s=await t.key,r=await t.value;e.push({key:s,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>E.mergeObjectSync(t,e)):E.mergeObjectSync(t,i)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new ye({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,s)=>{const r=this._def.errorMap?.(t,s).message??s.defaultError;return"unrecognized_keys"===t.code?{message:N.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new ye({...this._def,unknownKeys:"strip"})}passthrough(){return new ye({...this._def,unknownKeys:"passthrough"})}extend(e){return new ye({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ye({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Fe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ye({...this._def,catchall:e})}pick(e){const t={};for(const s of l.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new ye({...this._def,shape:()=>t})}omit(e){const t={};for(const s of l.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new ye({...this._def,shape:()=>t})}deepPartial(){return ge(this)}partial(e){const t={};for(const s of l.objectKeys(this.shape)){const r=this.shape[s];e&&!e[s]?t[s]=r:t[s]=r.optional()}return new ye({...this._def,shape:()=>t})}required(e){const t={};for(const s of l.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let e=this.shape[s];for(;e instanceof je;)e=e._def.innerType;t[s]=e}return new ye({...this._def,shape:()=>t})}keyof(){return Re(l.objectKeys(this.shape))}}ye.create=(e,t)=>new ye({shape:()=>e,unknownKeys:"strip",catchall:me.create(),typeName:Fe.ZodObject,...C(t)}),ye.strictCreate=(e,t)=>new ye({shape:()=>e,unknownKeys:"strict",catchall:me.create(),typeName:Fe.ZodObject,...C(t)}),ye.lazycreate=(e,t)=>new ye({shape:e,unknownKeys:"strip",catchall:me.create(),typeName:Fe.ZodObject,...C(t)});class ve extends D{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;if(t.common.async)return Promise.all(s.map(async e=>{const s={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const s of e)if("dirty"===s.result.status)return t.common.issues.push(...s.ctx.common.issues),s.result;const s=e.map(e=>new g(e.ctx.common.issues));return x(t,{code:_.invalid_union,unionErrors:s}),b});{let e;const r=[];for(const n of s){const s={...t,common:{...t.common,issues:[]},parent:null},a=n._parseSync({data:t.data,path:t.path,parent:s});if("valid"===a.status)return a;"dirty"!==a.status||e||(e={result:a,ctx:s}),s.common.issues.length&&r.push(s.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const n=r.map(e=>new g(e));return x(t,{code:_.invalid_union,unionErrors:n}),b}}get options(){return this._def.options}}ve.create=(e,t)=>new ve({options:e,typeName:Fe.ZodUnion,...C(t)});const xe=e=>e instanceof Ae?xe(e.schema):e instanceof Ze?xe(e.innerType()):e instanceof Ne?[e.value]:e instanceof Ie?e.options:e instanceof Ce?l.objectValues(e.enum):e instanceof $e?xe(e._def.innerType):e instanceof ue?[void 0]:e instanceof le?[null]:e instanceof je?[void 0,...xe(e.unwrap())]:e instanceof Pe?[null,...xe(e.unwrap())]:e instanceof qe||e instanceof Le?xe(e.unwrap()):e instanceof Ue?xe(e._def.innerType):[];class Ee extends D{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return x(t,{code:_.invalid_type,expected:m.object,received:t.parsedType}),b;const s=this.discriminator,r=t.data[s],n=this.optionsMap.get(r);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(x(t,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),b)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const r=new Map;for(const s of t){const t=xe(s.shape[e]);if(!t.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of t){if(r.has(n))throw Error(`Discriminator property ${e+""} has duplicate value ${n+""}`);r.set(n,s)}}return new Ee({typeName:Fe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...C(s)})}}function be(e,t){const s=f(e),r=f(t);if(e===t)return{valid:!0,data:e};if(s===m.object&&r===m.object){const s=l.objectKeys(t),r=l.objectKeys(e).filter(e=>-1!==s.indexOf(e)),n={...e,...t};for(const s of r){const r=be(e[s],t[s]);if(!r.valid)return{valid:!1};n[s]=r.data}return{valid:!0,data:n}}if(s===m.array&&r===m.array){if(e.length!==t.length)return{valid:!1};const s=[];for(let r=0;r<e.length;r++){const n=be(e[r],t[r]);if(!n.valid)return{valid:!1};s.push(n.data)}return{valid:!0,data:s}}return s===m.date&&r===m.date&&+e===+t?{valid:!0,data:e}:{valid:!1}}class Te extends D{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=(e,r)=>{if(S(e)||S(r))return b;const n=be(e.value,r.value);return n.valid?((w(e)||w(r))&&t.dirty(),{status:t.value,value:n.data}):(x(s,{code:_.invalid_intersection_types}),b)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}Te.create=(e,t,s)=>new Te({left:e,right:t,typeName:Fe.ZodIntersection,...C(s)});class ke extends D{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.array)return x(s,{code:_.invalid_type,expected:m.array,received:s.parsedType}),b;if(s.data.length<this._def.items.length)return x(s,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&s.data.length>this._def.items.length&&(x(s,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...s.data].map((e,t)=>{const r=this._def.items[t]||this._def.rest;return r?r._parse(new R(s,e,s.path,t)):null}).filter(e=>!!e);return s.common.async?Promise.all(r).then(e=>E.mergeArray(t,e)):E.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new ke({...this._def,rest:e})}}ke.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new ke({items:e,typeName:Fe.ZodTuple,rest:null,...C(t)})};class Se extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.object)return x(s,{code:_.invalid_type,expected:m.object,received:s.parsedType}),b;const r=[],n=this._def.keyType,a=this._def.valueType;for(const e in s.data)r.push({key:n._parse(new R(s,e,s.path,e)),value:a._parse(new R(s,s.data[e],s.path,e)),alwaysSet:e in s.data});return s.common.async?E.mergeObjectAsync(t,r):E.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,s){return new Se(t instanceof D?{keyType:e,valueType:t,typeName:Fe.ZodRecord,...C(s)}:{keyType:re.create(),valueType:e,typeName:Fe.ZodRecord,...C(t)})}}class we extends D{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.map)return x(s,{code:_.invalid_type,expected:m.map,received:s.parsedType}),b;const r=this._def.keyType,n=this._def.valueType,a=[...s.data.entries()].map(([e,t],a)=>({key:r._parse(new R(s,e,s.path,[a,"key"])),value:n._parse(new R(s,t,s.path,[a,"value"]))}));if(s.common.async){const e=new Map;return Promise.resolve().then(async()=>{for(const s of a){const r=await s.key,n=await s.value;if("aborted"===r.status||"aborted"===n.status)return b;"dirty"!==r.status&&"dirty"!==n.status||t.dirty(),e.set(r.value,n.value)}return{status:t.value,value:e}})}{const e=new Map;for(const s of a){const r=s.key,n=s.value;if("aborted"===r.status||"aborted"===n.status)return b;"dirty"!==r.status&&"dirty"!==n.status||t.dirty(),e.set(r.value,n.value)}return{status:t.value,value:e}}}}we.create=(e,t,s)=>new we({valueType:t,keyType:e,typeName:Fe.ZodMap,...C(s)});class Oe extends D{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==m.set)return x(s,{code:_.invalid_type,expected:m.set,received:s.parsedType}),b;const r=this._def;null!==r.minSize&&s.data.size<r.minSize.value&&(x(s,{code:_.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),null!==r.maxSize&&s.data.size>r.maxSize.value&&(x(s,{code:_.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const n=this._def.valueType;function a(e){const s=new Set;for(const r of e){if("aborted"===r.status)return b;"dirty"===r.status&&t.dirty(),s.add(r.value)}return{status:t.value,value:s}}const i=[...s.data.values()].map((e,t)=>n._parse(new R(s,e,s.path,t)));return s.common.async?Promise.all(i).then(e=>a(e)):a(i)}min(e,t){return new Oe({...this._def,minSize:{value:e,message:N.toString(t)}})}max(e,t){return new Oe({...this._def,maxSize:{value:e,message:N.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Oe.create=(e,t)=>new Oe({valueType:e,minSize:null,maxSize:null,typeName:Fe.ZodSet,...C(t)});class Ae extends D{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Ae.create=(e,t)=>new Ae({getter:e,typeName:Fe.ZodLazy,...C(t)});class Ne extends D{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return x(t,{received:t.data,code:_.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}}function Re(e,t){return new Ie({values:e,typeName:Fe.ZodEnum,...C(t)})}Ne.create=(e,t)=>new Ne({value:e,typeName:Fe.ZodLiteral,...C(t)});class Ie extends D{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),s=this._def.values;return x(t,{expected:l.joinValues(s),received:t.parsedType,code:_.invalid_type}),b}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return x(t,{received:t.data,code:_.invalid_enum_value,options:s}),b}return k(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return Ie.create(e,{...this._def,...t})}exclude(e,t=this._def){return Ie.create(this.options.filter(t=>!e.includes(t)),{...this._def,...t})}}Ie.create=Re;class Ce extends D{_parse(e){const t=l.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==m.string&&s.parsedType!==m.number){const e=l.objectValues(t);return x(s,{expected:l.joinValues(e),received:s.parsedType,code:_.invalid_type}),b}if(this._cache||(this._cache=new Set(l.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=l.objectValues(t);return x(s,{received:s.data,code:_.invalid_enum_value,options:e}),b}return k(e.data)}get enum(){return this._def.values}}Ce.create=(e,t)=>new Ce({values:e,typeName:Fe.ZodNativeEnum,...C(t)});class De extends D{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&!1===t.common.async)return x(t,{code:_.invalid_type,expected:m.promise,received:t.parsedType}),b;const s=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return k(s.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}}De.create=(e,t)=>new De({type:e,typeName:Fe.ZodPromise,...C(t)});class Ze extends D{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Fe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),r=this._def.effect||null,n={addIssue:e=>{x(s,e),e.fatal?t.abort():t.dirty()},get path(){return s.path}};if(n.addIssue=n.addIssue.bind(n),"preprocess"===r.type){const e=r.transform(s.data,n);if(s.common.async)return Promise.resolve(e).then(async e=>{if("aborted"===t.value)return b;const r=await this._def.schema._parseAsync({data:e,path:s.path,parent:s});return"aborted"===r.status?b:"dirty"===r.status||"dirty"===t.value?T(r.value):r});{if("aborted"===t.value)return b;const r=this._def.schema._parseSync({data:e,path:s.path,parent:s});return"aborted"===r.status?b:"dirty"===r.status||"dirty"===t.value?T(r.value):r}}if("refinement"===r.type){const e=e=>{const t=r.refinement(e,n);if(s.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===s.common.async){const r=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===r.status?b:("dirty"===r.status&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(s=>"aborted"===s.status?b:("dirty"===s.status&&t.dirty(),e(s.value).then(()=>({status:t.value,value:s.value}))))}if("transform"===r.type){if(!1===s.common.async){const e=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!O(e))return b;const a=r.transform(e.value,n);if(a instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(e=>O(e)?Promise.resolve(r.transform(e.value,n)).then(e=>({status:t.value,value:e})):b)}l.assertNever(r)}}Ze.create=(e,t,s)=>new Ze({schema:e,typeName:Fe.ZodEffects,effect:t,...C(s)}),Ze.createWithPreprocess=(e,t,s)=>new Ze({schema:t,effect:{type:"preprocess",transform:e},typeName:Fe.ZodEffects,...C(s)});class je extends D{_parse(e){return this._getType(e)===m.undefined?k(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}je.create=(e,t)=>new je({innerType:e,typeName:Fe.ZodOptional,...C(t)});class Pe extends D{_parse(e){return this._getType(e)===m.null?k(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Pe.create=(e,t)=>new Pe({innerType:e,typeName:Fe.ZodNullable,...C(t)});class $e extends D{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===m.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}$e.create=(e,t)=>new $e({innerType:e,typeName:Fe.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...C(t)});class Ue extends D{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return A(r)?r.then(e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new g(s.common.issues)},input:s.data})})):{status:"valid",value:"valid"===r.status?r.value:this._def.catchValue({get error(){return new g(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}Ue.create=(e,t)=>new Ue({innerType:e,typeName:Fe.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...C(t)});class Me extends D{_parse(e){if(this._getType(e)!==m.nan){const t=this._getOrReturnCtx(e);return x(t,{code:_.invalid_type,expected:m.nan,received:t.parsedType}),b}return{status:"valid",value:e.data}}}Me.create=e=>new Me({typeName:Fe.ZodNaN,...C(e)});class qe extends D{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ve extends D{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const e=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?b:"dirty"===e.status?(t.dirty(),T(e.value)):this._def.out._parseAsync({data:e.value,path:s.path,parent:s})})();{const e=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return"aborted"===e.status?b:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:s.path,parent:s})}}static create(e,t){return new Ve({in:e,out:t,typeName:Fe.ZodPipeline})}}class Le extends D{_parse(e){const t=this._def.innerType._parse(e),s=e=>(O(e)&&(e.value=Object.freeze(e.value)),e);return A(t)?t.then(e=>s(e)):s(t)}unwrap(){return this._def.innerType}}var Fe;Le.create=(e,t)=>new Le({innerType:e,typeName:Fe.ZodReadonly,...C(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(Fe||(Fe={}));const He=re.create,Be=ae.create,ze=oe.create,Qe=pe.create;me.create;const Ke=_e.create,We=ye.create,Ye=ve.create,Je=Ee.create;Te.create,ke.create;const Ge=Se.create,Xe=Ne.create,et=Ie.create;De.create;const tt=je.create;Pe.create;const st="2024-11-05",rt=[st,"2024-10-07"],nt="2.0",at=Ye([He(),Be().int()]),it=He(),ot=We({_meta:tt(We({progressToken:tt(at)}).passthrough())}).passthrough(),dt=We({method:He(),params:tt(ot)}),ct=We({_meta:tt(We({}).passthrough())}).passthrough(),ut=We({method:He(),params:tt(ct)}),lt=We({_meta:tt(We({}).passthrough())}).passthrough(),ht=Ye([He(),Be().int()]),pt=We({jsonrpc:Xe(nt),id:ht}).merge(dt).strict(),mt=We({jsonrpc:Xe(nt)}).merge(ut).strict(),ft=We({jsonrpc:Xe(nt),id:ht,result:lt}).strict();var _t;!function(e){e[e.ConnectionClosed=-1]="ConnectionClosed",e[e.RequestTimeout=-2]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError"}(_t||(_t={}));const gt=Ye([pt,mt,ft,We({jsonrpc:Xe(nt),id:ht,error:We({code:Be().int(),message:He(),data:tt(Qe())})}).strict()]),yt=lt.strict(),vt=ut.extend({method:Xe("notifications/cancelled"),params:ct.extend({requestId:ht,reason:He().optional()})}),xt=We({name:He(),version:He()}).passthrough(),Et=We({experimental:tt(We({}).passthrough()),sampling:tt(We({}).passthrough()),roots:tt(We({listChanged:tt(ze())}).passthrough())}).passthrough(),bt=dt.extend({method:Xe("initialize"),params:ot.extend({protocolVersion:He(),capabilities:Et,clientInfo:xt})}),Tt=We({experimental:tt(We({}).passthrough()),logging:tt(We({}).passthrough()),prompts:tt(We({listChanged:tt(ze())}).passthrough()),resources:tt(We({subscribe:tt(ze()),listChanged:tt(ze())}).passthrough()),tools:tt(We({listChanged:tt(ze())}).passthrough())}).passthrough(),kt=lt.extend({protocolVersion:He(),capabilities:Tt,serverInfo:xt}),St=ut.extend({method:Xe("notifications/initialized")}),wt=dt.extend({method:Xe("ping")}),Ot=We({progress:Be(),total:tt(Be())}).passthrough(),At=ut.extend({method:Xe("notifications/progress"),params:ct.merge(Ot).extend({progressToken:at})}),Nt=dt.extend({params:ot.extend({cursor:tt(it)}).optional()}),Rt=lt.extend({nextCursor:tt(it)}),It=We({uri:He(),mimeType:tt(He())}).passthrough(),Ct=It.extend({text:He()}),Dt=It.extend({blob:He().base64()}),Zt=We({uri:He(),name:He(),description:tt(He()),mimeType:tt(He())}).passthrough(),jt=We({uriTemplate:He(),name:He(),description:tt(He()),mimeType:tt(He())}).passthrough(),Pt=Nt.extend({method:Xe("resources/list")}),$t=Rt.extend({resources:Ke(Zt)}),Ut=Nt.extend({method:Xe("resources/templates/list")}),Mt=Rt.extend({resourceTemplates:Ke(jt)}),qt=dt.extend({method:Xe("resources/read"),params:ot.extend({uri:He()})}),Vt=lt.extend({contents:Ke(Ye([Ct,Dt]))}),Lt=ut.extend({method:Xe("notifications/resources/list_changed")}),Ft=dt.extend({method:Xe("resources/subscribe"),params:ot.extend({uri:He()})}),Ht=dt.extend({method:Xe("resources/unsubscribe"),params:ot.extend({uri:He()})}),Bt=ut.extend({method:Xe("notifications/resources/updated"),params:ct.extend({uri:He()})}),zt=We({name:He(),description:tt(He()),required:tt(ze())}).passthrough(),Qt=We({name:He(),description:tt(He()),arguments:tt(Ke(zt))}).passthrough(),Kt=Nt.extend({method:Xe("prompts/list")}),Wt=Rt.extend({prompts:Ke(Qt)}),Yt=dt.extend({method:Xe("prompts/get"),params:ot.extend({name:He(),arguments:tt(Ge(He()))})}),Jt=We({type:Xe("text"),text:He()}).passthrough(),Gt=We({type:Xe("image"),data:He().base64(),mimeType:He()}).passthrough(),Xt=We({type:Xe("resource"),resource:Ye([Ct,Dt])}).passthrough(),es=We({role:et(["user","assistant"]),content:Ye([Jt,Gt,Xt])}).passthrough(),ts=lt.extend({description:tt(He()),messages:Ke(es)}),ss=ut.extend({method:Xe("notifications/prompts/list_changed")}),rs=We({name:He(),description:tt(He()),inputSchema:We({type:Xe("object"),properties:tt(We({}).passthrough())}).passthrough()}).passthrough(),ns=Nt.extend({method:Xe("tools/list")}),as=Rt.extend({tools:Ke(rs)}),is=lt.extend({content:Ke(Ye([Jt,Gt,Xt])),isError:ze().default(!1).optional()});is.or(lt.extend({toolResult:Qe()}));const os=dt.extend({method:Xe("tools/call"),params:ot.extend({name:He(),arguments:tt(Ge(Qe()))})}),ds=ut.extend({method:Xe("notifications/tools/list_changed")}),cs=et(["debug","info","notice","warning","error","critical","alert","emergency"]),us=dt.extend({method:Xe("logging/setLevel"),params:ot.extend({level:cs})}),ls=ut.extend({method:Xe("notifications/message"),params:ct.extend({level:cs,logger:tt(He()),data:Qe()})}),hs=We({name:He().optional()}).passthrough(),ps=We({hints:tt(Ke(hs)),costPriority:tt(Be().min(0).max(1)),speedPriority:tt(Be().min(0).max(1)),intelligencePriority:tt(Be().min(0).max(1))}).passthrough(),ms=We({role:et(["user","assistant"]),content:Ye([Jt,Gt])}).passthrough(),fs=dt.extend({method:Xe("sampling/createMessage"),params:ot.extend({messages:Ke(ms),systemPrompt:tt(He()),includeContext:tt(et(["none","thisServer","allServers"])),temperature:tt(Be()),maxTokens:Be().int(),stopSequences:tt(Ke(He())),metadata:tt(We({}).passthrough()),modelPreferences:tt(ps)})}),_s=lt.extend({model:He(),stopReason:tt(et(["endTurn","stopSequence","maxTokens"]).or(He())),role:et(["user","assistant"]),content:Je("type",[Jt,Gt])}),gs=We({type:Xe("ref/resource"),uri:He()}).passthrough(),ys=We({type:Xe("ref/prompt"),name:He()}).passthrough(),vs=dt.extend({method:Xe("completion/complete"),params:ot.extend({ref:Ye([ys,gs]),argument:We({name:He(),value:He()}).passthrough()})}),xs=lt.extend({completion:We({values:Ke(He()).max(100),total:tt(Be().int()),hasMore:tt(ze())}).passthrough()}),Es=We({uri:He().startsWith("file://"),name:tt(He())}).passthrough(),bs=dt.extend({method:Xe("roots/list")}),Ts=lt.extend({roots:Ke(Es)}),ks=ut.extend({method:Xe("notifications/roots/list_changed")});Ye([wt,bt,vs,us,Yt,Kt,Pt,Ut,qt,Ft,Ht,os,ns]),Ye([vt,At,St,ks]),Ye([yt,_s,Ts]),Ye([wt,fs,bs]),Ye([vt,At,ls,Bt,Lt,ds,ss]),Ye([yt,kt,xs,ts,Wt,$t,Mt,Vt,is,as]);class Ss extends Error{constructor(e,t,s){super(`MCP error ${e}: ${t}`),this.code=e,this.data=s}}class ws{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this.setNotificationHandler(vt,e=>{const t=this._requestHandlerAbortControllers.get(e.params.requestId);null==t||t.abort(e.params.reason)}),this.setNotificationHandler(At,e=>{this._onprogress(e)}),this.setRequestHandler(wt,e=>({}))}async connect(e){this._transport=e,this._transport.onclose=()=>{this._onclose()},this._transport.onerror=e=>{this._onerror(e)},this._transport.onmessage=e=>{"method"in e?"id"in e?this._onrequest(e):this._onnotification(e):this._onresponse(e)},await this._transport.start()}_onclose(){var e;const t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._transport=void 0,null===(e=this.onclose)||void 0===e||e.call(this);const s=new Ss(_t.ConnectionClosed,"Connection closed");for(const e of t.values())e(s)}_onerror(e){var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}_onnotification(e){var t;const s=null!==(t=this._notificationHandlers.get(e.method))&&void 0!==t?t:this.fallbackNotificationHandler;void 0!==s&&Promise.resolve().then(()=>s(e)).catch(e=>this._onerror(Error("Uncaught error in notification handler: "+e)))}_onrequest(e){var t,s;const r=null!==(t=this._requestHandlers.get(e.method))&&void 0!==t?t:this.fallbackRequestHandler;if(void 0===r)return void(null===(s=this._transport)||void 0===s||s.send({jsonrpc:"2.0",id:e.id,error:{code:_t.MethodNotFound,message:"Method not found"}}).catch(e=>this._onerror(Error("Failed to send an error response: "+e))));const n=new AbortController;this._requestHandlerAbortControllers.set(e.id,n),Promise.resolve().then(()=>r(e,{signal:n.signal})).then(t=>{var s;if(!n.signal.aborted)return null===(s=this._transport)||void 0===s?void 0:s.send({result:t,jsonrpc:"2.0",id:e.id})},t=>{var s,r;if(!n.signal.aborted)return null===(s=this._transport)||void 0===s?void 0:s.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:_t.InternalError,message:null!==(r=t.message)&&void 0!==r?r:"Internal error"}})}).catch(e=>this._onerror(Error("Failed to send response: "+e))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progress:t,total:s,progressToken:r}=e.params,n=this._progressHandlers.get(+r);void 0!==n?n({progress:t,total:s}):this._onerror(Error("Received a progress notification for an unknown token: "+JSON.stringify(e)))}_onresponse(e){const t=e.id,s=this._responseHandlers.get(+t);void 0!==s?(this._responseHandlers.delete(+t),this._progressHandlers.delete(+t),s("result"in e?e:new Ss(e.error.code,e.error.message,e.error.data))):this._onerror(Error("Received a response for an unknown message ID: "+JSON.stringify(e)))}get transport(){return this._transport}async close(){var e;await(null===(e=this._transport)||void 0===e?void 0:e.close())}request(e,t,s){return new Promise((r,n)=>{var a,i,o,d;if(!this._transport)return void n(Error("Not connected"));!0===(null===(a=this._options)||void 0===a?void 0:a.enforceStrictCapabilities)&&this.assertCapabilityForMethod(e.method),null===(i=null==s?void 0:s.signal)||void 0===i||i.throwIfAborted();const c=this._requestMessageId++,u={...e,jsonrpc:"2.0",id:c};let l;(null==s?void 0:s.onprogress)&&(this._progressHandlers.set(c,s.onprogress),u.params={...e.params,_meta:{progressToken:c}}),this._responseHandlers.set(c,e=>{var a;if(void 0!==l&&clearTimeout(l),!(null===(a=null==s?void 0:s.signal)||void 0===a?void 0:a.aborted)){if(e instanceof Error)return n(e);try{const s=t.parse(e.result);r(s)}catch(e){n(e)}}});const h=e=>{var t;this._responseHandlers.delete(c),this._progressHandlers.delete(c),null===(t=this._transport)||void 0===t||t.send({jsonrpc:"2.0",method:"cancelled",params:{requestId:c,reason:e+""}}).catch(e=>this._onerror(Error("Failed to send cancellation: "+e))),n(e)};null===(o=null==s?void 0:s.signal)||void 0===o||o.addEventListener("abort",()=>{var e;void 0!==l&&clearTimeout(l),h(null===(e=null==s?void 0:s.signal)||void 0===e?void 0:e.reason)});const p=null!==(d=null==s?void 0:s.timeout)&&void 0!==d?d:6e4;l=setTimeout(()=>h(new Ss(_t.RequestTimeout,"Request timed out",{timeout:p})),p),this._transport.send(u).catch(e=>{void 0!==l&&clearTimeout(l),n(e)})})}async notification(e){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability(e.method);const t={...e,jsonrpc:"2.0"};await this._transport.send(t)}setRequestHandler(e,t){const s=e.shape.method.value;this.assertRequestHandlerCapability(s),this._requestHandlers.set(s,(s,r)=>Promise.resolve(t(e.parse(s),r)))}removeRequestHandler(e){this._requestHandlers.delete(e)}setNotificationHandler(e,t){this._notificationHandlers.set(e.shape.method.value,s=>Promise.resolve(t(e.parse(s))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}}class Os{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;const e=this._buffer.indexOf("\n");if(-1===e)return null;const t=this._buffer.toString("utf8",0,e);return this._buffer=this._buffer.subarray(e+1),function(e){return gt.parse(JSON.parse(e))}(t)}clear(){this._buffer=void 0}}class As{constructor(e=n.stdin,t=n.stdout){this._stdin=e,this._stdout=t,this._readBuffer=new Os,this._started=!1,this._ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()},this._onerror=e=>{var t;null===(t=this.onerror)||void 0===t||t.call(this,e)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(var e,t;;)try{const t=this._readBuffer.readMessage();if(null===t)break;null===(e=this.onmessage)||void 0===e||e.call(this,t)}catch(e){null===(t=this.onerror)||void 0===t||t.call(this,e)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._readBuffer.clear(),null===(e=this.onclose)||void 0===e||e.call(this)}send(e){return new Promise(t=>{const s=function(e){return JSON.stringify(e)+"\n"}(e);this._stdout.write(s)?t():this._stdout.once("drain",t)})}}class Ns{request;constructor(){this.request={REQUEST:{ESB_ATTRS:{App_ID:"VOSA",Target_ID:"WOMS",Application_ID:"00020000000002",Transaction_ID:""},REQUEST_DATA:{SendData:{Head:{jobTitle:"",businessSystem:"",proposeUser:"",jobDesc:"",fbk13:"",eventId:"",attachmentList:[]}},SendHead:{},SendURL:{},Operation:"Z_WORK_ORDER_CREATE_NEW",Type:"Z_WORK_ORDER_CREATE_NEW"}}}}setESBAttrs(e){return this.request.REQUEST.ESB_ATTRS={...this.request.REQUEST.ESB_ATTRS,...e},this}setAppId(e){return this.request.REQUEST.ESB_ATTRS.App_ID=e,this}setEventId(e){return this.request.REQUEST.REQUEST_DATA.SendData.Head.eventId=e,this}setTargetId(e){return this.request.REQUEST.ESB_ATTRS.Target_ID=e,this}setApplicationId(e){return this.request.REQUEST.ESB_ATTRS.Application_ID=e,this}generateApplicationId(){return this.request.REQUEST.ESB_ATTRS.Application_ID=this._generateApplicationId(),this}setTransactionId(e){return this.request.REQUEST.ESB_ATTRS.Transaction_ID=e||this._generateUUID(),this}setJobTitle(e){return this.request.REQUEST.REQUEST_DATA.SendData.Head.jobTitle=e,this}setBusinessSystem(e){return this.request.REQUEST.REQUEST_DATA.SendData.Head.businessSystem=e,this}setProposeUser(e){return this.request.REQUEST.REQUEST_DATA.SendData.Head.proposeUser=e,this}setJobDesc(e){return this.request.REQUEST.REQUEST_DATA.SendData.Head.jobDesc=e,this}setTimestamp(e){const t=e||new Date;return this.request.REQUEST.REQUEST_DATA.SendData.Head.fbk13=this._formatDate(t),this}addAttachment(e,t){return this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList||(this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList=[]),this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList.push({attachmentName:e,attachmentDesc:t}),this}addAttachments(e){return e.forEach(e=>{this.addAttachment(e.attachmentName,e.attachmentDesc)}),this}setAttachments(e){return this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList=e,this}clearAttachments(){return this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList=[],this}setOperation(e){return this.request.REQUEST.REQUEST_DATA.Operation=e,this.request.REQUEST.REQUEST_DATA.Type=e,this}setSendHead(e){return this.request.REQUEST.REQUEST_DATA.SendHead=e,this}setSendURL(e){return this.request.REQUEST.REQUEST_DATA.SendURL=e,this}setWorkOrderHead(e){return this.request.REQUEST.REQUEST_DATA.SendData.Head={...this.request.REQUEST.REQUEST_DATA.SendData.Head,...e},this}build(){return this.request.REQUEST.ESB_ATTRS.Transaction_ID||this.setTransactionId(),this.request.REQUEST.REQUEST_DATA.SendData.Head.fbk13||this.setTimestamp(),JSON.parse(JSON.stringify(this.request))}buildJSON(e=!1){return JSON.stringify(this.build(),null,e?2:0)}reset(){const e=new Ns;return this.request=e.request,this}getData(){return JSON.parse(JSON.stringify(this.request))}_generateApplicationId(){const e=new Date;return`${e.getFullYear()}${(e.getMonth()+1+"").padStart(2,"0")}${(e.getDate()+"").padStart(2,"0")}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`}_generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}_formatDate(e){const t=e=>e.toString().padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}}const Rs={SRM:"Supplier Relationship Management - 供应商管理、采购流程、供应商评估",SPMS:"Spare Parts Management System - 备件管理、库存查询、备件申领",POS:"Legacy Warehouse Management System - 仓库出入库、库存盘点、物料管理",SAP:"SAP ERP System - ERP 核心业务、财务、生产、销售",MDM:"Master Data Management - 主数据维护、数据质量、数据同步",WOM:"Work Order Management - 工单管理、任务跟踪、工单审批",OA:"Office Automation System - 办公自动化、审批流程、公文管理",ESB:"Enterprise Service Bus - 系统集成、接口管理、数据交换",TMS:"Transportation Management System - 运输调度、物流跟踪、配送管理","网络/硬件":"Network & Hardware Support - 网络故障、硬件报修、IT 基础设施",CRM:"Customer Relationship Management - 客户管理、销售跟进、客户服务",QMS:"Quality Management System - 质量检验、不合格品处理、质量追溯",VOSA:"Digital Product Platform - 数字化平台、创新项目、新产品功能",EAM:"Enterprise Asset Management - 资产管理、设备维护、资源调配"},Is="mcp-server-wom-call",Cs="0.0.11",Ds=5e3,Zs=10485760;let js=process.env.ESB_URL||"";const Ps={name:"create-wom-ticket",description:'创建运维工单(Work Order Management)\n\n⚠️ **关键规则:system 参数必须使用精确的系统代码(如 "OA"),不能带"系统"二字或其他后缀!**\n\n**功能说明:**\n用于自动化提交系统故障、需求变更、运维支持等工单到企业服务总线(ESB)。\n\n**适用场景:**\n- 系统故障报修(如:登录异常、功能失效)\n- 功能需求提交(如:新增报表、权限调整)\n- 运维支持请求(如:数据修复、配置变更)\n- 事件跟踪记录(如:性能问题、安全事件)\n\n**正确示例:**\n❌ 错误:system: "OA系统"、"oa"、"OA 系统"\n✅ 正确:system: "OA"\n\n用户:"帮我报个工单,OA系统的审批流程有bug"\n→ 应提取为 system: "OA"(只取代码部分)',inputSchema:{type:"object",required:["empNo","content","system","title"],properties:{name:{type:"string",minLength:1,maxLength:100,description:"提交人姓名(用于工单联系和通知)"},email:{type:"string",format:"email",description:"提交人邮箱(用于接收工单处理进度通知)"},empNo:{type:"string",minLength:1,description:"员工工号(必填,用于身份验证和工单归属,如果消息来自企微,from.userid 与该员工工号一致)"},system:{type:"string",minLength:1,enum:Object.keys(Rs),description:`⚠️ 问题所属系统代码(必填,只能使用以下代码,不能添加"系统"等后缀)\n\n【系统代码列表 - 严格使用以下代码】\n${Object.entries(Rs).map(([e,t])=>`• ${e} → ${t}`).join("\n")}\n\n⚠️ 重要提示:\n1. 必须精确匹配上述代码(区分大小写)\n2. 不能添加"系统"、"平台"等后缀\n3. 不能使用小写或其他变体\n\n✅ 正确示例:\n - 用户说"OA系统有问题" → 使用 "OA"\n - 用户说"srm登录不了" → 使用 "SRM"\n - 用户说"网络坏了" → 使用 "网络/硬件"\n \n❌ 错误示例:\n - "OA系统"(多了"系统")\n - "oa"(大小写错误)\n - "SAP系统"(多了"系统")`},eventId:{type:"string",description:"关联的事件ID(可选,用于追踪特定监控事件或告警)"},replayId:{type:"string",description:"会话回放ID(可选,用于问题复现和分析)"},title:{type:"string",minLength:1,maxLength:100,description:'工单标题(必填,简明扼要描述问题,如:"登录页面无法访问"、"审批流程卡住")'},content:{type:"string",minLength:1,maxLength:Ds,description:"问题详细描述(必填)\n建议包含以下信息:\n- 问题现象:具体出现了什么问题\n- 复现步骤:如何触发该问题\n- 影响范围:影响了哪些用户或业务\n- 期望结果:希望达到什么效果\n- 发生时间:问题首次出现的时间"},attachments:{type:"array",items:{type:"object",required:["filename","url"],properties:{filename:{type:"string",description:"附件文件名(必须含扩展名,如:error.log、screenshot.png)"},url:{type:"string",description:"附件访问URL(需可公网访问或内网可达,支持 http/https 协议)"},size:{type:"number",description:"文件大小(字节,用于验证和展示)"}}},description:"附件列表(可选,支持截图、日志、录屏等,建议单个文件不超过 10MB)"}}}};function $s(e){try{return new URL(e),!0}catch{return!1}}async function Us(e){const t=js;if(!t)throw Error("ESB_URL 未配置");const s=function(e){const t=new Ns;if(t.setJobTitle(e.title).setProposeUser(e.empNo).setJobDesc(Buffer.from(e.content,"utf-8").toString("base64")).setBusinessSystem(e.system).setEventId(e.eventId||"").setAppId(e.system),e.attachments&&e.attachments.length>0){const s=e.attachments.filter(e=>"string"==typeof e.filename&&"string"==typeof e.url&&e.filename.length>0&&e.url.length>0);s.length>0&&t.addAttachments(s.map(e=>({attachmentName:e.filename,attachmentDesc:e.url})))}return t.buildJSON()}(e);try{const e=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:s});if(!e.ok){const t=await e.text();throw Error(`ESB API 请求失败:HTTP ${e.status} ${e.statusText}\n响应内容:${t}`)}const r=function(e){if(!e||"object"!=typeof e)throw Error("ESB 响应格式无效:响应必须是对象");const t=e;if(!t.RESPONSE)throw Error("ESB 响应格式无效:缺少 RESPONSE 字段");if(!t.RESPONSE.ESB_ATTRS)throw Error("ESB 响应格式无效:缺少 ESB_ATTRS 字段");if(!t.RESPONSE.RETURN_DATA)throw Error("ESB 响应格式无效:缺少 RETURN_DATA 字段");return t}(await e.json());if(!function(e){const{RETURN_DATA:t}=e.RESPONSE;return t.success}(r)){const e=function(e){const{RETURN_DATA:t}=e.RESPONSE;return t.msg||"未知错误"}(r);throw Error(e)}return function(e){const{ESB_ATTRS:t,RETURN_DATA:s}=e.RESPONSE,r=["📋 工单处理结果","","【ESB 协议信息】"," 事务ID: "+t.Transaction_ID," 返回码: "+t.RETURN_CODE," 目标系统: "+t.Target_ID,"","【业务处理结果】"," 状态: "+(s.success?"✅ 成功":"❌ 失败")," 代码: "+s.code," 消息: "+s.msg];if(s.data&&"object"==typeof s.data){const e=s.data;(e.workOrderId||e.workOrderNo)&&(r.push("","【工单信息】"),e.workOrderId&&r.push(" 工单ID: "+e.workOrderId),e.workOrderNo&&r.push(" 工单编号: "+e.workOrderNo))}return r.join("\n")}(r)}catch(e){if(e instanceof Error)throw Error("创建工单失败:"+e.message);throw Error("创建工单失败:"+e)}}const Ms=new class extends ws{constructor(e,t){super(t),this._serverInfo=e,this._capabilities=t.capabilities,this.setRequestHandler(bt,e=>this._oninitialize(e)),this.setNotificationHandler(St,()=>{var e;return null===(e=this.oninitialized)||void 0===e?void 0:e.call(this)})}assertCapabilityForMethod(e){var t,s;switch(e){case"sampling/createMessage":if(!(null===(t=this._clientCapabilities)||void 0===t?void 0:t.sampling))throw Error(`Client does not support sampling (required for ${e})`);break;case"roots/list":if(!(null===(s=this._clientCapabilities)||void 0===s?void 0:s.roots))throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`)}}async _oninitialize(e){const t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:rt.includes(t)?t:st,capabilities:this.getCapabilities(),serverInfo:this._serverInfo}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},yt)}async createMessage(e,t){return this.request({method:"sampling/createMessage",params:e},_s,t)}async listRoots(e,t){return this.request({method:"roots/list",params:e},Ts,t)}async sendLoggingMessage(e){return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}({name:Is,version:Cs},{capabilities:{tools:{}}});Ms.setRequestHandler(ns,async()=>({tools:[Ps]})),Ms.setRequestHandler(os,async e=>{try{!function(){if(!js)throw Error("ESB_URL is not configured. Please set it in .env file, system environment, or MCP client configuration.")}();const{name:t,arguments:s}=e.params;if(!s)throw Error("缺少参数");if("create-wom-ticket"===t)return function(e){if(!e||"object"!=typeof e)throw Error("参数必须是一个对象");const t=e;if(!t.empNo||"string"!=typeof t.empNo||!t.empNo.trim())throw Error("empNo(员工工号)是必填项,且必须是非空字符串");if(!t.system||"string"!=typeof t.system||!t.system.trim())throw Error("system(系统代码)是必填项,且必须是非空字符串");if(!Object.keys(Rs).includes(t.system))throw Error(`system(系统代码)必须是以下值之一:${Object.keys(Rs).join("、")},当前值:${t.system}`);if(!t.title||"string"!=typeof t.title||!t.title.trim())throw Error("title(工单标题)是必填项,且必须是非空字符串");if(!t.content||"string"!=typeof t.content||!t.content.trim())throw Error("content(问题描述)是必填项,且必须是非空字符串");if(t.title.length>100)throw Error("title(工单标题)不能超过 100 个字符");if(t.content.length>Ds)throw Error("content(问题描述)不能超过 5000 个字符");if(void 0!==t.name){if("string"!=typeof t.name)throw Error("name(提交人姓名)必须是字符串");if(t.name.length>100)throw Error("name(提交人姓名)不能超过 100 个字符")}if(void 0!==t.email){if("string"!=typeof t.email)throw Error("email(邮箱)必须是字符串");if(t.email.length>0&&(s=t.email,!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)))throw Error("email(邮箱)格式不正确")}var s;if(void 0!==t.attachments){if(!Array.isArray(t.attachments))throw Error("attachments(附件列表)必须是数组");for(const[e,s]of t.attachments.entries()){if(!s||"object"!=typeof s)throw Error(`附件 [${e}] 必须是对象`);if(!s.filename||"string"!=typeof s.filename||!s.filename.trim())throw Error(`附件 [${e}] 的 filename(文件名)是必填项`);if(!s.url||"string"!=typeof s.url||!s.url.trim())throw Error(`附件 [${e}] 的 url(文件地址)是必填项`);if(!$s(s.url))throw Error(`附件 [${e}] 的 url(文件地址)格式不正确`);if(void 0!==s.size){if("number"!=typeof s.size||s.size<0)throw Error(`附件 [${e}] 的 size(文件大小)必须是正数`);if(s.size>Zs)throw Error(`附件 [${e}] 的大小超过限制(最大 10MB)`)}}}}(s),{content:[{type:"text",text:"✅ 工单创建成功\n\n"+await Us(s)}],isError:!1};throw Error("未知工具:"+t)}catch(e){return{content:[{type:"text",text:`❌ 工单创建失败\n\n错误信息:${e instanceof Error?e.message:e+""}\n\n💡 提示:\n- 请检查系统代码是否正确\n- 确认该系统是否已配置运维负责人\n- 如问题持续,请联系系统管理员`}],isError:!0}}}),async function(){try{const e=new As;await Ms.connect(e)}catch(e){throw e}}().catch(e=>{process.exit(1)});
8
+ import{Server as t}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as e}from"@modelcontextprotocol/sdk/server/stdio.js";import{ListToolsRequestSchema as r,CallToolRequestSchema as s}from"@modelcontextprotocol/sdk/types.js";import"dotenv/config";import{S3Client as n,PutObjectCommand as i}from"@aws-sdk/client-s3";import{randomUUID as a}from"crypto";import{extname as o}from"path";const c="mcp-server-wom-call",l=5e3,p=10485760,E={SRM:"Supplier Relationship Management - 供应商管理、采购流程、供应商评估",SPMS:"Spare Parts Management System - 备件管理、库存查询、备件申领",POS:"Legacy Warehouse Management System - 仓库出入库、库存盘点、物料管理",SAP:"SAP ERP System - ERP 核心业务、财务、生产、销售",MDM:"Master Data Management - 主数据维护、数据质量、数据同步",WOM:"Work Order Management - 工单管理、任务跟踪、工单审批",OA:"Office Automation System - 办公自动化、审批流程、公文管理",ESB:"Enterprise Service Bus - 系统集成、接口管理、数据交换",TMS:"Transportation Management System - 运输调度、物流跟踪、配送管理","网络/硬件":"Network & Hardware Support - 网络故障、硬件报修、IT 基础设施",CRM:"Customer Relationship Management - 客户管理、销售跟进、客户服务",QMS:"Quality Management System - 质量检验、不合格品处理、质量追溯",VOSA:"Digital Product Platform - 数字化平台、创新项目、新产品功能",EAM:"Enterprise Asset Management - 资产管理、设备维护、资源调配"};class h{static instance;_esbUrl="";_s3Config;constructor(){this.loadFromEnv(),this._s3Config={endpoint:process.env.S3_ENDPOINT||"",region:process.env.S3_REGION||"us-east-1",accessKey:process.env.S3_ACCESS_KEY||"",secretKey:process.env.S3_SECRET_KEY||"",bucket:process.env.S3_BUCKET||"",publicUrl:process.env.S3_PUBLIC_URL||""}}static getInstance(){return h.instance||(h.instance=new h),h.instance}loadFromEnv(){this._esbUrl=process.env.ESB_URL||""}get esbUrl(){return this._esbUrl}setEsbUrl(t){this._esbUrl=t}get s3(){return this._s3Config}validate(){if(!this._esbUrl)throw Error("ESB_URL is not configured. Please set it in .env file, system environment, or MCP client configuration.")}}const u=h.getInstance();class m{get name(){return this.definition.name}}const d={name:"create-wom-ticket",description:'创建运维工单(Work Order Management)\n\n⚠️ **关键规则:system 参数必须使用精确的系统代码(如 "OA"),不能带"系统"二字或其他后缀!**\n\n**功能说明:**\n用于自动化提交系统故障、需求变更、运维支持等工单到企业服务总线(ESB)。\n\n**适用场景:**\n- 系统故障报修(如:登录异常、功能失效)\n- 功能需求提交(如:新增报表、权限调整)\n- 运维支持请求(如:数据修复、配置变更)\n- 事件跟踪记录(如:性能问题、安全事件)',inputSchema:{type:"object",required:["empNo","content","system","title"],properties:{name:{type:"string",maxLength:100,description:"提交人姓名"},email:{type:"string",format:"email",description:"提交人邮箱"},empNo:{type:"string",minLength:1,description:"员工工号(必填)"},system:{type:"string",enum:Object.keys(E),description:`问题所属系统代码\n\n【系统代码列表 - 严格使用以下代码】\n${Object.entries(E).map(([t,e])=>` • ${t} → ${e}`).join("\n")}\n\n⚠️ 重要提示:\n1. 必须精确匹配上述代码(区分大小写)\n2. 不能添加"系统"、"平台"等后缀\n3. 不能使用小写或其他变体\n\n✅ 正确示例:\n - 用户说"OA系统有问题" → 使用 "OA"\n - 用户说"srm登录不了" → 使用 "SRM"\n - 用户说"网络坏了" → 使用 "网络/硬件"\n\n❌ 错误示例:\n - "OA系统"(多了"系统")\n - "oa"(大小写错误)\n - "SAP系统"(多了"系统")`},title:{type:"string",maxLength:100,description:"工单标题"},content:{type:"string",maxLength:l,description:"问题详细描述"},attachments:{type:"array",items:{type:"object",required:["filename","url"],properties:{filename:{type:"string"},url:{type:"string"},size:{type:"number"}}},description:"附件列表"}}}};class S{request;constructor(){this.request={REQUEST:{ESB_ATTRS:{App_ID:"VOSA",Target_ID:"WOMS",Application_ID:"00020000000002",Transaction_ID:""},REQUEST_DATA:{SendData:{Head:{jobTitle:"",businessSystem:"",proposeUser:"",jobDesc:"",fbk13:"",eventId:"",attachmentList:[]}},SendHead:{},SendURL:{},Operation:"Z_WORK_ORDER_CREATE_NEW",Type:"Z_WORK_ORDER_CREATE_NEW"}}}}setESBAttrs(t){return this.request.REQUEST.ESB_ATTRS={...this.request.REQUEST.ESB_ATTRS,...t},this}setAppId(t){return this.request.REQUEST.ESB_ATTRS.App_ID=t,this}setEventId(t){return this.request.REQUEST.REQUEST_DATA.SendData.Head.eventId=t,this}setTargetId(t){return this.request.REQUEST.ESB_ATTRS.Target_ID=t,this}setApplicationId(t){return this.request.REQUEST.ESB_ATTRS.Application_ID=t,this}generateApplicationId(){return this.request.REQUEST.ESB_ATTRS.Application_ID=this._generateApplicationId(),this}setTransactionId(t){return this.request.REQUEST.ESB_ATTRS.Transaction_ID=t||this._generateUUID(),this}setJobTitle(t){return this.request.REQUEST.REQUEST_DATA.SendData.Head.jobTitle=t,this}setBusinessSystem(t){return this.request.REQUEST.REQUEST_DATA.SendData.Head.businessSystem=t,this}setProposeUser(t){return this.request.REQUEST.REQUEST_DATA.SendData.Head.proposeUser=t,this}setJobDesc(t){return this.request.REQUEST.REQUEST_DATA.SendData.Head.jobDesc=t,this}setTimestamp(t){const e=t||new Date;return this.request.REQUEST.REQUEST_DATA.SendData.Head.fbk13=this._formatDate(e),this}addAttachment(t,e){return this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList||(this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList=[]),this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList.push({attachmentName:t,attachmentDesc:e}),this}addAttachments(t){return t.forEach(t=>{this.addAttachment(t.attachmentName,t.attachmentDesc)}),this}setAttachments(t){return this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList=t,this}clearAttachments(){return this.request.REQUEST.REQUEST_DATA.SendData.Head.attachmentList=[],this}setOperation(t){return this.request.REQUEST.REQUEST_DATA.Operation=t,this.request.REQUEST.REQUEST_DATA.Type=t,this}setSendHead(t){return this.request.REQUEST.REQUEST_DATA.SendHead=t,this}setSendURL(t){return this.request.REQUEST.REQUEST_DATA.SendURL=t,this}setWorkOrderHead(t){return this.request.REQUEST.REQUEST_DATA.SendData.Head={...this.request.REQUEST.REQUEST_DATA.SendData.Head,...t},this}build(){return this.request.REQUEST.ESB_ATTRS.Transaction_ID||this.setTransactionId(),this.request.REQUEST.REQUEST_DATA.SendData.Head.fbk13||this.setTimestamp(),JSON.parse(JSON.stringify(this.request))}buildJSON(t=!1){return JSON.stringify(this.build(),null,t?2:0)}reset(){const t=new S;return this.request=t.request,this}getData(){return JSON.parse(JSON.stringify(this.request))}_generateApplicationId(){const t=new Date;return`${t.getFullYear()}${(t.getMonth()+1+"").padStart(2,"0")}${(t.getDate()+"").padStart(2,"0")}${Math.floor(1e6*Math.random()).toString().padStart(6,"0")}`}_generateUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}_formatDate(t){const e=t=>t.toString().padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())} ${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}`}}class f{static isValidEmail(t){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}static isValidUrl(t){try{return new URL(t),!0}catch{return!1}}static validateWorkOrderInput(t){if(!t||"object"!=typeof t)throw Error("参数必须是一个对象");const e=t;if(!e.empNo?.trim())throw Error("empNo(员工工号)是必填项");if(!e.system?.trim())throw Error("system(系统代码)是必填项");if(!Object.keys(E).includes(e.system))throw Error("system 必须是以下值之一:"+Object.keys(E).join("、"));if(!e.title?.trim())throw Error("title(工单标题)是必填项");if(!e.content?.trim())throw Error("content(问题描述)是必填项");if(e.title.length>100)throw Error("title 不能超过 100 个字符");if(e.content.length>l)throw Error("content 不能超过 5000 个字符");if(e.email&&!this.isValidEmail(e.email))throw Error("email 格式不正确");e.attachments&&this.validateAttachments(e.attachments)}static validateAttachments(t){if(!Array.isArray(t))throw Error("attachments 必须是数组");t.forEach((t,e)=>{if(!t?.filename?.trim())throw Error(`附件 [${e}] 缺少 filename`);if(!t?.url?.trim())throw Error(`附件 [${e}] 缺少 url`);if(!this.isValidUrl(t.url))throw Error(`附件 [${e}] 的 url 格式不正确`);if(t.size&&t.size>p)throw Error(`附件 [${e}] 超过大小限制`)})}}class g{static parseESBResponse(t){if(!t||"object"!=typeof t)throw Error("ESB 响应格式无效");const e=t;if(!e.RESPONSE?.ESB_ATTRS)throw Error("ESB 响应缺少 ESB_ATTRS");if(!e.RESPONSE?.RETURN_DATA)throw Error("ESB 响应缺少 RETURN_DATA");return e}static isSuccess(t){return t.RESPONSE.RETURN_DATA.success}static getErrorMessage(t){return t.RESPONSE.RETURN_DATA.msg||"未知错误"}}class T{static isValidBase64(t){try{return Buffer.from(t,"base64").toString("base64")===t}catch{return!1}}static validateFileUpload(t){if(!t||"object"!=typeof t)throw Error("参数必须是一个对象");const e=t;if(!e.filename?.trim())throw Error("filename(文件名)是必填项");if(!e.content?.trim())throw Error("content(文件内容)是必填项");if(!this.isValidBase64(e.content))throw Error("content 必须是有效的 base64 编码字符串")}static validateMultipleFilesUpload(t){if(!t||"object"!=typeof t)throw Error("参数必须是一个对象");const e=t;if(!Array.isArray(e.files))throw Error("files 必须是数组");if(0===e.files.length)throw Error("files 数组不能为空");e.files.forEach((t,e)=>{try{this.validateFileUpload(t)}catch(t){const r=t instanceof Error?t.message:t+"";throw Error(`文件 [${e}] 验证失败:${r}`)}})}}class y{async call(t){const e=u.esbUrl;if(!e)throw Error("ESB_URL 未配置");try{const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:t});if(!r.ok){const t=await r.text();throw Error(`ESB API 请求失败:HTTP ${r.status}\n${t}`)}const s=await r.json();return g.parseESBResponse(s)}catch(t){if(t instanceof Error)throw Error("ESB 调用失败:"+t.message);throw t}}}class R{esbService;constructor(t=new y){this.esbService=t}buildPayload(t){const e=new S;return e.setJobTitle(t.title).setProposeUser(t.empNo).setJobDesc(Buffer.from(t.content,"utf-8").toString("base64")).setBusinessSystem(t.system).setEventId(t.eventId||"").setAppId(t.system),t.attachments?.length&&e.addAttachments(t.attachments.map(t=>({attachmentName:t.filename,attachmentDesc:t.url}))),e.buildJSON()}async create(t){const e=this.buildPayload(t),r=await this.esbService.call(e);if(!g.isSuccess(r)){const t=g.getErrorMessage(r);throw Error(t)}return r}}class A extends m{workOrderService;definition=d;constructor(t=new R){super(),this.workOrderService=t}async execute(t){try{f.validateWorkOrderInput(t);return{content:[{type:"text",text:"✅ 工单创建成功\n\n"+function(t){const{ESB_ATTRS:e,RETURN_DATA:r}=t.RESPONSE,s=["📋 工单处理结果","","【ESB 协议信息】"," 事务ID: "+e.Transaction_ID," 返回码: "+e.RETURN_CODE," 目标系统: "+e.Target_ID,"","【业务处理结果】"," 状态: "+(r.success?"✅ 成功":"❌ 失败")," 代码: "+r.code," 消息: "+r.msg];if(r.data){const t=r.data;(t.workOrderId||t.workOrderNo)&&(s.push("","【工单信息】"),t.workOrderId&&s.push(" 工单ID: "+t.workOrderId),t.workOrderNo&&s.push(" 工单编号: "+t.workOrderNo))}return s.join("\n")}(await this.workOrderService.create(t))}],isError:!1}}catch(t){return{content:[{type:"text",text:"❌ 工单创建失败\n\n错误信息:"+(t instanceof Error?t.message:t+"")}],isError:!0}}}}const U={name:"upload-file",description:"上传单个文件到 S3 存储\n\n**功能说明:**\n将文件上传到 S3 兼容存储服务,返回可访问的 URL。\n\n**适用场景:**\n- 工单附件上传\n- 图片、文档上传\n- 临时文件存储\n\n**文件限制:**\n- 最大文件大小:10MB\n- 支持格式:图片、文档、压缩包等常见格式",inputSchema:{type:"object",required:["filename","content"],properties:{filename:{type:"string",description:"文件名(包含扩展名),例如:report.pdf"},content:{type:"string",description:"文件内容(base64 编码)"},mimetype:{type:"string",description:"MIME 类型(可选,如:image/png)"}}}},w={name:"upload-multiple-files",description:"批量上传多个文件到 S3 存储\n\n**功能说明:**\n一次性上传多个文件,返回所有文件的 URL。\n\n**适用场景:**\n- 批量上传工单附件\n- 多图片上传\n- 文档批量归档",inputSchema:{type:"object",required:["files"],properties:{files:{type:"array",items:{type:"object",required:["filename","content"],properties:{filename:{type:"string"},content:{type:"string"},mimetype:{type:"string"}}},description:"文件列表"}}}};class _{client;bucket;publicUrl;constructor(){const t=u.s3;!function(t){const e=["endpoint","accessKey","secretKey","bucket","publicUrl"].filter(e=>!t[e]);if(e.length>0)throw Error(`S3 配置不完整,缺少:${e.join(", ")}。请在环境变量中配置。`)}(t),this.client=new n({endpoint:t.endpoint,region:t.region,credentials:{accessKeyId:t.accessKey,secretAccessKey:t.secretKey},forcePathStyle:!0}),this.bucket=t.bucket,this.publicUrl=t.publicUrl}async uploadFile(t){const e=Buffer.from(t.content,"base64");if(e.length>p)throw Error(`文件大小超过限制 10MB,当前:${(e.length/1024/1024).toFixed(2)}MB`);const r=o(t.filename),s=`${a()}${r}`,n=t.mimetype||this.getMimeType(r),c=new i({Bucket:this.bucket,Key:s,Body:e,ContentType:n,Metadata:{originalName:encodeURIComponent(t.filename)}});return await this.client.send(c),{fileName:s,originalName:t.filename,size:e.length,mimetype:n,url:`${this.publicUrl}/${this.bucket}/${s}`}}async uploadFiles(t){const e=t.map(t=>this.uploadFile(t));return Promise.all(e)}getMimeType(t){return{".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".txt":"text/plain",".zip":"application/zip"}[t.toLowerCase()]||"application/octet-stream"}}class D extends m{s3Service;definition=U;constructor(t=new _){super(),this.s3Service=t}async execute(t){try{T.validateFileUpload(t);const e=await this.s3Service.uploadFile(t);return{content:[{type:"text",text:`✅ 文件上传成功\n\n📁 文件信息:\n 原始文件名:${e.originalName}\n 存储文件名:${e.fileName}\n 文件大小:${(e.size/1024).toFixed(2)} KB\n 文件类型:${e.mimetype}\n\n🔗 访问地址:\n${e.url}`}],isError:!1}}catch(t){return{content:[{type:"text",text:"❌ 文件上传失败\n\n错误信息:"+(t instanceof Error?t.message:t+"")}],isError:!0}}}}class x extends m{s3Service;definition=w;constructor(t=new _){super(),this.s3Service=t}async execute(t){try{T.validateMultipleFilesUpload(t);const e=await this.s3Service.uploadFiles(t.files),r=e.map((t,e)=>`${e+1}. ${t.originalName}\n 大小:${(t.size/1024).toFixed(2)} KB\n URL:${t.url}`).join("\n\n");return{content:[{type:"text",text:`✅ 成功上传 ${e.length} 个文件\n\n📁 文件列表:\n${r}`}],isError:!1}}catch(t){return{content:[{type:"text",text:"❌ 文件上传失败\n\n错误信息:"+(t instanceof Error?t.message:t+"")}],isError:!0}}}}class b{tools=new Map;constructor(){this.registerDefaultTools()}registerDefaultTools(){this.register(new A),this.register(new D),this.register(new x)}register(t){this.tools.set(t.name,t)}get(t){return this.tools.get(t)}getAll(){return Array.from(this.tools.values())}getDefinitions(){return this.getAll().map(t=>t.definition)}}class v{static info(t,...e){}static error(t,...e){}static success(t,...e){}static warn(t,...e){}}var O="0.0.12";class Q{server;toolRegistry;constructor(){this.server=new t({name:c,version:O},{capabilities:{tools:{}}}),this.toolRegistry=new b,this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(r,async()=>({tools:this.toolRegistry.getDefinitions()})),this.server.setRequestHandler(s,async t=>{try{u.validate();const{name:e,arguments:r}=t.params,s=this.toolRegistry.get(e);if(!s)throw Error("未知工具:"+e);return await s.execute(r)}catch(t){const e=t instanceof Error?t.message:t+"";return v.error("Tool call error:",e),{content:[{type:"text",text:"❌ 操作失败\n\n"+e}],isError:!0}}})}async start(){const t=new e;await this.server.connect(t),v.success(`${c} v${O} is running`),v.info("MCP Server for Work Order Management System Integration"),u.esbUrl?v.info("ESB URL: "+u.esbUrl):v.warn("ESB URL not configured")}}(async function(){try{const t=new Q;await t.start()}catch(t){v.error("Failed to start server:",t),process.exit(1)}})().catch(t=>{v.error("Fatal error:",t),process.exit(1)});
9
9
  //# sourceMappingURL=index.js.map