@stackone/connect-sdk 1.32.0 → 1.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1,4652 @@
1
- "use strict";var e=require("@stackone/transport"),t=require("path-to-regexp"),o=require("@stackone/core"),r=require("@stackone/utils"),n=require("yaml"),s=require("zod"),i=require("@stackone/expressions");const a=async({inputs:t,context:o,operation:r,credentials:n,nextCursor:s,logger:i,getHttpClient:a=async()=>e.HttpClientManager.getInstance()})=>({inputs:t,fieldConfigs:[],context:o,operation:r,credentials:n,nextCursor:s,httpClient:await a(),logger:i}),c=(e,t,o)=>{const r=o.toUpperCase();if(!e.operations)return;const n=Object.keys(e.operations),s=p(t,r,n);return s?{operation:e.operations?.[s.path],params:s.params}:void 0},u=e=>{const t=e.startsWith("/")?e.slice(1):e;return t.endsWith("/")?t.slice(0,-1):t},p=(e,o,r)=>{const n=u(e);for(const e of r)if(e.startsWith(o)){const r=e.replace(`${o} `,"").trim(),s=t.match(u(r))(u(n));if(!1!==s)return{path:e,params:s.params}}},d=e=>{switch(e){case"list":return{statusCode:200,description:"The list of records was retrieved."};case"get":return{statusCode:200,description:"The record with the given identifier was retrieved."};case"create":return{statusCode:201,description:"The record was created successfully."};case"update":return{statusCode:200,description:"The record was updated successfully."};case"delete":return{statusCode:204,description:"The record was deleted successfully."};case"custom":return{statusCode:200,description:"The operation was executed successfully."};case"unknown":return{statusCode:200};default:throw new Error(`Unknown operation type: ${e}`)}},l={key:s.z.string(),label:s.z.string(),required:s.z.boolean().optional().default(!1),secret:s.z.boolean().optional().default(!1),readOnly:s.z.boolean().optional().default(!1),placeholder:s.z.string().optional(),description:s.z.string().optional(),tooltip:s.z.string().optional()},y=s.z.discriminatedUnion("type",[s.z.object({...l,type:s.z.enum(["text","password"])}),s.z.object({...l,type:s.z.literal("select"),options:s.z.object({value:s.z.string(),label:s.z.string()}).array()})]),g=s.z.object({operationId:s.z.string(),categories:s.z.string().array(),operationType:s.z.enum(["list","get","create","update","delete","custom","unknown"]),schema:s.z.string().optional(),entrypointUrl:s.z.string().optional(),entrypointHttpMethod:s.z.string().optional(),description:s.z.string(),responses:s.z.object({statusCode:s.z.number(),description:s.z.string()}).array().optional(),inputs:s.z.object({name:s.z.string(),type:s.z.string(),required:s.z.boolean(),description:s.z.string(),in:s.z.string()}).array().optional(),cursor:s.z.object({enabled:s.z.boolean(),pageSize:s.z.number()}).optional(),compositeIdentifiers:s.z.object({enabled:s.z.boolean(),version:s.z.number().optional(),fields:s.z.object({targetFieldKey:s.z.string(),remote:s.z.string().optional(),components:s.z.string().array()}).array().optional()}).optional(),fieldConfigs:s.z.object({targetFieldKey:s.z.string(),alias:s.z.string().optional(),expression:s.z.string(),type:s.z.enum(["string","number","boolean","datetime_string","enum"]),custom:s.z.boolean().default(!1),hidden:s.z.boolean().default(!1),enumMapper:s.z.object({matcher:s.z.enum(["country_alpha2code_by_alpha2code","country_alpha3code_by_alpha3code","country_code_by_country_code","country_name_by_country_name","country_name_by_alpha3code","country_name_by_alpha2code","country_name_by_country_code","country_alpha3code_by_alpha2code","country_alpha3code_by_country_name","country_alpha3code_by_country_code","country_alpha2code_by_alpha3code","country_alpha2code_by_country_name","country_alpha2code_by_country_code","country_code_by_alpha2code","country_code_by_alpha3code","country_code_by_country_name","country_subdivisions_by_alpha2code","country_subdivision_code_by_subdivision_name","country_alpha2code_by_citizenship","country_subdivision_name_by_subdivision_code"]).or(s.z.object({matchExpression:s.z.string(),value:s.z.string()}).array())}).optional()}).array().optional(),steps:s.z.object({stepId:s.z.string(),description:s.z.string(),stepFunction:s.z.object({functionName:s.z.string(),version:s.z.string().optional(),parameters:s.z.record(s.z.string(),s.z.unknown())}),condition:s.z.string().optional(),ignoreError:s.z.boolean().optional()}).array(),result:s.z.string().or(s.z.record(s.z.string(),s.z.unknown())).optional()}),m=s.z.object({StackOne:s.z.string(),info:s.z.object({title:s.z.string(),version:s.z.string(),key:s.z.string(),description:s.z.string().optional()}),baseUrl:s.z.string(),authentication:s.z.record(s.z.string(),s.z.object({type:s.z.string(),label:s.z.string(),authorization:o.AUTHENTICATION_SCHEMA,environments:s.z.object({key:s.z.string(),name:s.z.string()}).array(),support:s.z.object({link:s.z.string(),description:s.z.string().optional()}),configFields:y.array().optional(),setupFields:y.array().optional(),testOperationsIds:s.z.string().array().optional()})).array().optional(),operations:g.array().optional()});function b(e){try{const t=n.parse(e),o=m.parse(t),s={title:o.info.title,version:o.info.version,key:o.info.key,description:o.info.description},i=_(o),a={baseUrl:o.baseUrl,authentication:f(i)},c=z(o,a);return s.operations=c,s.authentication=i,r.notMissing(c)&&(s.categories=h(Object.values(c))),s}catch(e){throw new Error(`Error parsing YAML file: ${e.message}`)}}const f=e=>{const t={};for(const[o,r]of Object.entries(e))if(r&&"object"==typeof r){const{setupFields:e,configFields:n,support:s,testOperationsIds:i,...a}=r;t[o]=f(a)}else t[o]=r;return t},h=e=>{const t=e.reduce(((e,t)=>{for(const o of t.categories)e.add(o);return e}),new Set);return Array.from(t)},_=e=>{const t={};for(const o of e.authentication??[]){const[e]=Object.keys(o),r=o[e].environments.reduce(((t,r)=>{const{key:n,name:s}=r,{environments:i,...a}=o[e];return t[n]={...a,envKey:n,envName:s},t}),{});t[e]=r}return t},z=(t,o)=>{const r=t.operations?.reduce(((t,r)=>{const n=(e=>e.entrypointUrl&&e.entrypointHttpMethod?`${e.entrypointHttpMethod.toUpperCase()} ${e.entrypointUrl}`:void 0)(r),s=(e=>"list"===e.operationType?`GET /${e.schema}`:`GET /${e.schema}/:id`)(r),i=(e=>"list"===e.operationType?`/${e.schema}`:`/${e.schema}/:id`)(r),a=(t=>{const o={success:d(t.operationType),errors:{400:{statusCode:400,description:"Invalid request."},401:{statusCode:401,description:"Unauthorized access."},403:{statusCode:403,description:"Forbidden."},404:{statusCode:404,description:"Resource not found."},500:{statusCode:500,description:"Server error while executing the request."}}},r=t.responses?.reduce(((t,o)=>(e.isSuccessStatusCode(o.statusCode)?t.success={statusCode:o.statusCode,description:o.description}:t.errors[o.statusCode]={statusCode:o.statusCode,description:o.description},t)),o);return r??o})(r),c=S(r),u=r.inputs||[];return c.enabled&&u?.push({type:"string",name:"page_size",in:"query",required:!1,description:"Number of items to return per page"}),t[n??s]={id:r.operationId,categories:r.categories,description:r.description,operationType:r.operationType,entrypointUrl:r.entrypointUrl??i,entrypointHttpMethod:r.entrypointHttpMethod??"get",responses:a,cursor:c,compositeIdentifiers:E(r),inputs:u,steps:r.steps.reduce(((e,t)=>(e[t.stepId]={id:t.stepId,description:t.description,condition:t.condition,ignoreError:t.ignoreError,stepFunction:{functionName:t.stepFunction.functionName,version:t.stepFunction.version,params:{...t.stepFunction.parameters,...O(t.stepFunction.functionName,o,t.stepFunction.parameters),..."map_fields"===t.stepFunction.functionName||"typecast"===t.stepFunction.functionName?{fields:r.fieldConfigs}:{}}}},e)),{}),result:r.result},t}),{});return r},I=(e,t)=>{if(!e.inputs)return{};const o=v(e.inputs).parse(t);return{...o.headers??{},...o.query??{},...o.path??{},...o.body??{}}},C=e=>{const t={};return e.forEach((e=>{let o;switch(e.type.toLowerCase()){case"string":o=s.z.string();break;case"number":o=s.z.number();break;case"boolean":o=s.z.boolean();break;default:o=s.z.any()}t[e.name]=e.required?o:o.optional()})),s.z.object(t)},v=e=>{const t=e.filter((e=>"path"===e.in)),o=e.filter((e=>"query"===e.in)),r=e.filter((e=>"body"===e.in)),n=e.filter((e=>"headers"===e.in));return s.z.object({path:C(t).optional(),query:C(o).optional(),body:C(r).optional(),headers:C(n).optional()})},S=e=>{const t="list"===e.operationType,o=e.cursor??{enabled:t,pageSize:25};return{enabled:o.enabled&&t,pageSize:o.pageSize}},E=e=>{if(r.isMissing(e.compositeIdentifiers)){const t=e.fieldConfigs?.find((e=>"id"===e.targetFieldKey)),n=r.notMissing(t)?[{targetFieldKey:t.targetFieldKey,remote:"id",components:[{name:t.targetFieldKey,alias:t.alias}]}]:void 0;return{enabled:!0,version:o.COMPOSITE_ID_LATEST_VERSION,fields:n}}const t=[];for(const o of e.compositeIdentifiers?.fields??[]){const r=o.components.map((t=>{const o=e.fieldConfigs?.find((e=>e.targetFieldKey===t));return{name:t,alias:o?.alias}}));t.push({targetFieldKey:o.targetFieldKey,remote:o.remote,components:r})}return{enabled:e.compositeIdentifiers.enabled,version:e.compositeIdentifiers.version,fields:t.length>0?t:void 0}},O=(e,t,o={})=>{if("request"===e||"paginated_request"===e){const e=[{receivedStatus:500,targetStatus:502}];return{...t,customErrors:[...o.customErrors&&Array.isArray(o.customErrors)?o.customErrors:[],...e]}}return{}};class k extends Error{constructor(e,t,o){super(o),this.name="ConnectSDKError",this.errorType=e,this.context=t,Error.captureStackTrace&&Error.captureStackTrace(this,k)}toString(){return`${this.name} [${this.errorType}]: ${this.message}`}}class F extends k{constructor(e,t){super("CONNECTOR_PARSE_ERROR",e,t),this.name="ConnectorParseError"}}class T extends k{constructor(e,t){super("MISSING_OPERATION_ERROR",e,t),this.name="MissingOperationError"}}class j extends k{constructor(e,t){super("INVALID_OPERATION_INPUTS_ERROR",e,t),this.name="InvalidOperationInputsError"}}class x extends k{constructor(e,t){super("INVALID_CURSOR_ERROR",e,t),this.name="InvalidCursorError"}}const w=({category:e,connectorKey:t,connectorVersion:o,authConfigKey:r,environment:n="production",operation:s,accountSecureId:i,projectSecureId:a})=>({projectSecureId:a,accountSecureId:i,connectorKey:t,connectorVersion:o,category:e,service:"",resource:"",schema:s?.schema?.key,operationType:s?.operationType??"unknown",authenticationType:r,environment:n}),N=e=>{const t=e.operation?.compositeIdentifiers,n={...e.inputs??{}};if(!t?.enabled||r.isMissing(n))return e;const s=t.fields?.reduce(((e,t)=>(t.components.forEach((t=>{t.alias&&(e[t.name]=t.alias)})),e)),{}),i={version:t.version??o.COMPOSITE_ID_LATEST_VERSION,aliases:s};return R(n,i,e.logger),{...e,inputs:n}},R=(e,t,o)=>{for(const r in e){const n=e[r];if("string"==typeof n||Array.isArray(n)&&n.every((e=>"string"==typeof e)))M(n,r,e,t,o);else if(Array.isArray(n))for(const e of n)R(e,t,o);else"object"==typeof n&&null!==n&&R(n,t,o)}},A=e=>{const t=Object.values(e);return 1===t.length&&("string"==typeof t[0]||"number"==typeof t[0])},M=(e,t,r,n,s)=>{try{const i=Array.isArray(e),a=i?e:[e];if(0===a.length)return;const{compositeIdComponents:c,nonCompositeIds:u}=((e,t,r,n)=>{const s=[],i=[];for(const a of e)try{const e=o.decodeCompositeId(a,r);s.push(e)}catch(e){n?.debug({message:`Received ${t} with invalid composite ID, assuming it is not a composite ID`,category:"processCompositeId",context:{key:t,inputElement:a,compositeIdentifierConfig:r,error:e}}),i.push(a)}return{compositeIdComponents:s,nonCompositeIds:i}})(a,t,n,s);((e,t,o,r)=>{const n=o.filter((e=>Object.keys(e).length>1));n.length>0&&(e.decoded_ids={...e.decoded_ids??{},[t]:r?n:n[0]})})(r,t,c,i),((e,t,o,r,n)=>{o.every(A)&&(n?e[t]=[...o.map((e=>Object.values(e)[0])),...r]:o.length>0&&(e[t]=Object.values(o[0])[0]))})(r,t,c,u,i)}catch(e){((e,t,r)=>{e instanceof o.CoreError&&"COMPOSITE_ID_MISSING_HEADER_ERROR"===e.type?r?.debug({message:`Received ${t} with no composite ID header, assuming it is not a composite ID`}):r?.warning({message:`Error processing composite ID for ${t}, ignoring it`,error:e})})(e,t,s)}},q="remote_",$=e=>{const t=e.operation?.compositeIdentifiers;if(!t?.enabled)return e;const o="data",n=e.outputs?.[o];if(r.isMissing(n))return e;const s=Array.isArray(n)?n.map((e=>K(e,t))):K(n,t);return{...e,outputs:{...e.outputs??{},[o]:s}}},K=(e,t)=>{const o=P(e,t),n=V(o);return{...e,...r.isObject(n)?n:{}}},P=(e,t)=>{const r=t.version??o.COMPOSITE_ID_LATEST_VERSION,n={};return t.fields?.forEach((t=>{const s={},i=[];t.components.forEach((t=>{t.alias&&(s[t.name]=t.alias),i.push({key:t.name,value:e[t.name]})}));const a=1===i.length?i[0]:{identifiers:i},c={version:r,aliases:Object.keys(s).length>0?s:void 0},u=o.encodeCompositeId(a,c);n[t.targetFieldKey]=u,t.remote&&(n[`${q}${t.remote}`]=e[t.remote])})),{...e,...n}},D=e=>"id"===e||/.+_id(s)?$/.test(e),U=(e,t,n)=>{const s=t.map((t=>r.isString(t)&&t.length>0&&!o.isCompositeId(t)?((e,t)=>{try{return o.encodeCompositeId({key:e,value:t},{version:o.COMPOSITE_ID_LATEST_VERSION})}catch{return t}})(e,t):t));n[e]=s,n[`${q}${e}`]=t},H=(e,t,r)=>{if(((e,t)=>o.isCompositeId(e)||t.startsWith(q))(t,e))return;const n=o.encodeCompositeId({key:e,value:t},{version:o.COMPOSITE_ID_LATEST_VERSION});r[e]=n,r[`remote_${e}`]=t},L=(e,t,o)=>{(e=>Array.isArray(e)&&e.every((e=>r.isString(e)&&e.length>0)))(t)?U(e,t,o):r.isString(t)&&t.length>0&&H(e,t,o)},V=e=>{if(Array.isArray(e))return e.map((e=>V(e)));if(!r.isObject(e))return e;const t={...e};for(const[o,n]of Object.entries(e))(r.isObject(n)||Array.isArray(n)&&n.length>0&&r.isObject(n[0]))&&(t[o]=V(n)),D(o)&&L(o,n,t);return t},G=(e,t,n,s)=>{const i=r.isMissing(e)?void 0:e.data,a=Object.keys(n).length+1,c=o.isCursorEmpty({cursor:s,ignoreStepIndex:a});if(!r.isObject(e)||r.isMissing(i)||(i?.length??0)<=t)return{result:e,next:r.notMissing(s)&&!c?o.minifyCursor(s):null};const u=s?.remote?.[a]?.pageNumber??1,p=(u-1)*t,d=p+t,l=i.slice(p,d),y=i.length>d||!c,g=o.updateCursor({cursor:s,stepIndex:a,pageNumber:u+1});return{result:{...e,data:l},next:y?o.minifyCursor(g):null}},W=async({block:e,buildStepFunction:t=o.StepFunctionsFactory.build,virtualPaginateResultFn:r=G,encodeResultCompositeIds:n=$,decodeInputCompositeIds:s=N})=>{const i=s(e);return n(await Y({block:i,buildStepFunction:t,virtualPaginateResultFn:r}))},B=async(e,t,r,n,s,a)=>{const c=r[e],u=c.stepFunction,p=a.buildStepFunction({functionName:u.functionName,version:u.version,validateSchemas:!0}).fn;if(((e,t)=>!!e.condition&&!i.safeEvaluate(e.condition,t))(c,n))return Q({block:n,stepId:e,successful:!0,skipped:!0,message:"Step skipped due to condition not met."});if(s.hasFatalError)return Q({block:n,stepId:e,successful:!1,skipped:!0,message:"Step skipped due to previous error."});const d=((e,t,o)=>{const r=e.stepFunction;return t.operation?.cursor.enabled?{...r.params??{},cursor:{token:t.nextCursor?.remote?.[o]?.providerPageCursor,position:t.nextCursor?.remote?.[o]?.position}}:r.params??{}})(c,n,t),l=await p({block:n,params:d});if(!1===l.successful)return((e,t,o,r,n)=>{const s=Q({block:e,stepId:t,successful:!1,functionOutput:o});return(r.ignoreError??!1)||(n.hasFatalError=!0,n.errorStatusCode??=o.output?.statusCode??500),s})(n,e,l,c,s);const y=n.operation?.cursor.enabled?o.updateCursor({cursor:n.nextCursor,stepIndex:t,providerPageCursor:l.output?.next,position:l.output?.position}):void 0;return Q({block:{...l.block,nextCursor:y},stepId:e,functionOutput:l})},Y=async({block:t,buildStepFunction:n=o.StepFunctionsFactory.build,virtualPaginateResultFn:s=G})=>{const i=t.operation?.steps||{};let a={...t};const c=Object.keys(i),u=((e,t)=>{const o=Number(e.inputs?.page_size);return r.notMissing(e.inputs?.page_size)&&r.isNumber(o)&&!Number.isNaN(o)?o:e.operation?.cursor?.pageSize??t})(t,25),p={hasFatalError:!1,errorStatusCode:null},d={block:t,buildStepFunction:n,virtualPaginateResultFn:s};for(const[e,t]of c.entries())a=await B(t,e,i,a,p,d);const l=t.operation?.result?J(t.operation.result,a):void 0;return((t,o,n,s,i)=>{const a=!n.hasFatalError,c=a?t.operation?.responses.success.statusCode??200:n.errorStatusCode??500;return{...o,outputs:r.notMissing(i)&&r.isObject(i.result)?{next:i.next,...i.result}:s,response:{successful:a,statusCode:c,message:a?void 0:t.operation?.responses?.errors?.[c]?.description??e.HttpErrorMessages?.[c]??"Error while processing the request"}}})(t,a,p,l,t.operation?.cursor.enabled?s(l,u,i,a.nextCursor):void 0)},J=(e,t)=>r.isObject(e)?i.safeEvaluateRecord(e,t):i.safeEvaluate(e,t),Q=({block:e,stepId:t,successful:o,functionOutput:r,skipped:n,message:s})=>({...e,steps:{...e.steps,[t]:{successful:o??r?.successful??!1,errors:r?.errors,output:r?.output,skipped:n,message:s}}}),X=(e,t)=>{const n=e?.next,s=r.notMissing(n)&&"list"===t.operationType?o.expandCursor(n):void 0;if(null===s)throw new x(t,"Invalid cursor.");return s};exports.ConnectSDKError=k,exports.createBlock=a,exports.executeStepFunction=async({block:e,stepFunctionName:t,params:r,buildStepFunction:n=o.StepFunctionsFactory.build})=>{const s=n({functionName:t}).fn,i=await s({block:e,params:r}),a=t===o.StepFunctionName.MAP_FIELDS?{[o.StepFunctionName.MAP_FIELDS.toString()]:{output:{data:i.block.result},errors:i.errors,successful:i.successful}}:{};return{...i.block,steps:{...i?.block?.steps??{},...a}}},exports.getOperationFromUrl=c,exports.parseOperationInputs=I,exports.parseYamlConnector=b,exports.runConnectorOperation=async({account:e,connector:t,category:o,path:n,method:s="get",queryParams:i,body:u,headers:p,logger:d,parseConnector:l=b,getOperationFromUrlFn:y=c,parseOperationInputsFn:g=I,createBlockContextFn:m=w,createBlockFn:f=a,runStepOperationFn:h=W})=>{const _=e.authConfigKey,z=e.environment??"production",C=e.secureId,v=e.projectSecureId,S=e.credentials,E=m({category:o,connectorKey:e.providerKey,connectorVersion:e.providerVersion,authConfigKey:_,environment:z,accountSecureId:C,projectSecureId:v});let O;try{O=r.isString(t)?l(t):t}catch{throw new F(E,"Error while parsing connector")}const k=y(O,n,s);if(r.isMissing(k))throw new T(E,"No matching operation found");E.operationType=k.operation.operationType,E.schema=k.operation.schema?.key;const x=X(i,E);let N;try{N=g(k.operation,{query:i,body:u,headers:p,path:k.params})}catch{throw new j(E,"Error while parsing operation inputs")}const R=await f({inputs:N,context:E,operation:k.operation,credentials:S,nextCursor:x,logger:d});return await h({block:R})},exports.runStepOperation=W;
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ const __stackone_transport = __toESM(require("@stackone/transport"));
25
+ const path_to_regexp = __toESM(require("path-to-regexp"));
26
+ const __stackone_core = __toESM(require("@stackone/core"));
27
+ const __stackone_utils = __toESM(require("@stackone/utils"));
28
+ const yaml = __toESM(require("yaml"));
29
+ const __stackone_expressions = __toESM(require("@stackone/expressions"));
30
+
31
+ //#region src/blocks/createBlock.ts
32
+ const createBlock = async ({ inputs, context, operation, credentials, nextCursor, logger, getHttpClient = async () => __stackone_transport.HttpClientManager.getInstance() }) => {
33
+ const httpClient = await getHttpClient();
34
+ return {
35
+ inputs,
36
+ fieldConfigs: [],
37
+ context,
38
+ operation,
39
+ credentials,
40
+ nextCursor,
41
+ httpClient,
42
+ logger
43
+ };
44
+ };
45
+
46
+ //#endregion
47
+ //#region src/connectors/operations.ts
48
+ const getOperationFromUrl = (connector, url, method) => {
49
+ const httpMethod = method.toUpperCase();
50
+ if (!connector.operations) return void 0;
51
+ const validOperationUrls = Object.keys(connector.operations);
52
+ const test = testMatcher(url, httpMethod, validOperationUrls);
53
+ if (!test) return void 0;
54
+ return {
55
+ operation: connector.operations?.[test.path],
56
+ params: test.params
57
+ };
58
+ };
59
+ const removeLeadingAndTrailingSlashes = (path) => {
60
+ const withoutLeadingSlash = path.startsWith("/") ? path.slice(1) : path;
61
+ const withoutTrailingSlash = withoutLeadingSlash.endsWith("/") ? withoutLeadingSlash.slice(0, -1) : withoutLeadingSlash;
62
+ return withoutTrailingSlash;
63
+ };
64
+ const testMatcher = (url, method, routes) => {
65
+ const path = removeLeadingAndTrailingSlashes(url);
66
+ for (const r of routes) if (r.startsWith(method)) {
67
+ const cleanRoute = r.replace(`${method} `, "").trim();
68
+ const fn = (0, path_to_regexp.match)(removeLeadingAndTrailingSlashes(cleanRoute));
69
+ const res = fn(removeLeadingAndTrailingSlashes(path));
70
+ if (res !== false) return {
71
+ path: r,
72
+ params: res.params
73
+ };
74
+ }
75
+ return void 0;
76
+ };
77
+
78
+ //#endregion
79
+ //#region ../../node_modules/zod/v3/helpers/util.js
80
+ var util;
81
+ (function(util$1) {
82
+ util$1.assertEqual = (_) => {};
83
+ function assertIs(_arg) {}
84
+ util$1.assertIs = assertIs;
85
+ function assertNever(_x) {
86
+ throw new Error();
87
+ }
88
+ util$1.assertNever = assertNever;
89
+ util$1.arrayToEnum = (items) => {
90
+ const obj = {};
91
+ for (const item of items) obj[item] = item;
92
+ return obj;
93
+ };
94
+ util$1.getValidEnumValues = (obj) => {
95
+ const validKeys = util$1.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
96
+ const filtered = {};
97
+ for (const k of validKeys) filtered[k] = obj[k];
98
+ return util$1.objectValues(filtered);
99
+ };
100
+ util$1.objectValues = (obj) => {
101
+ return util$1.objectKeys(obj).map(function(e) {
102
+ return obj[e];
103
+ });
104
+ };
105
+ util$1.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
106
+ const keys = [];
107
+ for (const key in object) if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
108
+ return keys;
109
+ };
110
+ util$1.find = (arr, checker) => {
111
+ for (const item of arr) if (checker(item)) return item;
112
+ return void 0;
113
+ };
114
+ util$1.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
115
+ function joinValues(array, separator = " | ") {
116
+ return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
117
+ }
118
+ util$1.joinValues = joinValues;
119
+ util$1.jsonStringifyReplacer = (_, value) => {
120
+ if (typeof value === "bigint") return value.toString();
121
+ return value;
122
+ };
123
+ })(util || (util = {}));
124
+ var objectUtil;
125
+ (function(objectUtil$1) {
126
+ objectUtil$1.mergeShapes = (first, second) => {
127
+ return {
128
+ ...first,
129
+ ...second
130
+ };
131
+ };
132
+ })(objectUtil || (objectUtil = {}));
133
+ const ZodParsedType = util.arrayToEnum([
134
+ "string",
135
+ "nan",
136
+ "number",
137
+ "integer",
138
+ "float",
139
+ "boolean",
140
+ "date",
141
+ "bigint",
142
+ "symbol",
143
+ "function",
144
+ "undefined",
145
+ "null",
146
+ "array",
147
+ "object",
148
+ "unknown",
149
+ "promise",
150
+ "void",
151
+ "never",
152
+ "map",
153
+ "set"
154
+ ]);
155
+ const getParsedType = (data) => {
156
+ const t = typeof data;
157
+ switch (t) {
158
+ case "undefined": return ZodParsedType.undefined;
159
+ case "string": return ZodParsedType.string;
160
+ case "number": return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
161
+ case "boolean": return ZodParsedType.boolean;
162
+ case "function": return ZodParsedType.function;
163
+ case "bigint": return ZodParsedType.bigint;
164
+ case "symbol": return ZodParsedType.symbol;
165
+ case "object":
166
+ if (Array.isArray(data)) return ZodParsedType.array;
167
+ if (data === null) return ZodParsedType.null;
168
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") return ZodParsedType.promise;
169
+ if (typeof Map !== "undefined" && data instanceof Map) return ZodParsedType.map;
170
+ if (typeof Set !== "undefined" && data instanceof Set) return ZodParsedType.set;
171
+ if (typeof Date !== "undefined" && data instanceof Date) return ZodParsedType.date;
172
+ return ZodParsedType.object;
173
+ default: return ZodParsedType.unknown;
174
+ }
175
+ };
176
+
177
+ //#endregion
178
+ //#region ../../node_modules/zod/v3/ZodError.js
179
+ const ZodIssueCode = util.arrayToEnum([
180
+ "invalid_type",
181
+ "invalid_literal",
182
+ "custom",
183
+ "invalid_union",
184
+ "invalid_union_discriminator",
185
+ "invalid_enum_value",
186
+ "unrecognized_keys",
187
+ "invalid_arguments",
188
+ "invalid_return_type",
189
+ "invalid_date",
190
+ "invalid_string",
191
+ "too_small",
192
+ "too_big",
193
+ "invalid_intersection_types",
194
+ "not_multiple_of",
195
+ "not_finite"
196
+ ]);
197
+ var ZodError = class ZodError extends Error {
198
+ get errors() {
199
+ return this.issues;
200
+ }
201
+ constructor(issues) {
202
+ super();
203
+ this.issues = [];
204
+ this.addIssue = (sub) => {
205
+ this.issues = [...this.issues, sub];
206
+ };
207
+ this.addIssues = (subs = []) => {
208
+ this.issues = [...this.issues, ...subs];
209
+ };
210
+ const actualProto = new.target.prototype;
211
+ if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
212
+ else this.__proto__ = actualProto;
213
+ this.name = "ZodError";
214
+ this.issues = issues;
215
+ }
216
+ format(_mapper) {
217
+ const mapper = _mapper || function(issue) {
218
+ return issue.message;
219
+ };
220
+ const fieldErrors = { _errors: [] };
221
+ const processError = (error) => {
222
+ for (const issue of error.issues) if (issue.code === "invalid_union") issue.unionErrors.map(processError);
223
+ else if (issue.code === "invalid_return_type") processError(issue.returnTypeError);
224
+ else if (issue.code === "invalid_arguments") processError(issue.argumentsError);
225
+ else if (issue.path.length === 0) fieldErrors._errors.push(mapper(issue));
226
+ else {
227
+ let curr = fieldErrors;
228
+ let i = 0;
229
+ while (i < issue.path.length) {
230
+ const el = issue.path[i];
231
+ const terminal = i === issue.path.length - 1;
232
+ if (!terminal) curr[el] = curr[el] || { _errors: [] };
233
+ else {
234
+ curr[el] = curr[el] || { _errors: [] };
235
+ curr[el]._errors.push(mapper(issue));
236
+ }
237
+ curr = curr[el];
238
+ i++;
239
+ }
240
+ }
241
+ };
242
+ processError(this);
243
+ return fieldErrors;
244
+ }
245
+ static assert(value) {
246
+ if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
247
+ }
248
+ toString() {
249
+ return this.message;
250
+ }
251
+ get message() {
252
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
253
+ }
254
+ get isEmpty() {
255
+ return this.issues.length === 0;
256
+ }
257
+ flatten(mapper = (issue) => issue.message) {
258
+ const fieldErrors = {};
259
+ const formErrors = [];
260
+ for (const sub of this.issues) if (sub.path.length > 0) {
261
+ const firstEl = sub.path[0];
262
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
263
+ fieldErrors[firstEl].push(mapper(sub));
264
+ } else formErrors.push(mapper(sub));
265
+ return {
266
+ formErrors,
267
+ fieldErrors
268
+ };
269
+ }
270
+ get formErrors() {
271
+ return this.flatten();
272
+ }
273
+ };
274
+ ZodError.create = (issues) => {
275
+ const error = new ZodError(issues);
276
+ return error;
277
+ };
278
+
279
+ //#endregion
280
+ //#region ../../node_modules/zod/v3/locales/en.js
281
+ const errorMap = (issue, _ctx) => {
282
+ let message;
283
+ switch (issue.code) {
284
+ case ZodIssueCode.invalid_type:
285
+ if (issue.received === ZodParsedType.undefined) message = "Required";
286
+ else message = `Expected ${issue.expected}, received ${issue.received}`;
287
+ break;
288
+ case ZodIssueCode.invalid_literal:
289
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
290
+ break;
291
+ case ZodIssueCode.unrecognized_keys:
292
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
293
+ break;
294
+ case ZodIssueCode.invalid_union:
295
+ message = `Invalid input`;
296
+ break;
297
+ case ZodIssueCode.invalid_union_discriminator:
298
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
299
+ break;
300
+ case ZodIssueCode.invalid_enum_value:
301
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
302
+ break;
303
+ case ZodIssueCode.invalid_arguments:
304
+ message = `Invalid function arguments`;
305
+ break;
306
+ case ZodIssueCode.invalid_return_type:
307
+ message = `Invalid function return type`;
308
+ break;
309
+ case ZodIssueCode.invalid_date:
310
+ message = `Invalid date`;
311
+ break;
312
+ case ZodIssueCode.invalid_string:
313
+ if (typeof issue.validation === "object") if ("includes" in issue.validation) {
314
+ message = `Invalid input: must include "${issue.validation.includes}"`;
315
+ if (typeof issue.validation.position === "number") message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
316
+ } else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`;
317
+ else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`;
318
+ else util.assertNever(issue.validation);
319
+ else if (issue.validation !== "regex") message = `Invalid ${issue.validation}`;
320
+ else message = "Invalid";
321
+ break;
322
+ case ZodIssueCode.too_small:
323
+ if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
324
+ else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
325
+ else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
326
+ else if (issue.type === "bigint") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
327
+ else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
328
+ else message = "Invalid input";
329
+ break;
330
+ case ZodIssueCode.too_big:
331
+ if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
332
+ else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
333
+ else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
334
+ else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
335
+ else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
336
+ else message = "Invalid input";
337
+ break;
338
+ case ZodIssueCode.custom:
339
+ message = `Invalid input`;
340
+ break;
341
+ case ZodIssueCode.invalid_intersection_types:
342
+ message = `Intersection results could not be merged`;
343
+ break;
344
+ case ZodIssueCode.not_multiple_of:
345
+ message = `Number must be a multiple of ${issue.multipleOf}`;
346
+ break;
347
+ case ZodIssueCode.not_finite:
348
+ message = "Number must be finite";
349
+ break;
350
+ default:
351
+ message = _ctx.defaultError;
352
+ util.assertNever(issue);
353
+ }
354
+ return { message };
355
+ };
356
+ var en_default = errorMap;
357
+
358
+ //#endregion
359
+ //#region ../../node_modules/zod/v3/errors.js
360
+ let overrideErrorMap = en_default;
361
+ function getErrorMap() {
362
+ return overrideErrorMap;
363
+ }
364
+
365
+ //#endregion
366
+ //#region ../../node_modules/zod/v3/helpers/parseUtil.js
367
+ const makeIssue = (params) => {
368
+ const { data, path, errorMaps, issueData } = params;
369
+ const fullPath = [...path, ...issueData.path || []];
370
+ const fullIssue = {
371
+ ...issueData,
372
+ path: fullPath
373
+ };
374
+ if (issueData.message !== void 0) return {
375
+ ...issueData,
376
+ path: fullPath,
377
+ message: issueData.message
378
+ };
379
+ let errorMessage = "";
380
+ const maps = errorMaps.filter((m) => !!m).slice().reverse();
381
+ for (const map of maps) errorMessage = map(fullIssue, {
382
+ data,
383
+ defaultError: errorMessage
384
+ }).message;
385
+ return {
386
+ ...issueData,
387
+ path: fullPath,
388
+ message: errorMessage
389
+ };
390
+ };
391
+ function addIssueToContext(ctx, issueData) {
392
+ const overrideMap = getErrorMap();
393
+ const issue = makeIssue({
394
+ issueData,
395
+ data: ctx.data,
396
+ path: ctx.path,
397
+ errorMaps: [
398
+ ctx.common.contextualErrorMap,
399
+ ctx.schemaErrorMap,
400
+ overrideMap,
401
+ overrideMap === en_default ? void 0 : en_default
402
+ ].filter((x) => !!x)
403
+ });
404
+ ctx.common.issues.push(issue);
405
+ }
406
+ var ParseStatus = class ParseStatus {
407
+ constructor() {
408
+ this.value = "valid";
409
+ }
410
+ dirty() {
411
+ if (this.value === "valid") this.value = "dirty";
412
+ }
413
+ abort() {
414
+ if (this.value !== "aborted") this.value = "aborted";
415
+ }
416
+ static mergeArray(status, results) {
417
+ const arrayValue = [];
418
+ for (const s of results) {
419
+ if (s.status === "aborted") return INVALID;
420
+ if (s.status === "dirty") status.dirty();
421
+ arrayValue.push(s.value);
422
+ }
423
+ return {
424
+ status: status.value,
425
+ value: arrayValue
426
+ };
427
+ }
428
+ static async mergeObjectAsync(status, pairs) {
429
+ const syncPairs = [];
430
+ for (const pair of pairs) {
431
+ const key = await pair.key;
432
+ const value = await pair.value;
433
+ syncPairs.push({
434
+ key,
435
+ value
436
+ });
437
+ }
438
+ return ParseStatus.mergeObjectSync(status, syncPairs);
439
+ }
440
+ static mergeObjectSync(status, pairs) {
441
+ const finalObject = {};
442
+ for (const pair of pairs) {
443
+ const { key, value } = pair;
444
+ if (key.status === "aborted") return INVALID;
445
+ if (value.status === "aborted") return INVALID;
446
+ if (key.status === "dirty") status.dirty();
447
+ if (value.status === "dirty") status.dirty();
448
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) finalObject[key.value] = value.value;
449
+ }
450
+ return {
451
+ status: status.value,
452
+ value: finalObject
453
+ };
454
+ }
455
+ };
456
+ const INVALID = Object.freeze({ status: "aborted" });
457
+ const DIRTY = (value) => ({
458
+ status: "dirty",
459
+ value
460
+ });
461
+ const OK = (value) => ({
462
+ status: "valid",
463
+ value
464
+ });
465
+ const isAborted = (x) => x.status === "aborted";
466
+ const isDirty = (x) => x.status === "dirty";
467
+ const isValid = (x) => x.status === "valid";
468
+ const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
469
+
470
+ //#endregion
471
+ //#region ../../node_modules/zod/v3/helpers/errorUtil.js
472
+ var errorUtil;
473
+ (function(errorUtil$1) {
474
+ errorUtil$1.errToObj = (message) => typeof message === "string" ? { message } : message || {};
475
+ errorUtil$1.toString = (message) => typeof message === "string" ? message : message?.message;
476
+ })(errorUtil || (errorUtil = {}));
477
+
478
+ //#endregion
479
+ //#region ../../node_modules/zod/v3/types.js
480
+ var ParseInputLazyPath = class {
481
+ constructor(parent, value, path, key) {
482
+ this._cachedPath = [];
483
+ this.parent = parent;
484
+ this.data = value;
485
+ this._path = path;
486
+ this._key = key;
487
+ }
488
+ get path() {
489
+ if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
490
+ else this._cachedPath.push(...this._path, this._key);
491
+ return this._cachedPath;
492
+ }
493
+ };
494
+ const handleResult = (ctx, result) => {
495
+ if (isValid(result)) return {
496
+ success: true,
497
+ data: result.value
498
+ };
499
+ else {
500
+ if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
501
+ return {
502
+ success: false,
503
+ get error() {
504
+ if (this._error) return this._error;
505
+ const error = new ZodError(ctx.common.issues);
506
+ this._error = error;
507
+ return this._error;
508
+ }
509
+ };
510
+ }
511
+ };
512
+ function processCreateParams(params) {
513
+ if (!params) return {};
514
+ const { errorMap: errorMap$1, invalid_type_error, required_error, description } = params;
515
+ if (errorMap$1 && (invalid_type_error || required_error)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
516
+ if (errorMap$1) return {
517
+ errorMap: errorMap$1,
518
+ description
519
+ };
520
+ const customMap = (iss, ctx) => {
521
+ const { message } = params;
522
+ if (iss.code === "invalid_enum_value") return { message: message ?? ctx.defaultError };
523
+ if (typeof ctx.data === "undefined") return { message: message ?? required_error ?? ctx.defaultError };
524
+ if (iss.code !== "invalid_type") return { message: ctx.defaultError };
525
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
526
+ };
527
+ return {
528
+ errorMap: customMap,
529
+ description
530
+ };
531
+ }
532
+ var ZodType = class {
533
+ get description() {
534
+ return this._def.description;
535
+ }
536
+ _getType(input) {
537
+ return getParsedType(input.data);
538
+ }
539
+ _getOrReturnCtx(input, ctx) {
540
+ return ctx || {
541
+ common: input.parent.common,
542
+ data: input.data,
543
+ parsedType: getParsedType(input.data),
544
+ schemaErrorMap: this._def.errorMap,
545
+ path: input.path,
546
+ parent: input.parent
547
+ };
548
+ }
549
+ _processInputParams(input) {
550
+ return {
551
+ status: new ParseStatus(),
552
+ ctx: {
553
+ common: input.parent.common,
554
+ data: input.data,
555
+ parsedType: getParsedType(input.data),
556
+ schemaErrorMap: this._def.errorMap,
557
+ path: input.path,
558
+ parent: input.parent
559
+ }
560
+ };
561
+ }
562
+ _parseSync(input) {
563
+ const result = this._parse(input);
564
+ if (isAsync(result)) throw new Error("Synchronous parse encountered promise.");
565
+ return result;
566
+ }
567
+ _parseAsync(input) {
568
+ const result = this._parse(input);
569
+ return Promise.resolve(result);
570
+ }
571
+ parse(data, params) {
572
+ const result = this.safeParse(data, params);
573
+ if (result.success) return result.data;
574
+ throw result.error;
575
+ }
576
+ safeParse(data, params) {
577
+ const ctx = {
578
+ common: {
579
+ issues: [],
580
+ async: params?.async ?? false,
581
+ contextualErrorMap: params?.errorMap
582
+ },
583
+ path: params?.path || [],
584
+ schemaErrorMap: this._def.errorMap,
585
+ parent: null,
586
+ data,
587
+ parsedType: getParsedType(data)
588
+ };
589
+ const result = this._parseSync({
590
+ data,
591
+ path: ctx.path,
592
+ parent: ctx
593
+ });
594
+ return handleResult(ctx, result);
595
+ }
596
+ "~validate"(data) {
597
+ const ctx = {
598
+ common: {
599
+ issues: [],
600
+ async: !!this["~standard"].async
601
+ },
602
+ path: [],
603
+ schemaErrorMap: this._def.errorMap,
604
+ parent: null,
605
+ data,
606
+ parsedType: getParsedType(data)
607
+ };
608
+ if (!this["~standard"].async) try {
609
+ const result = this._parseSync({
610
+ data,
611
+ path: [],
612
+ parent: ctx
613
+ });
614
+ return isValid(result) ? { value: result.value } : { issues: ctx.common.issues };
615
+ } catch (err) {
616
+ if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
617
+ ctx.common = {
618
+ issues: [],
619
+ async: true
620
+ };
621
+ }
622
+ return this._parseAsync({
623
+ data,
624
+ path: [],
625
+ parent: ctx
626
+ }).then((result) => isValid(result) ? { value: result.value } : { issues: ctx.common.issues });
627
+ }
628
+ async parseAsync(data, params) {
629
+ const result = await this.safeParseAsync(data, params);
630
+ if (result.success) return result.data;
631
+ throw result.error;
632
+ }
633
+ async safeParseAsync(data, params) {
634
+ const ctx = {
635
+ common: {
636
+ issues: [],
637
+ contextualErrorMap: params?.errorMap,
638
+ async: true
639
+ },
640
+ path: params?.path || [],
641
+ schemaErrorMap: this._def.errorMap,
642
+ parent: null,
643
+ data,
644
+ parsedType: getParsedType(data)
645
+ };
646
+ const maybeAsyncResult = this._parse({
647
+ data,
648
+ path: ctx.path,
649
+ parent: ctx
650
+ });
651
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
652
+ return handleResult(ctx, result);
653
+ }
654
+ refine(check, message) {
655
+ const getIssueProperties = (val) => {
656
+ if (typeof message === "string" || typeof message === "undefined") return { message };
657
+ else if (typeof message === "function") return message(val);
658
+ else return message;
659
+ };
660
+ return this._refinement((val, ctx) => {
661
+ const result = check(val);
662
+ const setError = () => ctx.addIssue({
663
+ code: ZodIssueCode.custom,
664
+ ...getIssueProperties(val)
665
+ });
666
+ if (typeof Promise !== "undefined" && result instanceof Promise) return result.then((data) => {
667
+ if (!data) {
668
+ setError();
669
+ return false;
670
+ } else return true;
671
+ });
672
+ if (!result) {
673
+ setError();
674
+ return false;
675
+ } else return true;
676
+ });
677
+ }
678
+ refinement(check, refinementData) {
679
+ return this._refinement((val, ctx) => {
680
+ if (!check(val)) {
681
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
682
+ return false;
683
+ } else return true;
684
+ });
685
+ }
686
+ _refinement(refinement) {
687
+ return new ZodEffects({
688
+ schema: this,
689
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
690
+ effect: {
691
+ type: "refinement",
692
+ refinement
693
+ }
694
+ });
695
+ }
696
+ superRefine(refinement) {
697
+ return this._refinement(refinement);
698
+ }
699
+ constructor(def) {
700
+ /** Alias of safeParseAsync */
701
+ this.spa = this.safeParseAsync;
702
+ this._def = def;
703
+ this.parse = this.parse.bind(this);
704
+ this.safeParse = this.safeParse.bind(this);
705
+ this.parseAsync = this.parseAsync.bind(this);
706
+ this.safeParseAsync = this.safeParseAsync.bind(this);
707
+ this.spa = this.spa.bind(this);
708
+ this.refine = this.refine.bind(this);
709
+ this.refinement = this.refinement.bind(this);
710
+ this.superRefine = this.superRefine.bind(this);
711
+ this.optional = this.optional.bind(this);
712
+ this.nullable = this.nullable.bind(this);
713
+ this.nullish = this.nullish.bind(this);
714
+ this.array = this.array.bind(this);
715
+ this.promise = this.promise.bind(this);
716
+ this.or = this.or.bind(this);
717
+ this.and = this.and.bind(this);
718
+ this.transform = this.transform.bind(this);
719
+ this.brand = this.brand.bind(this);
720
+ this.default = this.default.bind(this);
721
+ this.catch = this.catch.bind(this);
722
+ this.describe = this.describe.bind(this);
723
+ this.pipe = this.pipe.bind(this);
724
+ this.readonly = this.readonly.bind(this);
725
+ this.isNullable = this.isNullable.bind(this);
726
+ this.isOptional = this.isOptional.bind(this);
727
+ this["~standard"] = {
728
+ version: 1,
729
+ vendor: "zod",
730
+ validate: (data) => this["~validate"](data)
731
+ };
732
+ }
733
+ optional() {
734
+ return ZodOptional.create(this, this._def);
735
+ }
736
+ nullable() {
737
+ return ZodNullable.create(this, this._def);
738
+ }
739
+ nullish() {
740
+ return this.nullable().optional();
741
+ }
742
+ array() {
743
+ return ZodArray.create(this);
744
+ }
745
+ promise() {
746
+ return ZodPromise.create(this, this._def);
747
+ }
748
+ or(option) {
749
+ return ZodUnion.create([this, option], this._def);
750
+ }
751
+ and(incoming) {
752
+ return ZodIntersection.create(this, incoming, this._def);
753
+ }
754
+ transform(transform) {
755
+ return new ZodEffects({
756
+ ...processCreateParams(this._def),
757
+ schema: this,
758
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
759
+ effect: {
760
+ type: "transform",
761
+ transform
762
+ }
763
+ });
764
+ }
765
+ default(def) {
766
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
767
+ return new ZodDefault({
768
+ ...processCreateParams(this._def),
769
+ innerType: this,
770
+ defaultValue: defaultValueFunc,
771
+ typeName: ZodFirstPartyTypeKind.ZodDefault
772
+ });
773
+ }
774
+ brand() {
775
+ return new ZodBranded({
776
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
777
+ type: this,
778
+ ...processCreateParams(this._def)
779
+ });
780
+ }
781
+ catch(def) {
782
+ const catchValueFunc = typeof def === "function" ? def : () => def;
783
+ return new ZodCatch({
784
+ ...processCreateParams(this._def),
785
+ innerType: this,
786
+ catchValue: catchValueFunc,
787
+ typeName: ZodFirstPartyTypeKind.ZodCatch
788
+ });
789
+ }
790
+ describe(description) {
791
+ const This = this.constructor;
792
+ return new This({
793
+ ...this._def,
794
+ description
795
+ });
796
+ }
797
+ pipe(target) {
798
+ return ZodPipeline.create(this, target);
799
+ }
800
+ readonly() {
801
+ return ZodReadonly.create(this);
802
+ }
803
+ isOptional() {
804
+ return this.safeParse(void 0).success;
805
+ }
806
+ isNullable() {
807
+ return this.safeParse(null).success;
808
+ }
809
+ };
810
+ const cuidRegex = /^c[^\s-]{8,}$/i;
811
+ const cuid2Regex = /^[0-9a-z]+$/;
812
+ const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
813
+ const uuidRegex = /^[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;
814
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
815
+ const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
816
+ const durationRegex = /^[-+]?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)?)??$/;
817
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
818
+ const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
819
+ let emojiRegex;
820
+ const ipv4Regex = /^(?:(?: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])$/;
821
+ const ipv4CidrRegex = /^(?:(?: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])$/;
822
+ const ipv6Regex = /^(([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]))$/;
823
+ const ipv6CidrRegex = /^(([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])$/;
824
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
825
+ const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
826
+ const dateRegexSource = `((\\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])))`;
827
+ const dateRegex = /* @__PURE__ */ new RegExp(`^${dateRegexSource}$`);
828
+ function timeRegexSource(args) {
829
+ let secondsRegexSource = `[0-5]\\d`;
830
+ if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
831
+ else if (args.precision == null) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
832
+ const secondsQuantifier = args.precision ? "+" : "?";
833
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
834
+ }
835
+ function timeRegex(args) {
836
+ return /* @__PURE__ */ new RegExp(`^${timeRegexSource(args)}$`);
837
+ }
838
+ function datetimeRegex(args) {
839
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
840
+ const opts = [];
841
+ opts.push(args.local ? `Z?` : `Z`);
842
+ if (args.offset) opts.push(`([+-]\\d{2}:?\\d{2})`);
843
+ regex = `${regex}(${opts.join("|")})`;
844
+ return /* @__PURE__ */ new RegExp(`^${regex}$`);
845
+ }
846
+ function isValidIP(ip, version) {
847
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) return true;
848
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) return true;
849
+ return false;
850
+ }
851
+ function isValidJWT(jwt, alg) {
852
+ if (!jwtRegex.test(jwt)) return false;
853
+ try {
854
+ const [header] = jwt.split(".");
855
+ if (!header) return false;
856
+ const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
857
+ const decoded = JSON.parse(atob(base64));
858
+ if (typeof decoded !== "object" || decoded === null) return false;
859
+ if ("typ" in decoded && decoded?.typ !== "JWT") return false;
860
+ if (!decoded.alg) return false;
861
+ if (alg && decoded.alg !== alg) return false;
862
+ return true;
863
+ } catch {
864
+ return false;
865
+ }
866
+ }
867
+ function isValidCidr(ip, version) {
868
+ if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) return true;
869
+ if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) return true;
870
+ return false;
871
+ }
872
+ var ZodString = class ZodString extends ZodType {
873
+ _parse(input) {
874
+ if (this._def.coerce) input.data = String(input.data);
875
+ const parsedType = this._getType(input);
876
+ if (parsedType !== ZodParsedType.string) {
877
+ const ctx$1 = this._getOrReturnCtx(input);
878
+ addIssueToContext(ctx$1, {
879
+ code: ZodIssueCode.invalid_type,
880
+ expected: ZodParsedType.string,
881
+ received: ctx$1.parsedType
882
+ });
883
+ return INVALID;
884
+ }
885
+ const status = new ParseStatus();
886
+ let ctx = void 0;
887
+ for (const check of this._def.checks) if (check.kind === "min") {
888
+ if (input.data.length < check.value) {
889
+ ctx = this._getOrReturnCtx(input, ctx);
890
+ addIssueToContext(ctx, {
891
+ code: ZodIssueCode.too_small,
892
+ minimum: check.value,
893
+ type: "string",
894
+ inclusive: true,
895
+ exact: false,
896
+ message: check.message
897
+ });
898
+ status.dirty();
899
+ }
900
+ } else if (check.kind === "max") {
901
+ if (input.data.length > check.value) {
902
+ ctx = this._getOrReturnCtx(input, ctx);
903
+ addIssueToContext(ctx, {
904
+ code: ZodIssueCode.too_big,
905
+ maximum: check.value,
906
+ type: "string",
907
+ inclusive: true,
908
+ exact: false,
909
+ message: check.message
910
+ });
911
+ status.dirty();
912
+ }
913
+ } else if (check.kind === "length") {
914
+ const tooBig = input.data.length > check.value;
915
+ const tooSmall = input.data.length < check.value;
916
+ if (tooBig || tooSmall) {
917
+ ctx = this._getOrReturnCtx(input, ctx);
918
+ if (tooBig) addIssueToContext(ctx, {
919
+ code: ZodIssueCode.too_big,
920
+ maximum: check.value,
921
+ type: "string",
922
+ inclusive: true,
923
+ exact: true,
924
+ message: check.message
925
+ });
926
+ else if (tooSmall) addIssueToContext(ctx, {
927
+ code: ZodIssueCode.too_small,
928
+ minimum: check.value,
929
+ type: "string",
930
+ inclusive: true,
931
+ exact: true,
932
+ message: check.message
933
+ });
934
+ status.dirty();
935
+ }
936
+ } else if (check.kind === "email") {
937
+ if (!emailRegex.test(input.data)) {
938
+ ctx = this._getOrReturnCtx(input, ctx);
939
+ addIssueToContext(ctx, {
940
+ validation: "email",
941
+ code: ZodIssueCode.invalid_string,
942
+ message: check.message
943
+ });
944
+ status.dirty();
945
+ }
946
+ } else if (check.kind === "emoji") {
947
+ if (!emojiRegex) emojiRegex = new RegExp(_emojiRegex, "u");
948
+ if (!emojiRegex.test(input.data)) {
949
+ ctx = this._getOrReturnCtx(input, ctx);
950
+ addIssueToContext(ctx, {
951
+ validation: "emoji",
952
+ code: ZodIssueCode.invalid_string,
953
+ message: check.message
954
+ });
955
+ status.dirty();
956
+ }
957
+ } else if (check.kind === "uuid") {
958
+ if (!uuidRegex.test(input.data)) {
959
+ ctx = this._getOrReturnCtx(input, ctx);
960
+ addIssueToContext(ctx, {
961
+ validation: "uuid",
962
+ code: ZodIssueCode.invalid_string,
963
+ message: check.message
964
+ });
965
+ status.dirty();
966
+ }
967
+ } else if (check.kind === "nanoid") {
968
+ if (!nanoidRegex.test(input.data)) {
969
+ ctx = this._getOrReturnCtx(input, ctx);
970
+ addIssueToContext(ctx, {
971
+ validation: "nanoid",
972
+ code: ZodIssueCode.invalid_string,
973
+ message: check.message
974
+ });
975
+ status.dirty();
976
+ }
977
+ } else if (check.kind === "cuid") {
978
+ if (!cuidRegex.test(input.data)) {
979
+ ctx = this._getOrReturnCtx(input, ctx);
980
+ addIssueToContext(ctx, {
981
+ validation: "cuid",
982
+ code: ZodIssueCode.invalid_string,
983
+ message: check.message
984
+ });
985
+ status.dirty();
986
+ }
987
+ } else if (check.kind === "cuid2") {
988
+ if (!cuid2Regex.test(input.data)) {
989
+ ctx = this._getOrReturnCtx(input, ctx);
990
+ addIssueToContext(ctx, {
991
+ validation: "cuid2",
992
+ code: ZodIssueCode.invalid_string,
993
+ message: check.message
994
+ });
995
+ status.dirty();
996
+ }
997
+ } else if (check.kind === "ulid") {
998
+ if (!ulidRegex.test(input.data)) {
999
+ ctx = this._getOrReturnCtx(input, ctx);
1000
+ addIssueToContext(ctx, {
1001
+ validation: "ulid",
1002
+ code: ZodIssueCode.invalid_string,
1003
+ message: check.message
1004
+ });
1005
+ status.dirty();
1006
+ }
1007
+ } else if (check.kind === "url") try {
1008
+ new URL(input.data);
1009
+ } catch {
1010
+ ctx = this._getOrReturnCtx(input, ctx);
1011
+ addIssueToContext(ctx, {
1012
+ validation: "url",
1013
+ code: ZodIssueCode.invalid_string,
1014
+ message: check.message
1015
+ });
1016
+ status.dirty();
1017
+ }
1018
+ else if (check.kind === "regex") {
1019
+ check.regex.lastIndex = 0;
1020
+ const testResult = check.regex.test(input.data);
1021
+ if (!testResult) {
1022
+ ctx = this._getOrReturnCtx(input, ctx);
1023
+ addIssueToContext(ctx, {
1024
+ validation: "regex",
1025
+ code: ZodIssueCode.invalid_string,
1026
+ message: check.message
1027
+ });
1028
+ status.dirty();
1029
+ }
1030
+ } else if (check.kind === "trim") input.data = input.data.trim();
1031
+ else if (check.kind === "includes") {
1032
+ if (!input.data.includes(check.value, check.position)) {
1033
+ ctx = this._getOrReturnCtx(input, ctx);
1034
+ addIssueToContext(ctx, {
1035
+ code: ZodIssueCode.invalid_string,
1036
+ validation: {
1037
+ includes: check.value,
1038
+ position: check.position
1039
+ },
1040
+ message: check.message
1041
+ });
1042
+ status.dirty();
1043
+ }
1044
+ } else if (check.kind === "toLowerCase") input.data = input.data.toLowerCase();
1045
+ else if (check.kind === "toUpperCase") input.data = input.data.toUpperCase();
1046
+ else if (check.kind === "startsWith") {
1047
+ if (!input.data.startsWith(check.value)) {
1048
+ ctx = this._getOrReturnCtx(input, ctx);
1049
+ addIssueToContext(ctx, {
1050
+ code: ZodIssueCode.invalid_string,
1051
+ validation: { startsWith: check.value },
1052
+ message: check.message
1053
+ });
1054
+ status.dirty();
1055
+ }
1056
+ } else if (check.kind === "endsWith") {
1057
+ if (!input.data.endsWith(check.value)) {
1058
+ ctx = this._getOrReturnCtx(input, ctx);
1059
+ addIssueToContext(ctx, {
1060
+ code: ZodIssueCode.invalid_string,
1061
+ validation: { endsWith: check.value },
1062
+ message: check.message
1063
+ });
1064
+ status.dirty();
1065
+ }
1066
+ } else if (check.kind === "datetime") {
1067
+ const regex = datetimeRegex(check);
1068
+ if (!regex.test(input.data)) {
1069
+ ctx = this._getOrReturnCtx(input, ctx);
1070
+ addIssueToContext(ctx, {
1071
+ code: ZodIssueCode.invalid_string,
1072
+ validation: "datetime",
1073
+ message: check.message
1074
+ });
1075
+ status.dirty();
1076
+ }
1077
+ } else if (check.kind === "date") {
1078
+ const regex = dateRegex;
1079
+ if (!regex.test(input.data)) {
1080
+ ctx = this._getOrReturnCtx(input, ctx);
1081
+ addIssueToContext(ctx, {
1082
+ code: ZodIssueCode.invalid_string,
1083
+ validation: "date",
1084
+ message: check.message
1085
+ });
1086
+ status.dirty();
1087
+ }
1088
+ } else if (check.kind === "time") {
1089
+ const regex = timeRegex(check);
1090
+ if (!regex.test(input.data)) {
1091
+ ctx = this._getOrReturnCtx(input, ctx);
1092
+ addIssueToContext(ctx, {
1093
+ code: ZodIssueCode.invalid_string,
1094
+ validation: "time",
1095
+ message: check.message
1096
+ });
1097
+ status.dirty();
1098
+ }
1099
+ } else if (check.kind === "duration") {
1100
+ if (!durationRegex.test(input.data)) {
1101
+ ctx = this._getOrReturnCtx(input, ctx);
1102
+ addIssueToContext(ctx, {
1103
+ validation: "duration",
1104
+ code: ZodIssueCode.invalid_string,
1105
+ message: check.message
1106
+ });
1107
+ status.dirty();
1108
+ }
1109
+ } else if (check.kind === "ip") {
1110
+ if (!isValidIP(input.data, check.version)) {
1111
+ ctx = this._getOrReturnCtx(input, ctx);
1112
+ addIssueToContext(ctx, {
1113
+ validation: "ip",
1114
+ code: ZodIssueCode.invalid_string,
1115
+ message: check.message
1116
+ });
1117
+ status.dirty();
1118
+ }
1119
+ } else if (check.kind === "jwt") {
1120
+ if (!isValidJWT(input.data, check.alg)) {
1121
+ ctx = this._getOrReturnCtx(input, ctx);
1122
+ addIssueToContext(ctx, {
1123
+ validation: "jwt",
1124
+ code: ZodIssueCode.invalid_string,
1125
+ message: check.message
1126
+ });
1127
+ status.dirty();
1128
+ }
1129
+ } else if (check.kind === "cidr") {
1130
+ if (!isValidCidr(input.data, check.version)) {
1131
+ ctx = this._getOrReturnCtx(input, ctx);
1132
+ addIssueToContext(ctx, {
1133
+ validation: "cidr",
1134
+ code: ZodIssueCode.invalid_string,
1135
+ message: check.message
1136
+ });
1137
+ status.dirty();
1138
+ }
1139
+ } else if (check.kind === "base64") {
1140
+ if (!base64Regex.test(input.data)) {
1141
+ ctx = this._getOrReturnCtx(input, ctx);
1142
+ addIssueToContext(ctx, {
1143
+ validation: "base64",
1144
+ code: ZodIssueCode.invalid_string,
1145
+ message: check.message
1146
+ });
1147
+ status.dirty();
1148
+ }
1149
+ } else if (check.kind === "base64url") {
1150
+ if (!base64urlRegex.test(input.data)) {
1151
+ ctx = this._getOrReturnCtx(input, ctx);
1152
+ addIssueToContext(ctx, {
1153
+ validation: "base64url",
1154
+ code: ZodIssueCode.invalid_string,
1155
+ message: check.message
1156
+ });
1157
+ status.dirty();
1158
+ }
1159
+ } else util.assertNever(check);
1160
+ return {
1161
+ status: status.value,
1162
+ value: input.data
1163
+ };
1164
+ }
1165
+ _regex(regex, validation, message) {
1166
+ return this.refinement((data) => regex.test(data), {
1167
+ validation,
1168
+ code: ZodIssueCode.invalid_string,
1169
+ ...errorUtil.errToObj(message)
1170
+ });
1171
+ }
1172
+ _addCheck(check) {
1173
+ return new ZodString({
1174
+ ...this._def,
1175
+ checks: [...this._def.checks, check]
1176
+ });
1177
+ }
1178
+ email(message) {
1179
+ return this._addCheck({
1180
+ kind: "email",
1181
+ ...errorUtil.errToObj(message)
1182
+ });
1183
+ }
1184
+ url(message) {
1185
+ return this._addCheck({
1186
+ kind: "url",
1187
+ ...errorUtil.errToObj(message)
1188
+ });
1189
+ }
1190
+ emoji(message) {
1191
+ return this._addCheck({
1192
+ kind: "emoji",
1193
+ ...errorUtil.errToObj(message)
1194
+ });
1195
+ }
1196
+ uuid(message) {
1197
+ return this._addCheck({
1198
+ kind: "uuid",
1199
+ ...errorUtil.errToObj(message)
1200
+ });
1201
+ }
1202
+ nanoid(message) {
1203
+ return this._addCheck({
1204
+ kind: "nanoid",
1205
+ ...errorUtil.errToObj(message)
1206
+ });
1207
+ }
1208
+ cuid(message) {
1209
+ return this._addCheck({
1210
+ kind: "cuid",
1211
+ ...errorUtil.errToObj(message)
1212
+ });
1213
+ }
1214
+ cuid2(message) {
1215
+ return this._addCheck({
1216
+ kind: "cuid2",
1217
+ ...errorUtil.errToObj(message)
1218
+ });
1219
+ }
1220
+ ulid(message) {
1221
+ return this._addCheck({
1222
+ kind: "ulid",
1223
+ ...errorUtil.errToObj(message)
1224
+ });
1225
+ }
1226
+ base64(message) {
1227
+ return this._addCheck({
1228
+ kind: "base64",
1229
+ ...errorUtil.errToObj(message)
1230
+ });
1231
+ }
1232
+ base64url(message) {
1233
+ return this._addCheck({
1234
+ kind: "base64url",
1235
+ ...errorUtil.errToObj(message)
1236
+ });
1237
+ }
1238
+ jwt(options) {
1239
+ return this._addCheck({
1240
+ kind: "jwt",
1241
+ ...errorUtil.errToObj(options)
1242
+ });
1243
+ }
1244
+ ip(options) {
1245
+ return this._addCheck({
1246
+ kind: "ip",
1247
+ ...errorUtil.errToObj(options)
1248
+ });
1249
+ }
1250
+ cidr(options) {
1251
+ return this._addCheck({
1252
+ kind: "cidr",
1253
+ ...errorUtil.errToObj(options)
1254
+ });
1255
+ }
1256
+ datetime(options) {
1257
+ if (typeof options === "string") return this._addCheck({
1258
+ kind: "datetime",
1259
+ precision: null,
1260
+ offset: false,
1261
+ local: false,
1262
+ message: options
1263
+ });
1264
+ return this._addCheck({
1265
+ kind: "datetime",
1266
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1267
+ offset: options?.offset ?? false,
1268
+ local: options?.local ?? false,
1269
+ ...errorUtil.errToObj(options?.message)
1270
+ });
1271
+ }
1272
+ date(message) {
1273
+ return this._addCheck({
1274
+ kind: "date",
1275
+ message
1276
+ });
1277
+ }
1278
+ time(options) {
1279
+ if (typeof options === "string") return this._addCheck({
1280
+ kind: "time",
1281
+ precision: null,
1282
+ message: options
1283
+ });
1284
+ return this._addCheck({
1285
+ kind: "time",
1286
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
1287
+ ...errorUtil.errToObj(options?.message)
1288
+ });
1289
+ }
1290
+ duration(message) {
1291
+ return this._addCheck({
1292
+ kind: "duration",
1293
+ ...errorUtil.errToObj(message)
1294
+ });
1295
+ }
1296
+ regex(regex, message) {
1297
+ return this._addCheck({
1298
+ kind: "regex",
1299
+ regex,
1300
+ ...errorUtil.errToObj(message)
1301
+ });
1302
+ }
1303
+ includes(value, options) {
1304
+ return this._addCheck({
1305
+ kind: "includes",
1306
+ value,
1307
+ position: options?.position,
1308
+ ...errorUtil.errToObj(options?.message)
1309
+ });
1310
+ }
1311
+ startsWith(value, message) {
1312
+ return this._addCheck({
1313
+ kind: "startsWith",
1314
+ value,
1315
+ ...errorUtil.errToObj(message)
1316
+ });
1317
+ }
1318
+ endsWith(value, message) {
1319
+ return this._addCheck({
1320
+ kind: "endsWith",
1321
+ value,
1322
+ ...errorUtil.errToObj(message)
1323
+ });
1324
+ }
1325
+ min(minLength, message) {
1326
+ return this._addCheck({
1327
+ kind: "min",
1328
+ value: minLength,
1329
+ ...errorUtil.errToObj(message)
1330
+ });
1331
+ }
1332
+ max(maxLength, message) {
1333
+ return this._addCheck({
1334
+ kind: "max",
1335
+ value: maxLength,
1336
+ ...errorUtil.errToObj(message)
1337
+ });
1338
+ }
1339
+ length(len, message) {
1340
+ return this._addCheck({
1341
+ kind: "length",
1342
+ value: len,
1343
+ ...errorUtil.errToObj(message)
1344
+ });
1345
+ }
1346
+ /**
1347
+ * Equivalent to `.min(1)`
1348
+ */
1349
+ nonempty(message) {
1350
+ return this.min(1, errorUtil.errToObj(message));
1351
+ }
1352
+ trim() {
1353
+ return new ZodString({
1354
+ ...this._def,
1355
+ checks: [...this._def.checks, { kind: "trim" }]
1356
+ });
1357
+ }
1358
+ toLowerCase() {
1359
+ return new ZodString({
1360
+ ...this._def,
1361
+ checks: [...this._def.checks, { kind: "toLowerCase" }]
1362
+ });
1363
+ }
1364
+ toUpperCase() {
1365
+ return new ZodString({
1366
+ ...this._def,
1367
+ checks: [...this._def.checks, { kind: "toUpperCase" }]
1368
+ });
1369
+ }
1370
+ get isDatetime() {
1371
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
1372
+ }
1373
+ get isDate() {
1374
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1375
+ }
1376
+ get isTime() {
1377
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1378
+ }
1379
+ get isDuration() {
1380
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1381
+ }
1382
+ get isEmail() {
1383
+ return !!this._def.checks.find((ch) => ch.kind === "email");
1384
+ }
1385
+ get isURL() {
1386
+ return !!this._def.checks.find((ch) => ch.kind === "url");
1387
+ }
1388
+ get isEmoji() {
1389
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
1390
+ }
1391
+ get isUUID() {
1392
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
1393
+ }
1394
+ get isNANOID() {
1395
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1396
+ }
1397
+ get isCUID() {
1398
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
1399
+ }
1400
+ get isCUID2() {
1401
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
1402
+ }
1403
+ get isULID() {
1404
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
1405
+ }
1406
+ get isIP() {
1407
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
1408
+ }
1409
+ get isCIDR() {
1410
+ return !!this._def.checks.find((ch) => ch.kind === "cidr");
1411
+ }
1412
+ get isBase64() {
1413
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1414
+ }
1415
+ get isBase64url() {
1416
+ return !!this._def.checks.find((ch) => ch.kind === "base64url");
1417
+ }
1418
+ get minLength() {
1419
+ let min = null;
1420
+ for (const ch of this._def.checks) if (ch.kind === "min") {
1421
+ if (min === null || ch.value > min) min = ch.value;
1422
+ }
1423
+ return min;
1424
+ }
1425
+ get maxLength() {
1426
+ let max = null;
1427
+ for (const ch of this._def.checks) if (ch.kind === "max") {
1428
+ if (max === null || ch.value < max) max = ch.value;
1429
+ }
1430
+ return max;
1431
+ }
1432
+ };
1433
+ ZodString.create = (params) => {
1434
+ return new ZodString({
1435
+ checks: [],
1436
+ typeName: ZodFirstPartyTypeKind.ZodString,
1437
+ coerce: params?.coerce ?? false,
1438
+ ...processCreateParams(params)
1439
+ });
1440
+ };
1441
+ function floatSafeRemainder(val, step) {
1442
+ const valDecCount = (val.toString().split(".")[1] || "").length;
1443
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
1444
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
1445
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
1446
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
1447
+ return valInt % stepInt / 10 ** decCount;
1448
+ }
1449
+ var ZodNumber = class ZodNumber extends ZodType {
1450
+ constructor() {
1451
+ super(...arguments);
1452
+ this.min = this.gte;
1453
+ this.max = this.lte;
1454
+ this.step = this.multipleOf;
1455
+ }
1456
+ _parse(input) {
1457
+ if (this._def.coerce) input.data = Number(input.data);
1458
+ const parsedType = this._getType(input);
1459
+ if (parsedType !== ZodParsedType.number) {
1460
+ const ctx$1 = this._getOrReturnCtx(input);
1461
+ addIssueToContext(ctx$1, {
1462
+ code: ZodIssueCode.invalid_type,
1463
+ expected: ZodParsedType.number,
1464
+ received: ctx$1.parsedType
1465
+ });
1466
+ return INVALID;
1467
+ }
1468
+ let ctx = void 0;
1469
+ const status = new ParseStatus();
1470
+ for (const check of this._def.checks) if (check.kind === "int") {
1471
+ if (!util.isInteger(input.data)) {
1472
+ ctx = this._getOrReturnCtx(input, ctx);
1473
+ addIssueToContext(ctx, {
1474
+ code: ZodIssueCode.invalid_type,
1475
+ expected: "integer",
1476
+ received: "float",
1477
+ message: check.message
1478
+ });
1479
+ status.dirty();
1480
+ }
1481
+ } else if (check.kind === "min") {
1482
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1483
+ if (tooSmall) {
1484
+ ctx = this._getOrReturnCtx(input, ctx);
1485
+ addIssueToContext(ctx, {
1486
+ code: ZodIssueCode.too_small,
1487
+ minimum: check.value,
1488
+ type: "number",
1489
+ inclusive: check.inclusive,
1490
+ exact: false,
1491
+ message: check.message
1492
+ });
1493
+ status.dirty();
1494
+ }
1495
+ } else if (check.kind === "max") {
1496
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1497
+ if (tooBig) {
1498
+ ctx = this._getOrReturnCtx(input, ctx);
1499
+ addIssueToContext(ctx, {
1500
+ code: ZodIssueCode.too_big,
1501
+ maximum: check.value,
1502
+ type: "number",
1503
+ inclusive: check.inclusive,
1504
+ exact: false,
1505
+ message: check.message
1506
+ });
1507
+ status.dirty();
1508
+ }
1509
+ } else if (check.kind === "multipleOf") {
1510
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
1511
+ ctx = this._getOrReturnCtx(input, ctx);
1512
+ addIssueToContext(ctx, {
1513
+ code: ZodIssueCode.not_multiple_of,
1514
+ multipleOf: check.value,
1515
+ message: check.message
1516
+ });
1517
+ status.dirty();
1518
+ }
1519
+ } else if (check.kind === "finite") {
1520
+ if (!Number.isFinite(input.data)) {
1521
+ ctx = this._getOrReturnCtx(input, ctx);
1522
+ addIssueToContext(ctx, {
1523
+ code: ZodIssueCode.not_finite,
1524
+ message: check.message
1525
+ });
1526
+ status.dirty();
1527
+ }
1528
+ } else util.assertNever(check);
1529
+ return {
1530
+ status: status.value,
1531
+ value: input.data
1532
+ };
1533
+ }
1534
+ gte(value, message) {
1535
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1536
+ }
1537
+ gt(value, message) {
1538
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1539
+ }
1540
+ lte(value, message) {
1541
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1542
+ }
1543
+ lt(value, message) {
1544
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1545
+ }
1546
+ setLimit(kind, value, inclusive, message) {
1547
+ return new ZodNumber({
1548
+ ...this._def,
1549
+ checks: [...this._def.checks, {
1550
+ kind,
1551
+ value,
1552
+ inclusive,
1553
+ message: errorUtil.toString(message)
1554
+ }]
1555
+ });
1556
+ }
1557
+ _addCheck(check) {
1558
+ return new ZodNumber({
1559
+ ...this._def,
1560
+ checks: [...this._def.checks, check]
1561
+ });
1562
+ }
1563
+ int(message) {
1564
+ return this._addCheck({
1565
+ kind: "int",
1566
+ message: errorUtil.toString(message)
1567
+ });
1568
+ }
1569
+ positive(message) {
1570
+ return this._addCheck({
1571
+ kind: "min",
1572
+ value: 0,
1573
+ inclusive: false,
1574
+ message: errorUtil.toString(message)
1575
+ });
1576
+ }
1577
+ negative(message) {
1578
+ return this._addCheck({
1579
+ kind: "max",
1580
+ value: 0,
1581
+ inclusive: false,
1582
+ message: errorUtil.toString(message)
1583
+ });
1584
+ }
1585
+ nonpositive(message) {
1586
+ return this._addCheck({
1587
+ kind: "max",
1588
+ value: 0,
1589
+ inclusive: true,
1590
+ message: errorUtil.toString(message)
1591
+ });
1592
+ }
1593
+ nonnegative(message) {
1594
+ return this._addCheck({
1595
+ kind: "min",
1596
+ value: 0,
1597
+ inclusive: true,
1598
+ message: errorUtil.toString(message)
1599
+ });
1600
+ }
1601
+ multipleOf(value, message) {
1602
+ return this._addCheck({
1603
+ kind: "multipleOf",
1604
+ value,
1605
+ message: errorUtil.toString(message)
1606
+ });
1607
+ }
1608
+ finite(message) {
1609
+ return this._addCheck({
1610
+ kind: "finite",
1611
+ message: errorUtil.toString(message)
1612
+ });
1613
+ }
1614
+ safe(message) {
1615
+ return this._addCheck({
1616
+ kind: "min",
1617
+ inclusive: true,
1618
+ value: Number.MIN_SAFE_INTEGER,
1619
+ message: errorUtil.toString(message)
1620
+ })._addCheck({
1621
+ kind: "max",
1622
+ inclusive: true,
1623
+ value: Number.MAX_SAFE_INTEGER,
1624
+ message: errorUtil.toString(message)
1625
+ });
1626
+ }
1627
+ get minValue() {
1628
+ let min = null;
1629
+ for (const ch of this._def.checks) if (ch.kind === "min") {
1630
+ if (min === null || ch.value > min) min = ch.value;
1631
+ }
1632
+ return min;
1633
+ }
1634
+ get maxValue() {
1635
+ let max = null;
1636
+ for (const ch of this._def.checks) if (ch.kind === "max") {
1637
+ if (max === null || ch.value < max) max = ch.value;
1638
+ }
1639
+ return max;
1640
+ }
1641
+ get isInt() {
1642
+ return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
1643
+ }
1644
+ get isFinite() {
1645
+ let max = null;
1646
+ let min = null;
1647
+ for (const ch of this._def.checks) if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") return true;
1648
+ else if (ch.kind === "min") {
1649
+ if (min === null || ch.value > min) min = ch.value;
1650
+ } else if (ch.kind === "max") {
1651
+ if (max === null || ch.value < max) max = ch.value;
1652
+ }
1653
+ return Number.isFinite(min) && Number.isFinite(max);
1654
+ }
1655
+ };
1656
+ ZodNumber.create = (params) => {
1657
+ return new ZodNumber({
1658
+ checks: [],
1659
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
1660
+ coerce: params?.coerce || false,
1661
+ ...processCreateParams(params)
1662
+ });
1663
+ };
1664
+ var ZodBigInt = class ZodBigInt extends ZodType {
1665
+ constructor() {
1666
+ super(...arguments);
1667
+ this.min = this.gte;
1668
+ this.max = this.lte;
1669
+ }
1670
+ _parse(input) {
1671
+ if (this._def.coerce) try {
1672
+ input.data = BigInt(input.data);
1673
+ } catch {
1674
+ return this._getInvalidInput(input);
1675
+ }
1676
+ const parsedType = this._getType(input);
1677
+ if (parsedType !== ZodParsedType.bigint) return this._getInvalidInput(input);
1678
+ let ctx = void 0;
1679
+ const status = new ParseStatus();
1680
+ for (const check of this._def.checks) if (check.kind === "min") {
1681
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
1682
+ if (tooSmall) {
1683
+ ctx = this._getOrReturnCtx(input, ctx);
1684
+ addIssueToContext(ctx, {
1685
+ code: ZodIssueCode.too_small,
1686
+ type: "bigint",
1687
+ minimum: check.value,
1688
+ inclusive: check.inclusive,
1689
+ message: check.message
1690
+ });
1691
+ status.dirty();
1692
+ }
1693
+ } else if (check.kind === "max") {
1694
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
1695
+ if (tooBig) {
1696
+ ctx = this._getOrReturnCtx(input, ctx);
1697
+ addIssueToContext(ctx, {
1698
+ code: ZodIssueCode.too_big,
1699
+ type: "bigint",
1700
+ maximum: check.value,
1701
+ inclusive: check.inclusive,
1702
+ message: check.message
1703
+ });
1704
+ status.dirty();
1705
+ }
1706
+ } else if (check.kind === "multipleOf") {
1707
+ if (input.data % check.value !== BigInt(0)) {
1708
+ ctx = this._getOrReturnCtx(input, ctx);
1709
+ addIssueToContext(ctx, {
1710
+ code: ZodIssueCode.not_multiple_of,
1711
+ multipleOf: check.value,
1712
+ message: check.message
1713
+ });
1714
+ status.dirty();
1715
+ }
1716
+ } else util.assertNever(check);
1717
+ return {
1718
+ status: status.value,
1719
+ value: input.data
1720
+ };
1721
+ }
1722
+ _getInvalidInput(input) {
1723
+ const ctx = this._getOrReturnCtx(input);
1724
+ addIssueToContext(ctx, {
1725
+ code: ZodIssueCode.invalid_type,
1726
+ expected: ZodParsedType.bigint,
1727
+ received: ctx.parsedType
1728
+ });
1729
+ return INVALID;
1730
+ }
1731
+ gte(value, message) {
1732
+ return this.setLimit("min", value, true, errorUtil.toString(message));
1733
+ }
1734
+ gt(value, message) {
1735
+ return this.setLimit("min", value, false, errorUtil.toString(message));
1736
+ }
1737
+ lte(value, message) {
1738
+ return this.setLimit("max", value, true, errorUtil.toString(message));
1739
+ }
1740
+ lt(value, message) {
1741
+ return this.setLimit("max", value, false, errorUtil.toString(message));
1742
+ }
1743
+ setLimit(kind, value, inclusive, message) {
1744
+ return new ZodBigInt({
1745
+ ...this._def,
1746
+ checks: [...this._def.checks, {
1747
+ kind,
1748
+ value,
1749
+ inclusive,
1750
+ message: errorUtil.toString(message)
1751
+ }]
1752
+ });
1753
+ }
1754
+ _addCheck(check) {
1755
+ return new ZodBigInt({
1756
+ ...this._def,
1757
+ checks: [...this._def.checks, check]
1758
+ });
1759
+ }
1760
+ positive(message) {
1761
+ return this._addCheck({
1762
+ kind: "min",
1763
+ value: BigInt(0),
1764
+ inclusive: false,
1765
+ message: errorUtil.toString(message)
1766
+ });
1767
+ }
1768
+ negative(message) {
1769
+ return this._addCheck({
1770
+ kind: "max",
1771
+ value: BigInt(0),
1772
+ inclusive: false,
1773
+ message: errorUtil.toString(message)
1774
+ });
1775
+ }
1776
+ nonpositive(message) {
1777
+ return this._addCheck({
1778
+ kind: "max",
1779
+ value: BigInt(0),
1780
+ inclusive: true,
1781
+ message: errorUtil.toString(message)
1782
+ });
1783
+ }
1784
+ nonnegative(message) {
1785
+ return this._addCheck({
1786
+ kind: "min",
1787
+ value: BigInt(0),
1788
+ inclusive: true,
1789
+ message: errorUtil.toString(message)
1790
+ });
1791
+ }
1792
+ multipleOf(value, message) {
1793
+ return this._addCheck({
1794
+ kind: "multipleOf",
1795
+ value,
1796
+ message: errorUtil.toString(message)
1797
+ });
1798
+ }
1799
+ get minValue() {
1800
+ let min = null;
1801
+ for (const ch of this._def.checks) if (ch.kind === "min") {
1802
+ if (min === null || ch.value > min) min = ch.value;
1803
+ }
1804
+ return min;
1805
+ }
1806
+ get maxValue() {
1807
+ let max = null;
1808
+ for (const ch of this._def.checks) if (ch.kind === "max") {
1809
+ if (max === null || ch.value < max) max = ch.value;
1810
+ }
1811
+ return max;
1812
+ }
1813
+ };
1814
+ ZodBigInt.create = (params) => {
1815
+ return new ZodBigInt({
1816
+ checks: [],
1817
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
1818
+ coerce: params?.coerce ?? false,
1819
+ ...processCreateParams(params)
1820
+ });
1821
+ };
1822
+ var ZodBoolean = class extends ZodType {
1823
+ _parse(input) {
1824
+ if (this._def.coerce) input.data = Boolean(input.data);
1825
+ const parsedType = this._getType(input);
1826
+ if (parsedType !== ZodParsedType.boolean) {
1827
+ const ctx = this._getOrReturnCtx(input);
1828
+ addIssueToContext(ctx, {
1829
+ code: ZodIssueCode.invalid_type,
1830
+ expected: ZodParsedType.boolean,
1831
+ received: ctx.parsedType
1832
+ });
1833
+ return INVALID;
1834
+ }
1835
+ return OK(input.data);
1836
+ }
1837
+ };
1838
+ ZodBoolean.create = (params) => {
1839
+ return new ZodBoolean({
1840
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
1841
+ coerce: params?.coerce || false,
1842
+ ...processCreateParams(params)
1843
+ });
1844
+ };
1845
+ var ZodDate = class ZodDate extends ZodType {
1846
+ _parse(input) {
1847
+ if (this._def.coerce) input.data = new Date(input.data);
1848
+ const parsedType = this._getType(input);
1849
+ if (parsedType !== ZodParsedType.date) {
1850
+ const ctx$1 = this._getOrReturnCtx(input);
1851
+ addIssueToContext(ctx$1, {
1852
+ code: ZodIssueCode.invalid_type,
1853
+ expected: ZodParsedType.date,
1854
+ received: ctx$1.parsedType
1855
+ });
1856
+ return INVALID;
1857
+ }
1858
+ if (Number.isNaN(input.data.getTime())) {
1859
+ const ctx$1 = this._getOrReturnCtx(input);
1860
+ addIssueToContext(ctx$1, { code: ZodIssueCode.invalid_date });
1861
+ return INVALID;
1862
+ }
1863
+ const status = new ParseStatus();
1864
+ let ctx = void 0;
1865
+ for (const check of this._def.checks) if (check.kind === "min") {
1866
+ if (input.data.getTime() < check.value) {
1867
+ ctx = this._getOrReturnCtx(input, ctx);
1868
+ addIssueToContext(ctx, {
1869
+ code: ZodIssueCode.too_small,
1870
+ message: check.message,
1871
+ inclusive: true,
1872
+ exact: false,
1873
+ minimum: check.value,
1874
+ type: "date"
1875
+ });
1876
+ status.dirty();
1877
+ }
1878
+ } else if (check.kind === "max") {
1879
+ if (input.data.getTime() > check.value) {
1880
+ ctx = this._getOrReturnCtx(input, ctx);
1881
+ addIssueToContext(ctx, {
1882
+ code: ZodIssueCode.too_big,
1883
+ message: check.message,
1884
+ inclusive: true,
1885
+ exact: false,
1886
+ maximum: check.value,
1887
+ type: "date"
1888
+ });
1889
+ status.dirty();
1890
+ }
1891
+ } else util.assertNever(check);
1892
+ return {
1893
+ status: status.value,
1894
+ value: new Date(input.data.getTime())
1895
+ };
1896
+ }
1897
+ _addCheck(check) {
1898
+ return new ZodDate({
1899
+ ...this._def,
1900
+ checks: [...this._def.checks, check]
1901
+ });
1902
+ }
1903
+ min(minDate, message) {
1904
+ return this._addCheck({
1905
+ kind: "min",
1906
+ value: minDate.getTime(),
1907
+ message: errorUtil.toString(message)
1908
+ });
1909
+ }
1910
+ max(maxDate, message) {
1911
+ return this._addCheck({
1912
+ kind: "max",
1913
+ value: maxDate.getTime(),
1914
+ message: errorUtil.toString(message)
1915
+ });
1916
+ }
1917
+ get minDate() {
1918
+ let min = null;
1919
+ for (const ch of this._def.checks) if (ch.kind === "min") {
1920
+ if (min === null || ch.value > min) min = ch.value;
1921
+ }
1922
+ return min != null ? new Date(min) : null;
1923
+ }
1924
+ get maxDate() {
1925
+ let max = null;
1926
+ for (const ch of this._def.checks) if (ch.kind === "max") {
1927
+ if (max === null || ch.value < max) max = ch.value;
1928
+ }
1929
+ return max != null ? new Date(max) : null;
1930
+ }
1931
+ };
1932
+ ZodDate.create = (params) => {
1933
+ return new ZodDate({
1934
+ checks: [],
1935
+ coerce: params?.coerce || false,
1936
+ typeName: ZodFirstPartyTypeKind.ZodDate,
1937
+ ...processCreateParams(params)
1938
+ });
1939
+ };
1940
+ var ZodSymbol = class extends ZodType {
1941
+ _parse(input) {
1942
+ const parsedType = this._getType(input);
1943
+ if (parsedType !== ZodParsedType.symbol) {
1944
+ const ctx = this._getOrReturnCtx(input);
1945
+ addIssueToContext(ctx, {
1946
+ code: ZodIssueCode.invalid_type,
1947
+ expected: ZodParsedType.symbol,
1948
+ received: ctx.parsedType
1949
+ });
1950
+ return INVALID;
1951
+ }
1952
+ return OK(input.data);
1953
+ }
1954
+ };
1955
+ ZodSymbol.create = (params) => {
1956
+ return new ZodSymbol({
1957
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
1958
+ ...processCreateParams(params)
1959
+ });
1960
+ };
1961
+ var ZodUndefined = class extends ZodType {
1962
+ _parse(input) {
1963
+ const parsedType = this._getType(input);
1964
+ if (parsedType !== ZodParsedType.undefined) {
1965
+ const ctx = this._getOrReturnCtx(input);
1966
+ addIssueToContext(ctx, {
1967
+ code: ZodIssueCode.invalid_type,
1968
+ expected: ZodParsedType.undefined,
1969
+ received: ctx.parsedType
1970
+ });
1971
+ return INVALID;
1972
+ }
1973
+ return OK(input.data);
1974
+ }
1975
+ };
1976
+ ZodUndefined.create = (params) => {
1977
+ return new ZodUndefined({
1978
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
1979
+ ...processCreateParams(params)
1980
+ });
1981
+ };
1982
+ var ZodNull = class extends ZodType {
1983
+ _parse(input) {
1984
+ const parsedType = this._getType(input);
1985
+ if (parsedType !== ZodParsedType.null) {
1986
+ const ctx = this._getOrReturnCtx(input);
1987
+ addIssueToContext(ctx, {
1988
+ code: ZodIssueCode.invalid_type,
1989
+ expected: ZodParsedType.null,
1990
+ received: ctx.parsedType
1991
+ });
1992
+ return INVALID;
1993
+ }
1994
+ return OK(input.data);
1995
+ }
1996
+ };
1997
+ ZodNull.create = (params) => {
1998
+ return new ZodNull({
1999
+ typeName: ZodFirstPartyTypeKind.ZodNull,
2000
+ ...processCreateParams(params)
2001
+ });
2002
+ };
2003
+ var ZodAny = class extends ZodType {
2004
+ constructor() {
2005
+ super(...arguments);
2006
+ this._any = true;
2007
+ }
2008
+ _parse(input) {
2009
+ return OK(input.data);
2010
+ }
2011
+ };
2012
+ ZodAny.create = (params) => {
2013
+ return new ZodAny({
2014
+ typeName: ZodFirstPartyTypeKind.ZodAny,
2015
+ ...processCreateParams(params)
2016
+ });
2017
+ };
2018
+ var ZodUnknown = class extends ZodType {
2019
+ constructor() {
2020
+ super(...arguments);
2021
+ this._unknown = true;
2022
+ }
2023
+ _parse(input) {
2024
+ return OK(input.data);
2025
+ }
2026
+ };
2027
+ ZodUnknown.create = (params) => {
2028
+ return new ZodUnknown({
2029
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
2030
+ ...processCreateParams(params)
2031
+ });
2032
+ };
2033
+ var ZodNever = class extends ZodType {
2034
+ _parse(input) {
2035
+ const ctx = this._getOrReturnCtx(input);
2036
+ addIssueToContext(ctx, {
2037
+ code: ZodIssueCode.invalid_type,
2038
+ expected: ZodParsedType.never,
2039
+ received: ctx.parsedType
2040
+ });
2041
+ return INVALID;
2042
+ }
2043
+ };
2044
+ ZodNever.create = (params) => {
2045
+ return new ZodNever({
2046
+ typeName: ZodFirstPartyTypeKind.ZodNever,
2047
+ ...processCreateParams(params)
2048
+ });
2049
+ };
2050
+ var ZodVoid = class extends ZodType {
2051
+ _parse(input) {
2052
+ const parsedType = this._getType(input);
2053
+ if (parsedType !== ZodParsedType.undefined) {
2054
+ const ctx = this._getOrReturnCtx(input);
2055
+ addIssueToContext(ctx, {
2056
+ code: ZodIssueCode.invalid_type,
2057
+ expected: ZodParsedType.void,
2058
+ received: ctx.parsedType
2059
+ });
2060
+ return INVALID;
2061
+ }
2062
+ return OK(input.data);
2063
+ }
2064
+ };
2065
+ ZodVoid.create = (params) => {
2066
+ return new ZodVoid({
2067
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
2068
+ ...processCreateParams(params)
2069
+ });
2070
+ };
2071
+ var ZodArray = class ZodArray extends ZodType {
2072
+ _parse(input) {
2073
+ const { ctx, status } = this._processInputParams(input);
2074
+ const def = this._def;
2075
+ if (ctx.parsedType !== ZodParsedType.array) {
2076
+ addIssueToContext(ctx, {
2077
+ code: ZodIssueCode.invalid_type,
2078
+ expected: ZodParsedType.array,
2079
+ received: ctx.parsedType
2080
+ });
2081
+ return INVALID;
2082
+ }
2083
+ if (def.exactLength !== null) {
2084
+ const tooBig = ctx.data.length > def.exactLength.value;
2085
+ const tooSmall = ctx.data.length < def.exactLength.value;
2086
+ if (tooBig || tooSmall) {
2087
+ addIssueToContext(ctx, {
2088
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
2089
+ minimum: tooSmall ? def.exactLength.value : void 0,
2090
+ maximum: tooBig ? def.exactLength.value : void 0,
2091
+ type: "array",
2092
+ inclusive: true,
2093
+ exact: true,
2094
+ message: def.exactLength.message
2095
+ });
2096
+ status.dirty();
2097
+ }
2098
+ }
2099
+ if (def.minLength !== null) {
2100
+ if (ctx.data.length < def.minLength.value) {
2101
+ addIssueToContext(ctx, {
2102
+ code: ZodIssueCode.too_small,
2103
+ minimum: def.minLength.value,
2104
+ type: "array",
2105
+ inclusive: true,
2106
+ exact: false,
2107
+ message: def.minLength.message
2108
+ });
2109
+ status.dirty();
2110
+ }
2111
+ }
2112
+ if (def.maxLength !== null) {
2113
+ if (ctx.data.length > def.maxLength.value) {
2114
+ addIssueToContext(ctx, {
2115
+ code: ZodIssueCode.too_big,
2116
+ maximum: def.maxLength.value,
2117
+ type: "array",
2118
+ inclusive: true,
2119
+ exact: false,
2120
+ message: def.maxLength.message
2121
+ });
2122
+ status.dirty();
2123
+ }
2124
+ }
2125
+ if (ctx.common.async) return Promise.all([...ctx.data].map((item, i) => {
2126
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2127
+ })).then((result$1) => {
2128
+ return ParseStatus.mergeArray(status, result$1);
2129
+ });
2130
+ const result = [...ctx.data].map((item, i) => {
2131
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
2132
+ });
2133
+ return ParseStatus.mergeArray(status, result);
2134
+ }
2135
+ get element() {
2136
+ return this._def.type;
2137
+ }
2138
+ min(minLength, message) {
2139
+ return new ZodArray({
2140
+ ...this._def,
2141
+ minLength: {
2142
+ value: minLength,
2143
+ message: errorUtil.toString(message)
2144
+ }
2145
+ });
2146
+ }
2147
+ max(maxLength, message) {
2148
+ return new ZodArray({
2149
+ ...this._def,
2150
+ maxLength: {
2151
+ value: maxLength,
2152
+ message: errorUtil.toString(message)
2153
+ }
2154
+ });
2155
+ }
2156
+ length(len, message) {
2157
+ return new ZodArray({
2158
+ ...this._def,
2159
+ exactLength: {
2160
+ value: len,
2161
+ message: errorUtil.toString(message)
2162
+ }
2163
+ });
2164
+ }
2165
+ nonempty(message) {
2166
+ return this.min(1, message);
2167
+ }
2168
+ };
2169
+ ZodArray.create = (schema, params) => {
2170
+ return new ZodArray({
2171
+ type: schema,
2172
+ minLength: null,
2173
+ maxLength: null,
2174
+ exactLength: null,
2175
+ typeName: ZodFirstPartyTypeKind.ZodArray,
2176
+ ...processCreateParams(params)
2177
+ });
2178
+ };
2179
+ function deepPartialify(schema) {
2180
+ if (schema instanceof ZodObject) {
2181
+ const newShape = {};
2182
+ for (const key in schema.shape) {
2183
+ const fieldSchema = schema.shape[key];
2184
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
2185
+ }
2186
+ return new ZodObject({
2187
+ ...schema._def,
2188
+ shape: () => newShape
2189
+ });
2190
+ } else if (schema instanceof ZodArray) return new ZodArray({
2191
+ ...schema._def,
2192
+ type: deepPartialify(schema.element)
2193
+ });
2194
+ else if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap()));
2195
+ else if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap()));
2196
+ else if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
2197
+ else return schema;
2198
+ }
2199
+ var ZodObject = class ZodObject extends ZodType {
2200
+ constructor() {
2201
+ super(...arguments);
2202
+ this._cached = null;
2203
+ /**
2204
+ * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
2205
+ * If you want to pass through unknown properties, use `.passthrough()` instead.
2206
+ */
2207
+ this.nonstrict = this.passthrough;
2208
+ /**
2209
+ * @deprecated Use `.extend` instead
2210
+ * */
2211
+ this.augment = this.extend;
2212
+ }
2213
+ _getCached() {
2214
+ if (this._cached !== null) return this._cached;
2215
+ const shape = this._def.shape();
2216
+ const keys = util.objectKeys(shape);
2217
+ this._cached = {
2218
+ shape,
2219
+ keys
2220
+ };
2221
+ return this._cached;
2222
+ }
2223
+ _parse(input) {
2224
+ const parsedType = this._getType(input);
2225
+ if (parsedType !== ZodParsedType.object) {
2226
+ const ctx$1 = this._getOrReturnCtx(input);
2227
+ addIssueToContext(ctx$1, {
2228
+ code: ZodIssueCode.invalid_type,
2229
+ expected: ZodParsedType.object,
2230
+ received: ctx$1.parsedType
2231
+ });
2232
+ return INVALID;
2233
+ }
2234
+ const { status, ctx } = this._processInputParams(input);
2235
+ const { shape, keys: shapeKeys } = this._getCached();
2236
+ const extraKeys = [];
2237
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
2238
+ for (const key in ctx.data) if (!shapeKeys.includes(key)) extraKeys.push(key);
2239
+ }
2240
+ const pairs = [];
2241
+ for (const key of shapeKeys) {
2242
+ const keyValidator = shape[key];
2243
+ const value = ctx.data[key];
2244
+ pairs.push({
2245
+ key: {
2246
+ status: "valid",
2247
+ value: key
2248
+ },
2249
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2250
+ alwaysSet: key in ctx.data
2251
+ });
2252
+ }
2253
+ if (this._def.catchall instanceof ZodNever) {
2254
+ const unknownKeys = this._def.unknownKeys;
2255
+ if (unknownKeys === "passthrough") for (const key of extraKeys) pairs.push({
2256
+ key: {
2257
+ status: "valid",
2258
+ value: key
2259
+ },
2260
+ value: {
2261
+ status: "valid",
2262
+ value: ctx.data[key]
2263
+ }
2264
+ });
2265
+ else if (unknownKeys === "strict") {
2266
+ if (extraKeys.length > 0) {
2267
+ addIssueToContext(ctx, {
2268
+ code: ZodIssueCode.unrecognized_keys,
2269
+ keys: extraKeys
2270
+ });
2271
+ status.dirty();
2272
+ }
2273
+ } else if (unknownKeys === "strip") {} else throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
2274
+ } else {
2275
+ const catchall = this._def.catchall;
2276
+ for (const key of extraKeys) {
2277
+ const value = ctx.data[key];
2278
+ pairs.push({
2279
+ key: {
2280
+ status: "valid",
2281
+ value: key
2282
+ },
2283
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
2284
+ alwaysSet: key in ctx.data
2285
+ });
2286
+ }
2287
+ }
2288
+ if (ctx.common.async) return Promise.resolve().then(async () => {
2289
+ const syncPairs = [];
2290
+ for (const pair of pairs) {
2291
+ const key = await pair.key;
2292
+ const value = await pair.value;
2293
+ syncPairs.push({
2294
+ key,
2295
+ value,
2296
+ alwaysSet: pair.alwaysSet
2297
+ });
2298
+ }
2299
+ return syncPairs;
2300
+ }).then((syncPairs) => {
2301
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2302
+ });
2303
+ else return ParseStatus.mergeObjectSync(status, pairs);
2304
+ }
2305
+ get shape() {
2306
+ return this._def.shape();
2307
+ }
2308
+ strict(message) {
2309
+ errorUtil.errToObj;
2310
+ return new ZodObject({
2311
+ ...this._def,
2312
+ unknownKeys: "strict",
2313
+ ...message !== void 0 ? { errorMap: (issue, ctx) => {
2314
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
2315
+ if (issue.code === "unrecognized_keys") return { message: errorUtil.errToObj(message).message ?? defaultError };
2316
+ return { message: defaultError };
2317
+ } } : {}
2318
+ });
2319
+ }
2320
+ strip() {
2321
+ return new ZodObject({
2322
+ ...this._def,
2323
+ unknownKeys: "strip"
2324
+ });
2325
+ }
2326
+ passthrough() {
2327
+ return new ZodObject({
2328
+ ...this._def,
2329
+ unknownKeys: "passthrough"
2330
+ });
2331
+ }
2332
+ extend(augmentation) {
2333
+ return new ZodObject({
2334
+ ...this._def,
2335
+ shape: () => ({
2336
+ ...this._def.shape(),
2337
+ ...augmentation
2338
+ })
2339
+ });
2340
+ }
2341
+ /**
2342
+ * Prior to zod@1.0.12 there was a bug in the
2343
+ * inferred type of merged objects. Please
2344
+ * upgrade if you are experiencing issues.
2345
+ */
2346
+ merge(merging) {
2347
+ const merged = new ZodObject({
2348
+ unknownKeys: merging._def.unknownKeys,
2349
+ catchall: merging._def.catchall,
2350
+ shape: () => ({
2351
+ ...this._def.shape(),
2352
+ ...merging._def.shape()
2353
+ }),
2354
+ typeName: ZodFirstPartyTypeKind.ZodObject
2355
+ });
2356
+ return merged;
2357
+ }
2358
+ setKey(key, schema) {
2359
+ return this.augment({ [key]: schema });
2360
+ }
2361
+ catchall(index) {
2362
+ return new ZodObject({
2363
+ ...this._def,
2364
+ catchall: index
2365
+ });
2366
+ }
2367
+ pick(mask) {
2368
+ const shape = {};
2369
+ for (const key of util.objectKeys(mask)) if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
2370
+ return new ZodObject({
2371
+ ...this._def,
2372
+ shape: () => shape
2373
+ });
2374
+ }
2375
+ omit(mask) {
2376
+ const shape = {};
2377
+ for (const key of util.objectKeys(this.shape)) if (!mask[key]) shape[key] = this.shape[key];
2378
+ return new ZodObject({
2379
+ ...this._def,
2380
+ shape: () => shape
2381
+ });
2382
+ }
2383
+ /**
2384
+ * @deprecated
2385
+ */
2386
+ deepPartial() {
2387
+ return deepPartialify(this);
2388
+ }
2389
+ partial(mask) {
2390
+ const newShape = {};
2391
+ for (const key of util.objectKeys(this.shape)) {
2392
+ const fieldSchema = this.shape[key];
2393
+ if (mask && !mask[key]) newShape[key] = fieldSchema;
2394
+ else newShape[key] = fieldSchema.optional();
2395
+ }
2396
+ return new ZodObject({
2397
+ ...this._def,
2398
+ shape: () => newShape
2399
+ });
2400
+ }
2401
+ required(mask) {
2402
+ const newShape = {};
2403
+ for (const key of util.objectKeys(this.shape)) if (mask && !mask[key]) newShape[key] = this.shape[key];
2404
+ else {
2405
+ const fieldSchema = this.shape[key];
2406
+ let newField = fieldSchema;
2407
+ while (newField instanceof ZodOptional) newField = newField._def.innerType;
2408
+ newShape[key] = newField;
2409
+ }
2410
+ return new ZodObject({
2411
+ ...this._def,
2412
+ shape: () => newShape
2413
+ });
2414
+ }
2415
+ keyof() {
2416
+ return createZodEnum(util.objectKeys(this.shape));
2417
+ }
2418
+ };
2419
+ ZodObject.create = (shape, params) => {
2420
+ return new ZodObject({
2421
+ shape: () => shape,
2422
+ unknownKeys: "strip",
2423
+ catchall: ZodNever.create(),
2424
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2425
+ ...processCreateParams(params)
2426
+ });
2427
+ };
2428
+ ZodObject.strictCreate = (shape, params) => {
2429
+ return new ZodObject({
2430
+ shape: () => shape,
2431
+ unknownKeys: "strict",
2432
+ catchall: ZodNever.create(),
2433
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2434
+ ...processCreateParams(params)
2435
+ });
2436
+ };
2437
+ ZodObject.lazycreate = (shape, params) => {
2438
+ return new ZodObject({
2439
+ shape,
2440
+ unknownKeys: "strip",
2441
+ catchall: ZodNever.create(),
2442
+ typeName: ZodFirstPartyTypeKind.ZodObject,
2443
+ ...processCreateParams(params)
2444
+ });
2445
+ };
2446
+ var ZodUnion = class extends ZodType {
2447
+ _parse(input) {
2448
+ const { ctx } = this._processInputParams(input);
2449
+ const options = this._def.options;
2450
+ function handleResults(results) {
2451
+ for (const result of results) if (result.result.status === "valid") return result.result;
2452
+ for (const result of results) if (result.result.status === "dirty") {
2453
+ ctx.common.issues.push(...result.ctx.common.issues);
2454
+ return result.result;
2455
+ }
2456
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
2457
+ addIssueToContext(ctx, {
2458
+ code: ZodIssueCode.invalid_union,
2459
+ unionErrors
2460
+ });
2461
+ return INVALID;
2462
+ }
2463
+ if (ctx.common.async) return Promise.all(options.map(async (option) => {
2464
+ const childCtx = {
2465
+ ...ctx,
2466
+ common: {
2467
+ ...ctx.common,
2468
+ issues: []
2469
+ },
2470
+ parent: null
2471
+ };
2472
+ return {
2473
+ result: await option._parseAsync({
2474
+ data: ctx.data,
2475
+ path: ctx.path,
2476
+ parent: childCtx
2477
+ }),
2478
+ ctx: childCtx
2479
+ };
2480
+ })).then(handleResults);
2481
+ else {
2482
+ let dirty = void 0;
2483
+ const issues = [];
2484
+ for (const option of options) {
2485
+ const childCtx = {
2486
+ ...ctx,
2487
+ common: {
2488
+ ...ctx.common,
2489
+ issues: []
2490
+ },
2491
+ parent: null
2492
+ };
2493
+ const result = option._parseSync({
2494
+ data: ctx.data,
2495
+ path: ctx.path,
2496
+ parent: childCtx
2497
+ });
2498
+ if (result.status === "valid") return result;
2499
+ else if (result.status === "dirty" && !dirty) dirty = {
2500
+ result,
2501
+ ctx: childCtx
2502
+ };
2503
+ if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
2504
+ }
2505
+ if (dirty) {
2506
+ ctx.common.issues.push(...dirty.ctx.common.issues);
2507
+ return dirty.result;
2508
+ }
2509
+ const unionErrors = issues.map((issues$1) => new ZodError(issues$1));
2510
+ addIssueToContext(ctx, {
2511
+ code: ZodIssueCode.invalid_union,
2512
+ unionErrors
2513
+ });
2514
+ return INVALID;
2515
+ }
2516
+ }
2517
+ get options() {
2518
+ return this._def.options;
2519
+ }
2520
+ };
2521
+ ZodUnion.create = (types, params) => {
2522
+ return new ZodUnion({
2523
+ options: types,
2524
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
2525
+ ...processCreateParams(params)
2526
+ });
2527
+ };
2528
+ const getDiscriminator = (type) => {
2529
+ if (type instanceof ZodLazy) return getDiscriminator(type.schema);
2530
+ else if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
2531
+ else if (type instanceof ZodLiteral) return [type.value];
2532
+ else if (type instanceof ZodEnum) return type.options;
2533
+ else if (type instanceof ZodNativeEnum) return util.objectValues(type.enum);
2534
+ else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
2535
+ else if (type instanceof ZodUndefined) return [void 0];
2536
+ else if (type instanceof ZodNull) return [null];
2537
+ else if (type instanceof ZodOptional) return [void 0, ...getDiscriminator(type.unwrap())];
2538
+ else if (type instanceof ZodNullable) return [null, ...getDiscriminator(type.unwrap())];
2539
+ else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
2540
+ else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
2541
+ else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
2542
+ else return [];
2543
+ };
2544
+ var ZodDiscriminatedUnion = class ZodDiscriminatedUnion extends ZodType {
2545
+ _parse(input) {
2546
+ const { ctx } = this._processInputParams(input);
2547
+ if (ctx.parsedType !== ZodParsedType.object) {
2548
+ addIssueToContext(ctx, {
2549
+ code: ZodIssueCode.invalid_type,
2550
+ expected: ZodParsedType.object,
2551
+ received: ctx.parsedType
2552
+ });
2553
+ return INVALID;
2554
+ }
2555
+ const discriminator = this.discriminator;
2556
+ const discriminatorValue = ctx.data[discriminator];
2557
+ const option = this.optionsMap.get(discriminatorValue);
2558
+ if (!option) {
2559
+ addIssueToContext(ctx, {
2560
+ code: ZodIssueCode.invalid_union_discriminator,
2561
+ options: Array.from(this.optionsMap.keys()),
2562
+ path: [discriminator]
2563
+ });
2564
+ return INVALID;
2565
+ }
2566
+ if (ctx.common.async) return option._parseAsync({
2567
+ data: ctx.data,
2568
+ path: ctx.path,
2569
+ parent: ctx
2570
+ });
2571
+ else return option._parseSync({
2572
+ data: ctx.data,
2573
+ path: ctx.path,
2574
+ parent: ctx
2575
+ });
2576
+ }
2577
+ get discriminator() {
2578
+ return this._def.discriminator;
2579
+ }
2580
+ get options() {
2581
+ return this._def.options;
2582
+ }
2583
+ get optionsMap() {
2584
+ return this._def.optionsMap;
2585
+ }
2586
+ /**
2587
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
2588
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
2589
+ * have a different value for each object in the union.
2590
+ * @param discriminator the name of the discriminator property
2591
+ * @param types an array of object schemas
2592
+ * @param params
2593
+ */
2594
+ static create(discriminator, options, params) {
2595
+ const optionsMap = /* @__PURE__ */ new Map();
2596
+ for (const type of options) {
2597
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
2598
+ if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
2599
+ for (const value of discriminatorValues) {
2600
+ if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
2601
+ optionsMap.set(value, type);
2602
+ }
2603
+ }
2604
+ return new ZodDiscriminatedUnion({
2605
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
2606
+ discriminator,
2607
+ options,
2608
+ optionsMap,
2609
+ ...processCreateParams(params)
2610
+ });
2611
+ }
2612
+ };
2613
+ function mergeValues(a, b) {
2614
+ const aType = getParsedType(a);
2615
+ const bType = getParsedType(b);
2616
+ if (a === b) return {
2617
+ valid: true,
2618
+ data: a
2619
+ };
2620
+ else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
2621
+ const bKeys = util.objectKeys(b);
2622
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
2623
+ const newObj = {
2624
+ ...a,
2625
+ ...b
2626
+ };
2627
+ for (const key of sharedKeys) {
2628
+ const sharedValue = mergeValues(a[key], b[key]);
2629
+ if (!sharedValue.valid) return { valid: false };
2630
+ newObj[key] = sharedValue.data;
2631
+ }
2632
+ return {
2633
+ valid: true,
2634
+ data: newObj
2635
+ };
2636
+ } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
2637
+ if (a.length !== b.length) return { valid: false };
2638
+ const newArray = [];
2639
+ for (let index = 0; index < a.length; index++) {
2640
+ const itemA = a[index];
2641
+ const itemB = b[index];
2642
+ const sharedValue = mergeValues(itemA, itemB);
2643
+ if (!sharedValue.valid) return { valid: false };
2644
+ newArray.push(sharedValue.data);
2645
+ }
2646
+ return {
2647
+ valid: true,
2648
+ data: newArray
2649
+ };
2650
+ } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return {
2651
+ valid: true,
2652
+ data: a
2653
+ };
2654
+ else return { valid: false };
2655
+ }
2656
+ var ZodIntersection = class extends ZodType {
2657
+ _parse(input) {
2658
+ const { status, ctx } = this._processInputParams(input);
2659
+ const handleParsed = (parsedLeft, parsedRight) => {
2660
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) return INVALID;
2661
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
2662
+ if (!merged.valid) {
2663
+ addIssueToContext(ctx, { code: ZodIssueCode.invalid_intersection_types });
2664
+ return INVALID;
2665
+ }
2666
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty();
2667
+ return {
2668
+ status: status.value,
2669
+ value: merged.data
2670
+ };
2671
+ };
2672
+ if (ctx.common.async) return Promise.all([this._def.left._parseAsync({
2673
+ data: ctx.data,
2674
+ path: ctx.path,
2675
+ parent: ctx
2676
+ }), this._def.right._parseAsync({
2677
+ data: ctx.data,
2678
+ path: ctx.path,
2679
+ parent: ctx
2680
+ })]).then(([left, right]) => handleParsed(left, right));
2681
+ else return handleParsed(this._def.left._parseSync({
2682
+ data: ctx.data,
2683
+ path: ctx.path,
2684
+ parent: ctx
2685
+ }), this._def.right._parseSync({
2686
+ data: ctx.data,
2687
+ path: ctx.path,
2688
+ parent: ctx
2689
+ }));
2690
+ }
2691
+ };
2692
+ ZodIntersection.create = (left, right, params) => {
2693
+ return new ZodIntersection({
2694
+ left,
2695
+ right,
2696
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
2697
+ ...processCreateParams(params)
2698
+ });
2699
+ };
2700
+ var ZodTuple = class ZodTuple extends ZodType {
2701
+ _parse(input) {
2702
+ const { status, ctx } = this._processInputParams(input);
2703
+ if (ctx.parsedType !== ZodParsedType.array) {
2704
+ addIssueToContext(ctx, {
2705
+ code: ZodIssueCode.invalid_type,
2706
+ expected: ZodParsedType.array,
2707
+ received: ctx.parsedType
2708
+ });
2709
+ return INVALID;
2710
+ }
2711
+ if (ctx.data.length < this._def.items.length) {
2712
+ addIssueToContext(ctx, {
2713
+ code: ZodIssueCode.too_small,
2714
+ minimum: this._def.items.length,
2715
+ inclusive: true,
2716
+ exact: false,
2717
+ type: "array"
2718
+ });
2719
+ return INVALID;
2720
+ }
2721
+ const rest = this._def.rest;
2722
+ if (!rest && ctx.data.length > this._def.items.length) {
2723
+ addIssueToContext(ctx, {
2724
+ code: ZodIssueCode.too_big,
2725
+ maximum: this._def.items.length,
2726
+ inclusive: true,
2727
+ exact: false,
2728
+ type: "array"
2729
+ });
2730
+ status.dirty();
2731
+ }
2732
+ const items = [...ctx.data].map((item, itemIndex) => {
2733
+ const schema = this._def.items[itemIndex] || this._def.rest;
2734
+ if (!schema) return null;
2735
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
2736
+ }).filter((x) => !!x);
2737
+ if (ctx.common.async) return Promise.all(items).then((results) => {
2738
+ return ParseStatus.mergeArray(status, results);
2739
+ });
2740
+ else return ParseStatus.mergeArray(status, items);
2741
+ }
2742
+ get items() {
2743
+ return this._def.items;
2744
+ }
2745
+ rest(rest) {
2746
+ return new ZodTuple({
2747
+ ...this._def,
2748
+ rest
2749
+ });
2750
+ }
2751
+ };
2752
+ ZodTuple.create = (schemas, params) => {
2753
+ if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
2754
+ return new ZodTuple({
2755
+ items: schemas,
2756
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
2757
+ rest: null,
2758
+ ...processCreateParams(params)
2759
+ });
2760
+ };
2761
+ var ZodRecord = class ZodRecord extends ZodType {
2762
+ get keySchema() {
2763
+ return this._def.keyType;
2764
+ }
2765
+ get valueSchema() {
2766
+ return this._def.valueType;
2767
+ }
2768
+ _parse(input) {
2769
+ const { status, ctx } = this._processInputParams(input);
2770
+ if (ctx.parsedType !== ZodParsedType.object) {
2771
+ addIssueToContext(ctx, {
2772
+ code: ZodIssueCode.invalid_type,
2773
+ expected: ZodParsedType.object,
2774
+ received: ctx.parsedType
2775
+ });
2776
+ return INVALID;
2777
+ }
2778
+ const pairs = [];
2779
+ const keyType = this._def.keyType;
2780
+ const valueType = this._def.valueType;
2781
+ for (const key in ctx.data) pairs.push({
2782
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
2783
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
2784
+ alwaysSet: key in ctx.data
2785
+ });
2786
+ if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs);
2787
+ else return ParseStatus.mergeObjectSync(status, pairs);
2788
+ }
2789
+ get element() {
2790
+ return this._def.valueType;
2791
+ }
2792
+ static create(first, second, third) {
2793
+ if (second instanceof ZodType) return new ZodRecord({
2794
+ keyType: first,
2795
+ valueType: second,
2796
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
2797
+ ...processCreateParams(third)
2798
+ });
2799
+ return new ZodRecord({
2800
+ keyType: ZodString.create(),
2801
+ valueType: first,
2802
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
2803
+ ...processCreateParams(second)
2804
+ });
2805
+ }
2806
+ };
2807
+ var ZodMap = class extends ZodType {
2808
+ get keySchema() {
2809
+ return this._def.keyType;
2810
+ }
2811
+ get valueSchema() {
2812
+ return this._def.valueType;
2813
+ }
2814
+ _parse(input) {
2815
+ const { status, ctx } = this._processInputParams(input);
2816
+ if (ctx.parsedType !== ZodParsedType.map) {
2817
+ addIssueToContext(ctx, {
2818
+ code: ZodIssueCode.invalid_type,
2819
+ expected: ZodParsedType.map,
2820
+ received: ctx.parsedType
2821
+ });
2822
+ return INVALID;
2823
+ }
2824
+ const keyType = this._def.keyType;
2825
+ const valueType = this._def.valueType;
2826
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
2827
+ return {
2828
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
2829
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
2830
+ };
2831
+ });
2832
+ if (ctx.common.async) {
2833
+ const finalMap = /* @__PURE__ */ new Map();
2834
+ return Promise.resolve().then(async () => {
2835
+ for (const pair of pairs) {
2836
+ const key = await pair.key;
2837
+ const value = await pair.value;
2838
+ if (key.status === "aborted" || value.status === "aborted") return INVALID;
2839
+ if (key.status === "dirty" || value.status === "dirty") status.dirty();
2840
+ finalMap.set(key.value, value.value);
2841
+ }
2842
+ return {
2843
+ status: status.value,
2844
+ value: finalMap
2845
+ };
2846
+ });
2847
+ } else {
2848
+ const finalMap = /* @__PURE__ */ new Map();
2849
+ for (const pair of pairs) {
2850
+ const key = pair.key;
2851
+ const value = pair.value;
2852
+ if (key.status === "aborted" || value.status === "aborted") return INVALID;
2853
+ if (key.status === "dirty" || value.status === "dirty") status.dirty();
2854
+ finalMap.set(key.value, value.value);
2855
+ }
2856
+ return {
2857
+ status: status.value,
2858
+ value: finalMap
2859
+ };
2860
+ }
2861
+ }
2862
+ };
2863
+ ZodMap.create = (keyType, valueType, params) => {
2864
+ return new ZodMap({
2865
+ valueType,
2866
+ keyType,
2867
+ typeName: ZodFirstPartyTypeKind.ZodMap,
2868
+ ...processCreateParams(params)
2869
+ });
2870
+ };
2871
+ var ZodSet = class ZodSet extends ZodType {
2872
+ _parse(input) {
2873
+ const { status, ctx } = this._processInputParams(input);
2874
+ if (ctx.parsedType !== ZodParsedType.set) {
2875
+ addIssueToContext(ctx, {
2876
+ code: ZodIssueCode.invalid_type,
2877
+ expected: ZodParsedType.set,
2878
+ received: ctx.parsedType
2879
+ });
2880
+ return INVALID;
2881
+ }
2882
+ const def = this._def;
2883
+ if (def.minSize !== null) {
2884
+ if (ctx.data.size < def.minSize.value) {
2885
+ addIssueToContext(ctx, {
2886
+ code: ZodIssueCode.too_small,
2887
+ minimum: def.minSize.value,
2888
+ type: "set",
2889
+ inclusive: true,
2890
+ exact: false,
2891
+ message: def.minSize.message
2892
+ });
2893
+ status.dirty();
2894
+ }
2895
+ }
2896
+ if (def.maxSize !== null) {
2897
+ if (ctx.data.size > def.maxSize.value) {
2898
+ addIssueToContext(ctx, {
2899
+ code: ZodIssueCode.too_big,
2900
+ maximum: def.maxSize.value,
2901
+ type: "set",
2902
+ inclusive: true,
2903
+ exact: false,
2904
+ message: def.maxSize.message
2905
+ });
2906
+ status.dirty();
2907
+ }
2908
+ }
2909
+ const valueType = this._def.valueType;
2910
+ function finalizeSet(elements$1) {
2911
+ const parsedSet = /* @__PURE__ */ new Set();
2912
+ for (const element of elements$1) {
2913
+ if (element.status === "aborted") return INVALID;
2914
+ if (element.status === "dirty") status.dirty();
2915
+ parsedSet.add(element.value);
2916
+ }
2917
+ return {
2918
+ status: status.value,
2919
+ value: parsedSet
2920
+ };
2921
+ }
2922
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
2923
+ if (ctx.common.async) return Promise.all(elements).then((elements$1) => finalizeSet(elements$1));
2924
+ else return finalizeSet(elements);
2925
+ }
2926
+ min(minSize, message) {
2927
+ return new ZodSet({
2928
+ ...this._def,
2929
+ minSize: {
2930
+ value: minSize,
2931
+ message: errorUtil.toString(message)
2932
+ }
2933
+ });
2934
+ }
2935
+ max(maxSize, message) {
2936
+ return new ZodSet({
2937
+ ...this._def,
2938
+ maxSize: {
2939
+ value: maxSize,
2940
+ message: errorUtil.toString(message)
2941
+ }
2942
+ });
2943
+ }
2944
+ size(size, message) {
2945
+ return this.min(size, message).max(size, message);
2946
+ }
2947
+ nonempty(message) {
2948
+ return this.min(1, message);
2949
+ }
2950
+ };
2951
+ ZodSet.create = (valueType, params) => {
2952
+ return new ZodSet({
2953
+ valueType,
2954
+ minSize: null,
2955
+ maxSize: null,
2956
+ typeName: ZodFirstPartyTypeKind.ZodSet,
2957
+ ...processCreateParams(params)
2958
+ });
2959
+ };
2960
+ var ZodFunction = class ZodFunction extends ZodType {
2961
+ constructor() {
2962
+ super(...arguments);
2963
+ this.validate = this.implement;
2964
+ }
2965
+ _parse(input) {
2966
+ const { ctx } = this._processInputParams(input);
2967
+ if (ctx.parsedType !== ZodParsedType.function) {
2968
+ addIssueToContext(ctx, {
2969
+ code: ZodIssueCode.invalid_type,
2970
+ expected: ZodParsedType.function,
2971
+ received: ctx.parsedType
2972
+ });
2973
+ return INVALID;
2974
+ }
2975
+ function makeArgsIssue(args, error) {
2976
+ return makeIssue({
2977
+ data: args,
2978
+ path: ctx.path,
2979
+ errorMaps: [
2980
+ ctx.common.contextualErrorMap,
2981
+ ctx.schemaErrorMap,
2982
+ getErrorMap(),
2983
+ en_default
2984
+ ].filter((x) => !!x),
2985
+ issueData: {
2986
+ code: ZodIssueCode.invalid_arguments,
2987
+ argumentsError: error
2988
+ }
2989
+ });
2990
+ }
2991
+ function makeReturnsIssue(returns, error) {
2992
+ return makeIssue({
2993
+ data: returns,
2994
+ path: ctx.path,
2995
+ errorMaps: [
2996
+ ctx.common.contextualErrorMap,
2997
+ ctx.schemaErrorMap,
2998
+ getErrorMap(),
2999
+ en_default
3000
+ ].filter((x) => !!x),
3001
+ issueData: {
3002
+ code: ZodIssueCode.invalid_return_type,
3003
+ returnTypeError: error
3004
+ }
3005
+ });
3006
+ }
3007
+ const params = { errorMap: ctx.common.contextualErrorMap };
3008
+ const fn = ctx.data;
3009
+ if (this._def.returns instanceof ZodPromise) {
3010
+ const me = this;
3011
+ return OK(async function(...args) {
3012
+ const error = new ZodError([]);
3013
+ const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {
3014
+ error.addIssue(makeArgsIssue(args, e));
3015
+ throw error;
3016
+ });
3017
+ const result = await Reflect.apply(fn, this, parsedArgs);
3018
+ const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e) => {
3019
+ error.addIssue(makeReturnsIssue(result, e));
3020
+ throw error;
3021
+ });
3022
+ return parsedReturns;
3023
+ });
3024
+ } else {
3025
+ const me = this;
3026
+ return OK(function(...args) {
3027
+ const parsedArgs = me._def.args.safeParse(args, params);
3028
+ if (!parsedArgs.success) throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
3029
+ const result = Reflect.apply(fn, this, parsedArgs.data);
3030
+ const parsedReturns = me._def.returns.safeParse(result, params);
3031
+ if (!parsedReturns.success) throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
3032
+ return parsedReturns.data;
3033
+ });
3034
+ }
3035
+ }
3036
+ parameters() {
3037
+ return this._def.args;
3038
+ }
3039
+ returnType() {
3040
+ return this._def.returns;
3041
+ }
3042
+ args(...items) {
3043
+ return new ZodFunction({
3044
+ ...this._def,
3045
+ args: ZodTuple.create(items).rest(ZodUnknown.create())
3046
+ });
3047
+ }
3048
+ returns(returnType) {
3049
+ return new ZodFunction({
3050
+ ...this._def,
3051
+ returns: returnType
3052
+ });
3053
+ }
3054
+ implement(func) {
3055
+ const validatedFunc = this.parse(func);
3056
+ return validatedFunc;
3057
+ }
3058
+ strictImplement(func) {
3059
+ const validatedFunc = this.parse(func);
3060
+ return validatedFunc;
3061
+ }
3062
+ static create(args, returns, params) {
3063
+ return new ZodFunction({
3064
+ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
3065
+ returns: returns || ZodUnknown.create(),
3066
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
3067
+ ...processCreateParams(params)
3068
+ });
3069
+ }
3070
+ };
3071
+ var ZodLazy = class extends ZodType {
3072
+ get schema() {
3073
+ return this._def.getter();
3074
+ }
3075
+ _parse(input) {
3076
+ const { ctx } = this._processInputParams(input);
3077
+ const lazySchema = this._def.getter();
3078
+ return lazySchema._parse({
3079
+ data: ctx.data,
3080
+ path: ctx.path,
3081
+ parent: ctx
3082
+ });
3083
+ }
3084
+ };
3085
+ ZodLazy.create = (getter, params) => {
3086
+ return new ZodLazy({
3087
+ getter,
3088
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
3089
+ ...processCreateParams(params)
3090
+ });
3091
+ };
3092
+ var ZodLiteral = class extends ZodType {
3093
+ _parse(input) {
3094
+ if (input.data !== this._def.value) {
3095
+ const ctx = this._getOrReturnCtx(input);
3096
+ addIssueToContext(ctx, {
3097
+ received: ctx.data,
3098
+ code: ZodIssueCode.invalid_literal,
3099
+ expected: this._def.value
3100
+ });
3101
+ return INVALID;
3102
+ }
3103
+ return {
3104
+ status: "valid",
3105
+ value: input.data
3106
+ };
3107
+ }
3108
+ get value() {
3109
+ return this._def.value;
3110
+ }
3111
+ };
3112
+ ZodLiteral.create = (value, params) => {
3113
+ return new ZodLiteral({
3114
+ value,
3115
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
3116
+ ...processCreateParams(params)
3117
+ });
3118
+ };
3119
+ function createZodEnum(values, params) {
3120
+ return new ZodEnum({
3121
+ values,
3122
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
3123
+ ...processCreateParams(params)
3124
+ });
3125
+ }
3126
+ var ZodEnum = class ZodEnum extends ZodType {
3127
+ _parse(input) {
3128
+ if (typeof input.data !== "string") {
3129
+ const ctx = this._getOrReturnCtx(input);
3130
+ const expectedValues = this._def.values;
3131
+ addIssueToContext(ctx, {
3132
+ expected: util.joinValues(expectedValues),
3133
+ received: ctx.parsedType,
3134
+ code: ZodIssueCode.invalid_type
3135
+ });
3136
+ return INVALID;
3137
+ }
3138
+ if (!this._cache) this._cache = new Set(this._def.values);
3139
+ if (!this._cache.has(input.data)) {
3140
+ const ctx = this._getOrReturnCtx(input);
3141
+ const expectedValues = this._def.values;
3142
+ addIssueToContext(ctx, {
3143
+ received: ctx.data,
3144
+ code: ZodIssueCode.invalid_enum_value,
3145
+ options: expectedValues
3146
+ });
3147
+ return INVALID;
3148
+ }
3149
+ return OK(input.data);
3150
+ }
3151
+ get options() {
3152
+ return this._def.values;
3153
+ }
3154
+ get enum() {
3155
+ const enumValues = {};
3156
+ for (const val of this._def.values) enumValues[val] = val;
3157
+ return enumValues;
3158
+ }
3159
+ get Values() {
3160
+ const enumValues = {};
3161
+ for (const val of this._def.values) enumValues[val] = val;
3162
+ return enumValues;
3163
+ }
3164
+ get Enum() {
3165
+ const enumValues = {};
3166
+ for (const val of this._def.values) enumValues[val] = val;
3167
+ return enumValues;
3168
+ }
3169
+ extract(values, newDef = this._def) {
3170
+ return ZodEnum.create(values, {
3171
+ ...this._def,
3172
+ ...newDef
3173
+ });
3174
+ }
3175
+ exclude(values, newDef = this._def) {
3176
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
3177
+ ...this._def,
3178
+ ...newDef
3179
+ });
3180
+ }
3181
+ };
3182
+ ZodEnum.create = createZodEnum;
3183
+ var ZodNativeEnum = class extends ZodType {
3184
+ _parse(input) {
3185
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
3186
+ const ctx = this._getOrReturnCtx(input);
3187
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
3188
+ const expectedValues = util.objectValues(nativeEnumValues);
3189
+ addIssueToContext(ctx, {
3190
+ expected: util.joinValues(expectedValues),
3191
+ received: ctx.parsedType,
3192
+ code: ZodIssueCode.invalid_type
3193
+ });
3194
+ return INVALID;
3195
+ }
3196
+ if (!this._cache) this._cache = new Set(util.getValidEnumValues(this._def.values));
3197
+ if (!this._cache.has(input.data)) {
3198
+ const expectedValues = util.objectValues(nativeEnumValues);
3199
+ addIssueToContext(ctx, {
3200
+ received: ctx.data,
3201
+ code: ZodIssueCode.invalid_enum_value,
3202
+ options: expectedValues
3203
+ });
3204
+ return INVALID;
3205
+ }
3206
+ return OK(input.data);
3207
+ }
3208
+ get enum() {
3209
+ return this._def.values;
3210
+ }
3211
+ };
3212
+ ZodNativeEnum.create = (values, params) => {
3213
+ return new ZodNativeEnum({
3214
+ values,
3215
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
3216
+ ...processCreateParams(params)
3217
+ });
3218
+ };
3219
+ var ZodPromise = class extends ZodType {
3220
+ unwrap() {
3221
+ return this._def.type;
3222
+ }
3223
+ _parse(input) {
3224
+ const { ctx } = this._processInputParams(input);
3225
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
3226
+ addIssueToContext(ctx, {
3227
+ code: ZodIssueCode.invalid_type,
3228
+ expected: ZodParsedType.promise,
3229
+ received: ctx.parsedType
3230
+ });
3231
+ return INVALID;
3232
+ }
3233
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
3234
+ return OK(promisified.then((data) => {
3235
+ return this._def.type.parseAsync(data, {
3236
+ path: ctx.path,
3237
+ errorMap: ctx.common.contextualErrorMap
3238
+ });
3239
+ }));
3240
+ }
3241
+ };
3242
+ ZodPromise.create = (schema, params) => {
3243
+ return new ZodPromise({
3244
+ type: schema,
3245
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
3246
+ ...processCreateParams(params)
3247
+ });
3248
+ };
3249
+ var ZodEffects = class extends ZodType {
3250
+ innerType() {
3251
+ return this._def.schema;
3252
+ }
3253
+ sourceType() {
3254
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
3255
+ }
3256
+ _parse(input) {
3257
+ const { status, ctx } = this._processInputParams(input);
3258
+ const effect = this._def.effect || null;
3259
+ const checkCtx = {
3260
+ addIssue: (arg) => {
3261
+ addIssueToContext(ctx, arg);
3262
+ if (arg.fatal) status.abort();
3263
+ else status.dirty();
3264
+ },
3265
+ get path() {
3266
+ return ctx.path;
3267
+ }
3268
+ };
3269
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3270
+ if (effect.type === "preprocess") {
3271
+ const processed = effect.transform(ctx.data, checkCtx);
3272
+ if (ctx.common.async) return Promise.resolve(processed).then(async (processed$1) => {
3273
+ if (status.value === "aborted") return INVALID;
3274
+ const result = await this._def.schema._parseAsync({
3275
+ data: processed$1,
3276
+ path: ctx.path,
3277
+ parent: ctx
3278
+ });
3279
+ if (result.status === "aborted") return INVALID;
3280
+ if (result.status === "dirty") return DIRTY(result.value);
3281
+ if (status.value === "dirty") return DIRTY(result.value);
3282
+ return result;
3283
+ });
3284
+ else {
3285
+ if (status.value === "aborted") return INVALID;
3286
+ const result = this._def.schema._parseSync({
3287
+ data: processed,
3288
+ path: ctx.path,
3289
+ parent: ctx
3290
+ });
3291
+ if (result.status === "aborted") return INVALID;
3292
+ if (result.status === "dirty") return DIRTY(result.value);
3293
+ if (status.value === "dirty") return DIRTY(result.value);
3294
+ return result;
3295
+ }
3296
+ }
3297
+ if (effect.type === "refinement") {
3298
+ const executeRefinement = (acc) => {
3299
+ const result = effect.refinement(acc, checkCtx);
3300
+ if (ctx.common.async) return Promise.resolve(result);
3301
+ if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
3302
+ return acc;
3303
+ };
3304
+ if (ctx.common.async === false) {
3305
+ const inner = this._def.schema._parseSync({
3306
+ data: ctx.data,
3307
+ path: ctx.path,
3308
+ parent: ctx
3309
+ });
3310
+ if (inner.status === "aborted") return INVALID;
3311
+ if (inner.status === "dirty") status.dirty();
3312
+ executeRefinement(inner.value);
3313
+ return {
3314
+ status: status.value,
3315
+ value: inner.value
3316
+ };
3317
+ } else return this._def.schema._parseAsync({
3318
+ data: ctx.data,
3319
+ path: ctx.path,
3320
+ parent: ctx
3321
+ }).then((inner) => {
3322
+ if (inner.status === "aborted") return INVALID;
3323
+ if (inner.status === "dirty") status.dirty();
3324
+ return executeRefinement(inner.value).then(() => {
3325
+ return {
3326
+ status: status.value,
3327
+ value: inner.value
3328
+ };
3329
+ });
3330
+ });
3331
+ }
3332
+ if (effect.type === "transform") if (ctx.common.async === false) {
3333
+ const base = this._def.schema._parseSync({
3334
+ data: ctx.data,
3335
+ path: ctx.path,
3336
+ parent: ctx
3337
+ });
3338
+ if (!isValid(base)) return INVALID;
3339
+ const result = effect.transform(base.value, checkCtx);
3340
+ if (result instanceof Promise) throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
3341
+ return {
3342
+ status: status.value,
3343
+ value: result
3344
+ };
3345
+ } else return this._def.schema._parseAsync({
3346
+ data: ctx.data,
3347
+ path: ctx.path,
3348
+ parent: ctx
3349
+ }).then((base) => {
3350
+ if (!isValid(base)) return INVALID;
3351
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
3352
+ status: status.value,
3353
+ value: result
3354
+ }));
3355
+ });
3356
+ util.assertNever(effect);
3357
+ }
3358
+ };
3359
+ ZodEffects.create = (schema, effect, params) => {
3360
+ return new ZodEffects({
3361
+ schema,
3362
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3363
+ effect,
3364
+ ...processCreateParams(params)
3365
+ });
3366
+ };
3367
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
3368
+ return new ZodEffects({
3369
+ schema,
3370
+ effect: {
3371
+ type: "preprocess",
3372
+ transform: preprocess
3373
+ },
3374
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
3375
+ ...processCreateParams(params)
3376
+ });
3377
+ };
3378
+ var ZodOptional = class extends ZodType {
3379
+ _parse(input) {
3380
+ const parsedType = this._getType(input);
3381
+ if (parsedType === ZodParsedType.undefined) return OK(void 0);
3382
+ return this._def.innerType._parse(input);
3383
+ }
3384
+ unwrap() {
3385
+ return this._def.innerType;
3386
+ }
3387
+ };
3388
+ ZodOptional.create = (type, params) => {
3389
+ return new ZodOptional({
3390
+ innerType: type,
3391
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
3392
+ ...processCreateParams(params)
3393
+ });
3394
+ };
3395
+ var ZodNullable = class extends ZodType {
3396
+ _parse(input) {
3397
+ const parsedType = this._getType(input);
3398
+ if (parsedType === ZodParsedType.null) return OK(null);
3399
+ return this._def.innerType._parse(input);
3400
+ }
3401
+ unwrap() {
3402
+ return this._def.innerType;
3403
+ }
3404
+ };
3405
+ ZodNullable.create = (type, params) => {
3406
+ return new ZodNullable({
3407
+ innerType: type,
3408
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
3409
+ ...processCreateParams(params)
3410
+ });
3411
+ };
3412
+ var ZodDefault = class extends ZodType {
3413
+ _parse(input) {
3414
+ const { ctx } = this._processInputParams(input);
3415
+ let data = ctx.data;
3416
+ if (ctx.parsedType === ZodParsedType.undefined) data = this._def.defaultValue();
3417
+ return this._def.innerType._parse({
3418
+ data,
3419
+ path: ctx.path,
3420
+ parent: ctx
3421
+ });
3422
+ }
3423
+ removeDefault() {
3424
+ return this._def.innerType;
3425
+ }
3426
+ };
3427
+ ZodDefault.create = (type, params) => {
3428
+ return new ZodDefault({
3429
+ innerType: type,
3430
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
3431
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
3432
+ ...processCreateParams(params)
3433
+ });
3434
+ };
3435
+ var ZodCatch = class extends ZodType {
3436
+ _parse(input) {
3437
+ const { ctx } = this._processInputParams(input);
3438
+ const newCtx = {
3439
+ ...ctx,
3440
+ common: {
3441
+ ...ctx.common,
3442
+ issues: []
3443
+ }
3444
+ };
3445
+ const result = this._def.innerType._parse({
3446
+ data: newCtx.data,
3447
+ path: newCtx.path,
3448
+ parent: { ...newCtx }
3449
+ });
3450
+ if (isAsync(result)) return result.then((result$1) => {
3451
+ return {
3452
+ status: "valid",
3453
+ value: result$1.status === "valid" ? result$1.value : this._def.catchValue({
3454
+ get error() {
3455
+ return new ZodError(newCtx.common.issues);
3456
+ },
3457
+ input: newCtx.data
3458
+ })
3459
+ };
3460
+ });
3461
+ else return {
3462
+ status: "valid",
3463
+ value: result.status === "valid" ? result.value : this._def.catchValue({
3464
+ get error() {
3465
+ return new ZodError(newCtx.common.issues);
3466
+ },
3467
+ input: newCtx.data
3468
+ })
3469
+ };
3470
+ }
3471
+ removeCatch() {
3472
+ return this._def.innerType;
3473
+ }
3474
+ };
3475
+ ZodCatch.create = (type, params) => {
3476
+ return new ZodCatch({
3477
+ innerType: type,
3478
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
3479
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
3480
+ ...processCreateParams(params)
3481
+ });
3482
+ };
3483
+ var ZodNaN = class extends ZodType {
3484
+ _parse(input) {
3485
+ const parsedType = this._getType(input);
3486
+ if (parsedType !== ZodParsedType.nan) {
3487
+ const ctx = this._getOrReturnCtx(input);
3488
+ addIssueToContext(ctx, {
3489
+ code: ZodIssueCode.invalid_type,
3490
+ expected: ZodParsedType.nan,
3491
+ received: ctx.parsedType
3492
+ });
3493
+ return INVALID;
3494
+ }
3495
+ return {
3496
+ status: "valid",
3497
+ value: input.data
3498
+ };
3499
+ }
3500
+ };
3501
+ ZodNaN.create = (params) => {
3502
+ return new ZodNaN({
3503
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
3504
+ ...processCreateParams(params)
3505
+ });
3506
+ };
3507
+ const BRAND = Symbol("zod_brand");
3508
+ var ZodBranded = class extends ZodType {
3509
+ _parse(input) {
3510
+ const { ctx } = this._processInputParams(input);
3511
+ const data = ctx.data;
3512
+ return this._def.type._parse({
3513
+ data,
3514
+ path: ctx.path,
3515
+ parent: ctx
3516
+ });
3517
+ }
3518
+ unwrap() {
3519
+ return this._def.type;
3520
+ }
3521
+ };
3522
+ var ZodPipeline = class ZodPipeline extends ZodType {
3523
+ _parse(input) {
3524
+ const { status, ctx } = this._processInputParams(input);
3525
+ if (ctx.common.async) {
3526
+ const handleAsync = async () => {
3527
+ const inResult = await this._def.in._parseAsync({
3528
+ data: ctx.data,
3529
+ path: ctx.path,
3530
+ parent: ctx
3531
+ });
3532
+ if (inResult.status === "aborted") return INVALID;
3533
+ if (inResult.status === "dirty") {
3534
+ status.dirty();
3535
+ return DIRTY(inResult.value);
3536
+ } else return this._def.out._parseAsync({
3537
+ data: inResult.value,
3538
+ path: ctx.path,
3539
+ parent: ctx
3540
+ });
3541
+ };
3542
+ return handleAsync();
3543
+ } else {
3544
+ const inResult = this._def.in._parseSync({
3545
+ data: ctx.data,
3546
+ path: ctx.path,
3547
+ parent: ctx
3548
+ });
3549
+ if (inResult.status === "aborted") return INVALID;
3550
+ if (inResult.status === "dirty") {
3551
+ status.dirty();
3552
+ return {
3553
+ status: "dirty",
3554
+ value: inResult.value
3555
+ };
3556
+ } else return this._def.out._parseSync({
3557
+ data: inResult.value,
3558
+ path: ctx.path,
3559
+ parent: ctx
3560
+ });
3561
+ }
3562
+ }
3563
+ static create(a, b) {
3564
+ return new ZodPipeline({
3565
+ in: a,
3566
+ out: b,
3567
+ typeName: ZodFirstPartyTypeKind.ZodPipeline
3568
+ });
3569
+ }
3570
+ };
3571
+ var ZodReadonly = class extends ZodType {
3572
+ _parse(input) {
3573
+ const result = this._def.innerType._parse(input);
3574
+ const freeze = (data) => {
3575
+ if (isValid(data)) data.value = Object.freeze(data.value);
3576
+ return data;
3577
+ };
3578
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
3579
+ }
3580
+ unwrap() {
3581
+ return this._def.innerType;
3582
+ }
3583
+ };
3584
+ ZodReadonly.create = (type, params) => {
3585
+ return new ZodReadonly({
3586
+ innerType: type,
3587
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
3588
+ ...processCreateParams(params)
3589
+ });
3590
+ };
3591
+ const late = { object: ZodObject.lazycreate };
3592
+ var ZodFirstPartyTypeKind;
3593
+ (function(ZodFirstPartyTypeKind$1) {
3594
+ ZodFirstPartyTypeKind$1["ZodString"] = "ZodString";
3595
+ ZodFirstPartyTypeKind$1["ZodNumber"] = "ZodNumber";
3596
+ ZodFirstPartyTypeKind$1["ZodNaN"] = "ZodNaN";
3597
+ ZodFirstPartyTypeKind$1["ZodBigInt"] = "ZodBigInt";
3598
+ ZodFirstPartyTypeKind$1["ZodBoolean"] = "ZodBoolean";
3599
+ ZodFirstPartyTypeKind$1["ZodDate"] = "ZodDate";
3600
+ ZodFirstPartyTypeKind$1["ZodSymbol"] = "ZodSymbol";
3601
+ ZodFirstPartyTypeKind$1["ZodUndefined"] = "ZodUndefined";
3602
+ ZodFirstPartyTypeKind$1["ZodNull"] = "ZodNull";
3603
+ ZodFirstPartyTypeKind$1["ZodAny"] = "ZodAny";
3604
+ ZodFirstPartyTypeKind$1["ZodUnknown"] = "ZodUnknown";
3605
+ ZodFirstPartyTypeKind$1["ZodNever"] = "ZodNever";
3606
+ ZodFirstPartyTypeKind$1["ZodVoid"] = "ZodVoid";
3607
+ ZodFirstPartyTypeKind$1["ZodArray"] = "ZodArray";
3608
+ ZodFirstPartyTypeKind$1["ZodObject"] = "ZodObject";
3609
+ ZodFirstPartyTypeKind$1["ZodUnion"] = "ZodUnion";
3610
+ ZodFirstPartyTypeKind$1["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
3611
+ ZodFirstPartyTypeKind$1["ZodIntersection"] = "ZodIntersection";
3612
+ ZodFirstPartyTypeKind$1["ZodTuple"] = "ZodTuple";
3613
+ ZodFirstPartyTypeKind$1["ZodRecord"] = "ZodRecord";
3614
+ ZodFirstPartyTypeKind$1["ZodMap"] = "ZodMap";
3615
+ ZodFirstPartyTypeKind$1["ZodSet"] = "ZodSet";
3616
+ ZodFirstPartyTypeKind$1["ZodFunction"] = "ZodFunction";
3617
+ ZodFirstPartyTypeKind$1["ZodLazy"] = "ZodLazy";
3618
+ ZodFirstPartyTypeKind$1["ZodLiteral"] = "ZodLiteral";
3619
+ ZodFirstPartyTypeKind$1["ZodEnum"] = "ZodEnum";
3620
+ ZodFirstPartyTypeKind$1["ZodEffects"] = "ZodEffects";
3621
+ ZodFirstPartyTypeKind$1["ZodNativeEnum"] = "ZodNativeEnum";
3622
+ ZodFirstPartyTypeKind$1["ZodOptional"] = "ZodOptional";
3623
+ ZodFirstPartyTypeKind$1["ZodNullable"] = "ZodNullable";
3624
+ ZodFirstPartyTypeKind$1["ZodDefault"] = "ZodDefault";
3625
+ ZodFirstPartyTypeKind$1["ZodCatch"] = "ZodCatch";
3626
+ ZodFirstPartyTypeKind$1["ZodPromise"] = "ZodPromise";
3627
+ ZodFirstPartyTypeKind$1["ZodBranded"] = "ZodBranded";
3628
+ ZodFirstPartyTypeKind$1["ZodPipeline"] = "ZodPipeline";
3629
+ ZodFirstPartyTypeKind$1["ZodReadonly"] = "ZodReadonly";
3630
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
3631
+ const stringType = ZodString.create;
3632
+ const numberType = ZodNumber.create;
3633
+ const nanType = ZodNaN.create;
3634
+ const bigIntType = ZodBigInt.create;
3635
+ const booleanType = ZodBoolean.create;
3636
+ const dateType = ZodDate.create;
3637
+ const symbolType = ZodSymbol.create;
3638
+ const undefinedType = ZodUndefined.create;
3639
+ const nullType = ZodNull.create;
3640
+ const anyType = ZodAny.create;
3641
+ const unknownType = ZodUnknown.create;
3642
+ const neverType = ZodNever.create;
3643
+ const voidType = ZodVoid.create;
3644
+ const arrayType = ZodArray.create;
3645
+ const objectType = ZodObject.create;
3646
+ const strictObjectType = ZodObject.strictCreate;
3647
+ const unionType = ZodUnion.create;
3648
+ const discriminatedUnionType = ZodDiscriminatedUnion.create;
3649
+ const intersectionType = ZodIntersection.create;
3650
+ const tupleType = ZodTuple.create;
3651
+ const recordType = ZodRecord.create;
3652
+ const mapType = ZodMap.create;
3653
+ const setType = ZodSet.create;
3654
+ const functionType = ZodFunction.create;
3655
+ const lazyType = ZodLazy.create;
3656
+ const literalType = ZodLiteral.create;
3657
+ const enumType = ZodEnum.create;
3658
+ const nativeEnumType = ZodNativeEnum.create;
3659
+ const promiseType = ZodPromise.create;
3660
+ const effectsType = ZodEffects.create;
3661
+ const optionalType = ZodOptional.create;
3662
+ const nullableType = ZodNullable.create;
3663
+ const preprocessType = ZodEffects.createWithPreprocess;
3664
+ const pipelineType = ZodPipeline.create;
3665
+
3666
+ //#endregion
3667
+ //#region src/connectors/constants.ts
3668
+ const DEFAULT_PAGE_SIZE = 25;
3669
+
3670
+ //#endregion
3671
+ //#region src/connectors/responses.ts
3672
+ const getDefaultSuccessOperationResponse = (operationType) => {
3673
+ switch (operationType) {
3674
+ case "list": return {
3675
+ statusCode: 200,
3676
+ description: "The list of records was retrieved."
3677
+ };
3678
+ case "get": return {
3679
+ statusCode: 200,
3680
+ description: "The record with the given identifier was retrieved."
3681
+ };
3682
+ case "create": return {
3683
+ statusCode: 201,
3684
+ description: "The record was created successfully."
3685
+ };
3686
+ case "update": return {
3687
+ statusCode: 200,
3688
+ description: "The record was updated successfully."
3689
+ };
3690
+ case "delete": return {
3691
+ statusCode: 204,
3692
+ description: "The record was deleted successfully."
3693
+ };
3694
+ case "custom": return {
3695
+ statusCode: 200,
3696
+ description: "The operation was executed successfully."
3697
+ };
3698
+ case "unknown": return { statusCode: 200 };
3699
+ default: throw new Error(`Unknown operation type: ${operationType}`);
3700
+ }
3701
+ };
3702
+ const getDefaultErrorOperationResponses = () => {
3703
+ const defaultErrorStatusCodes = {
3704
+ 400: {
3705
+ statusCode: 400,
3706
+ description: "Invalid request."
3707
+ },
3708
+ 401: {
3709
+ statusCode: 401,
3710
+ description: "Unauthorized access."
3711
+ },
3712
+ 403: {
3713
+ statusCode: 403,
3714
+ description: "Forbidden."
3715
+ },
3716
+ 404: {
3717
+ statusCode: 404,
3718
+ description: "Resource not found."
3719
+ },
3720
+ 500: {
3721
+ statusCode: 500,
3722
+ description: "Server error while executing the request."
3723
+ }
3724
+ };
3725
+ return defaultErrorStatusCodes;
3726
+ };
3727
+
3728
+ //#endregion
3729
+ //#region src/connectors/schemas.ts
3730
+ const BASE_AUTH_FIELD = {
3731
+ key: stringType(),
3732
+ label: stringType(),
3733
+ required: booleanType().optional().default(false),
3734
+ secret: booleanType().optional().default(false),
3735
+ readOnly: booleanType().optional().default(false),
3736
+ placeholder: stringType().optional(),
3737
+ description: stringType().optional(),
3738
+ tooltip: stringType().optional()
3739
+ };
3740
+ const AUTHENTICATION_FIELD_SCHEMA = discriminatedUnionType("type", [objectType({
3741
+ ...BASE_AUTH_FIELD,
3742
+ type: enumType(["text", "password"])
3743
+ }), objectType({
3744
+ ...BASE_AUTH_FIELD,
3745
+ type: literalType("select"),
3746
+ options: objectType({
3747
+ value: stringType(),
3748
+ label: stringType()
3749
+ }).array()
3750
+ })]);
3751
+ const OPERATION_SCHEMA = objectType({
3752
+ operationId: stringType(),
3753
+ categories: stringType().array(),
3754
+ operationType: enumType([
3755
+ "list",
3756
+ "get",
3757
+ "create",
3758
+ "update",
3759
+ "delete",
3760
+ "custom",
3761
+ "unknown"
3762
+ ]),
3763
+ schema: stringType().optional(),
3764
+ entrypointUrl: stringType().optional(),
3765
+ entrypointHttpMethod: stringType().optional(),
3766
+ description: stringType(),
3767
+ responses: objectType({
3768
+ statusCode: numberType(),
3769
+ description: stringType()
3770
+ }).array().optional(),
3771
+ inputs: objectType({
3772
+ name: stringType(),
3773
+ type: stringType(),
3774
+ required: booleanType(),
3775
+ description: stringType(),
3776
+ in: stringType()
3777
+ }).array().optional(),
3778
+ cursor: objectType({
3779
+ enabled: booleanType(),
3780
+ pageSize: numberType()
3781
+ }).optional(),
3782
+ compositeIdentifiers: objectType({
3783
+ enabled: booleanType(),
3784
+ version: numberType().optional(),
3785
+ fields: objectType({
3786
+ targetFieldKey: stringType(),
3787
+ remote: stringType().optional(),
3788
+ components: stringType().array()
3789
+ }).array().optional()
3790
+ }).optional(),
3791
+ scheduledJobs: objectType({
3792
+ enabled: booleanType(),
3793
+ type: enumType(["data_sync"]),
3794
+ schedule: stringType(),
3795
+ description: stringType(),
3796
+ requestParams: objectType({
3797
+ fields: stringType().array().optional(),
3798
+ expand: stringType().array().optional(),
3799
+ filter: recordType(stringType(), stringType()).optional()
3800
+ }).optional(),
3801
+ syncFilter: objectType({
3802
+ name: enumType(["updated_after", "created_after"]),
3803
+ initialLoopbackPeriod: stringType(),
3804
+ incrementalLoopbackPeriod: stringType()
3805
+ }).optional()
3806
+ }).array().optional(),
3807
+ fieldConfigs: objectType({
3808
+ targetFieldKey: stringType(),
3809
+ alias: stringType().optional(),
3810
+ expression: stringType(),
3811
+ type: enumType([
3812
+ "string",
3813
+ "number",
3814
+ "boolean",
3815
+ "datetime_string",
3816
+ "enum"
3817
+ ]),
3818
+ custom: booleanType().default(false),
3819
+ hidden: booleanType().default(false),
3820
+ enumMapper: objectType({ matcher: enumType([
3821
+ "country_alpha2code_by_alpha2code",
3822
+ "country_alpha3code_by_alpha3code",
3823
+ "country_code_by_country_code",
3824
+ "country_name_by_country_name",
3825
+ "country_name_by_alpha3code",
3826
+ "country_name_by_alpha2code",
3827
+ "country_name_by_country_code",
3828
+ "country_alpha3code_by_alpha2code",
3829
+ "country_alpha3code_by_country_name",
3830
+ "country_alpha3code_by_country_code",
3831
+ "country_alpha2code_by_alpha3code",
3832
+ "country_alpha2code_by_country_name",
3833
+ "country_alpha2code_by_country_code",
3834
+ "country_code_by_alpha2code",
3835
+ "country_code_by_alpha3code",
3836
+ "country_code_by_country_name",
3837
+ "country_subdivisions_by_alpha2code",
3838
+ "country_subdivision_code_by_subdivision_name",
3839
+ "country_alpha2code_by_citizenship",
3840
+ "country_subdivision_name_by_subdivision_code"
3841
+ ]).or(objectType({
3842
+ matchExpression: stringType(),
3843
+ value: stringType()
3844
+ }).array()) }).optional()
3845
+ }).array().optional(),
3846
+ steps: objectType({
3847
+ stepId: stringType(),
3848
+ description: stringType(),
3849
+ stepFunction: objectType({
3850
+ functionName: stringType(),
3851
+ version: stringType().optional(),
3852
+ parameters: recordType(stringType(), unknownType())
3853
+ }),
3854
+ condition: stringType().optional(),
3855
+ ignoreError: booleanType().optional()
3856
+ }).array(),
3857
+ result: stringType().or(recordType(stringType(), unknownType())).optional()
3858
+ });
3859
+ const CONNECTOR_YAML_SCHEMA = objectType({
3860
+ StackOne: stringType(),
3861
+ info: objectType({
3862
+ title: stringType(),
3863
+ version: stringType(),
3864
+ key: stringType(),
3865
+ description: stringType().optional()
3866
+ }),
3867
+ baseUrl: stringType(),
3868
+ authentication: recordType(stringType(), objectType({
3869
+ type: stringType(),
3870
+ label: stringType(),
3871
+ authorization: __stackone_core.AUTHENTICATION_SCHEMA,
3872
+ environments: objectType({
3873
+ key: stringType(),
3874
+ name: stringType()
3875
+ }).array(),
3876
+ support: objectType({
3877
+ link: stringType(),
3878
+ description: stringType().optional()
3879
+ }),
3880
+ configFields: AUTHENTICATION_FIELD_SCHEMA.array().optional(),
3881
+ setupFields: AUTHENTICATION_FIELD_SCHEMA.array().optional(),
3882
+ testOperationsIds: stringType().array().optional()
3883
+ })).array().optional(),
3884
+ operations: OPERATION_SCHEMA.array().optional()
3885
+ });
3886
+
3887
+ //#endregion
3888
+ //#region src/connectors/parsers.ts
3889
+ function parseYamlConnector(yamlFileContents) {
3890
+ try {
3891
+ const yamlConnector = (0, yaml.parse)(yamlFileContents);
3892
+ const parsedYamlConnector = CONNECTOR_YAML_SCHEMA.parse(yamlConnector);
3893
+ const newJsonConnector = {
3894
+ title: parsedYamlConnector.info.title,
3895
+ version: parsedYamlConnector.info.version,
3896
+ key: parsedYamlConnector.info.key,
3897
+ description: parsedYamlConnector.info.description
3898
+ };
3899
+ const authentication = buildAuthenticationFromYaml(parsedYamlConnector);
3900
+ const baseRequestParams = {
3901
+ baseUrl: parsedYamlConnector.baseUrl,
3902
+ authentication: stripAuthenticationSetup(authentication)
3903
+ };
3904
+ const newOperations = buildOperationsFromYaml(parsedYamlConnector, baseRequestParams);
3905
+ newJsonConnector.operations = newOperations;
3906
+ newJsonConnector.authentication = authentication;
3907
+ if ((0, __stackone_utils.notMissing)(newOperations)) newJsonConnector.categories = getConnectorCategoriesFromOperations(Object.values(newOperations));
3908
+ return newJsonConnector;
3909
+ } catch (error) {
3910
+ throw new Error(`Error parsing YAML file: ${error.message}`);
3911
+ }
3912
+ }
3913
+ const stripAuthenticationSetup = (authentication) => {
3914
+ const result = {};
3915
+ for (const [key, value] of Object.entries(authentication)) if (value && typeof value === "object") {
3916
+ const { setupFields: _setupFields, configFields: _configFields, support: _support, testOperationsIds: _testOperationsIds,...rest } = value;
3917
+ result[key] = stripAuthenticationSetup(rest);
3918
+ } else result[key] = value;
3919
+ return result;
3920
+ };
3921
+ const getConnectorCategoriesFromOperations = (operations) => {
3922
+ const categoriesSet = operations.reduce((acc, op) => {
3923
+ for (const category of op.categories) acc.add(category);
3924
+ return acc;
3925
+ }, /* @__PURE__ */ new Set());
3926
+ return Array.from(categoriesSet);
3927
+ };
3928
+ const buildAuthenticationFromYaml = (parsedYamlConnector) => {
3929
+ const authentication = {};
3930
+ for (const auth of parsedYamlConnector.authentication ?? []) {
3931
+ const [authKey] = Object.keys(auth);
3932
+ const authConfig = auth[authKey].environments.reduce((acc, env) => {
3933
+ const { key, name } = env;
3934
+ const { environments: _envs,...authConfig$1 } = auth[authKey];
3935
+ acc[key] = {
3936
+ ...authConfig$1,
3937
+ envKey: key,
3938
+ envName: name
3939
+ };
3940
+ return acc;
3941
+ }, {});
3942
+ authentication[authKey] = authConfig;
3943
+ }
3944
+ return authentication;
3945
+ };
3946
+ const buildOperationKey = (op) => {
3947
+ return op.entrypointUrl && op.entrypointHttpMethod ? `${op.entrypointHttpMethod.toUpperCase()} ${op.entrypointUrl}` : void 0;
3948
+ };
3949
+ const inferOperationKey = (op) => {
3950
+ return op.operationType === "list" ? `GET /${op.schema}` : `GET /${op.schema}/:id`;
3951
+ };
3952
+ const inferEntrypointUrl = (op) => {
3953
+ return op.operationType === "list" ? `/${op.schema}` : `/${op.schema}/:id`;
3954
+ };
3955
+ const buildOperationResponses = (op) => {
3956
+ const defaultOperationResponses = {
3957
+ success: getDefaultSuccessOperationResponse(op.operationType),
3958
+ errors: getDefaultErrorOperationResponses()
3959
+ };
3960
+ const operationResponses = op.responses?.reduce((acc, response) => {
3961
+ const isSuccess = (0, __stackone_transport.isSuccessStatusCode)(response.statusCode);
3962
+ if (isSuccess) acc.success = {
3963
+ statusCode: response.statusCode,
3964
+ description: response.description
3965
+ };
3966
+ else acc.errors[response.statusCode] = {
3967
+ statusCode: response.statusCode,
3968
+ description: response.description
3969
+ };
3970
+ return acc;
3971
+ }, defaultOperationResponses);
3972
+ return operationResponses ?? defaultOperationResponses;
3973
+ };
3974
+ const buildOperationsFromYaml = (parsedYamlConnector, baseRequestParams) => {
3975
+ const newOperations = parsedYamlConnector.operations?.reduce((acc, op) => {
3976
+ const operationKey = buildOperationKey(op);
3977
+ const inferredOperationKey = inferOperationKey(op);
3978
+ const inferredEntrypointUrl = inferEntrypointUrl(op);
3979
+ const operationResponses = buildOperationResponses(op);
3980
+ const cursorConfig = buildCursorConfig(op);
3981
+ const inputs = op.inputs || [];
3982
+ if (cursorConfig.enabled) inputs?.push({
3983
+ type: "string",
3984
+ name: "page_size",
3985
+ in: "query",
3986
+ required: false,
3987
+ description: "Number of items to return per page"
3988
+ });
3989
+ acc[operationKey ?? inferredOperationKey] = {
3990
+ id: op.operationId,
3991
+ categories: op.categories,
3992
+ description: op.description,
3993
+ operationType: op.operationType,
3994
+ entrypointUrl: op.entrypointUrl ?? inferredEntrypointUrl,
3995
+ entrypointHttpMethod: op.entrypointHttpMethod ?? "get",
3996
+ responses: operationResponses,
3997
+ cursor: cursorConfig,
3998
+ compositeIdentifiers: parseCompositeIdentifiersConfig(op),
3999
+ scheduledJobs: parseScheduledJobConfig(op),
4000
+ inputs,
4001
+ steps: op.steps.reduce((acc$1, step) => {
4002
+ acc$1[step.stepId] = {
4003
+ id: step.stepId,
4004
+ description: step.description,
4005
+ condition: step.condition,
4006
+ ignoreError: step.ignoreError,
4007
+ stepFunction: {
4008
+ functionName: step.stepFunction.functionName,
4009
+ version: step.stepFunction.version,
4010
+ params: {
4011
+ ...step.stepFunction.parameters,
4012
+ ...getDefaultRequestStepFunctionsParams(step.stepFunction.functionName, baseRequestParams, step.stepFunction.parameters),
4013
+ ...step.stepFunction.functionName === "map_fields" || step.stepFunction.functionName === "typecast" ? { fields: op.fieldConfigs } : {}
4014
+ }
4015
+ }
4016
+ };
4017
+ return acc$1;
4018
+ }, {}),
4019
+ result: op.result
4020
+ };
4021
+ return acc;
4022
+ }, {});
4023
+ return newOperations;
4024
+ };
4025
+ const parseOperationInputs = (operation, inputs) => {
4026
+ if (!operation.inputs) return {};
4027
+ const inputSchema = createSchemaByFieldLocation(operation.inputs);
4028
+ const parsedInputs = inputSchema.parse(inputs);
4029
+ return {
4030
+ ...parsedInputs.headers ?? {},
4031
+ ...parsedInputs.query ?? {},
4032
+ ...parsedInputs.path ?? {},
4033
+ ...parsedInputs.body ?? {}
4034
+ };
4035
+ };
4036
+ const createDynamicSchema = (fields) => {
4037
+ const schemaObj = {};
4038
+ fields.forEach((field) => {
4039
+ let fieldSchema;
4040
+ switch (field.type.toLowerCase()) {
4041
+ case "string":
4042
+ fieldSchema = stringType();
4043
+ break;
4044
+ case "number":
4045
+ fieldSchema = numberType();
4046
+ break;
4047
+ case "boolean":
4048
+ fieldSchema = booleanType();
4049
+ break;
4050
+ default: fieldSchema = anyType();
4051
+ }
4052
+ schemaObj[field.name] = field.required ? fieldSchema : fieldSchema.optional();
4053
+ });
4054
+ return objectType(schemaObj);
4055
+ };
4056
+ const createSchemaByFieldLocation = (fields) => {
4057
+ const pathFields = fields.filter((field) => field.in === "path");
4058
+ const queryFields = fields.filter((field) => field.in === "query");
4059
+ const bodyFields = fields.filter((field) => field.in === "body");
4060
+ const headersFields = fields.filter((field) => field.in === "headers");
4061
+ return objectType({
4062
+ path: createDynamicSchema(pathFields).optional(),
4063
+ query: createDynamicSchema(queryFields).optional(),
4064
+ body: createDynamicSchema(bodyFields).optional(),
4065
+ headers: createDynamicSchema(headersFields).optional()
4066
+ });
4067
+ };
4068
+ const buildCursorConfig = (op) => {
4069
+ const isListOperation = op.operationType === "list";
4070
+ const cursorConfig = op.cursor ?? {
4071
+ enabled: isListOperation,
4072
+ pageSize: DEFAULT_PAGE_SIZE
4073
+ };
4074
+ return {
4075
+ enabled: cursorConfig.enabled && isListOperation,
4076
+ pageSize: cursorConfig.pageSize
4077
+ };
4078
+ };
4079
+ const parseCompositeIdentifiersConfig = (op) => {
4080
+ if ((0, __stackone_utils.isMissing)(op.compositeIdentifiers)) {
4081
+ const identifierFieldConfig = op.fieldConfigs?.find((fieldConfig) => fieldConfig.targetFieldKey === "id");
4082
+ const defaultIdentifierFields = (0, __stackone_utils.notMissing)(identifierFieldConfig) ? [{
4083
+ targetFieldKey: identifierFieldConfig.targetFieldKey,
4084
+ remote: "id",
4085
+ components: [{
4086
+ name: identifierFieldConfig.targetFieldKey,
4087
+ alias: identifierFieldConfig.alias
4088
+ }]
4089
+ }] : void 0;
4090
+ return {
4091
+ enabled: true,
4092
+ version: __stackone_core.COMPOSITE_ID_LATEST_VERSION,
4093
+ fields: defaultIdentifierFields
4094
+ };
4095
+ }
4096
+ const mappedFields = [];
4097
+ for (const field of op.compositeIdentifiers?.fields ?? []) {
4098
+ const fieldComponents = field.components.map((component) => {
4099
+ const componentDetail = op.fieldConfigs?.find((fieldConfig) => fieldConfig.targetFieldKey === component);
4100
+ return {
4101
+ name: component,
4102
+ alias: componentDetail?.alias
4103
+ };
4104
+ });
4105
+ mappedFields.push({
4106
+ targetFieldKey: field.targetFieldKey,
4107
+ remote: field.remote,
4108
+ components: fieldComponents
4109
+ });
4110
+ }
4111
+ return {
4112
+ enabled: op.compositeIdentifiers.enabled,
4113
+ version: op.compositeIdentifiers.version,
4114
+ fields: mappedFields.length > 0 ? mappedFields : void 0
4115
+ };
4116
+ };
4117
+ const parseScheduledJobConfig = (op) => {
4118
+ if ((0, __stackone_utils.isMissing)(op.scheduledJobs)) return void 0;
4119
+ return op.scheduledJobs;
4120
+ };
4121
+ const getDefaultRequestStepFunctionsParams = (stepFunctionName, baseRequestParams, functionParams = {}) => {
4122
+ if (stepFunctionName === "request" || stepFunctionName === "paginated_request") {
4123
+ const defaultCustomErrors = [{
4124
+ receivedStatus: 500,
4125
+ targetStatus: 502
4126
+ }];
4127
+ const functionCustomErrors = functionParams.customErrors && Array.isArray(functionParams.customErrors) ? functionParams.customErrors : [];
4128
+ const mergedCustomErrors = [...functionCustomErrors, ...defaultCustomErrors];
4129
+ return {
4130
+ ...baseRequestParams,
4131
+ customErrors: mergedCustomErrors
4132
+ };
4133
+ } else return {};
4134
+ };
4135
+
4136
+ //#endregion
4137
+ //#region src/errors/connectSDKErrors.ts
4138
+ var ConnectSDKError = class ConnectSDKError extends Error {
4139
+ errorType;
4140
+ context;
4141
+ constructor(errorType, context, message) {
4142
+ super(message);
4143
+ this.name = "ConnectSDKError";
4144
+ this.errorType = errorType;
4145
+ this.context = context;
4146
+ if (Error.captureStackTrace) Error.captureStackTrace(this, ConnectSDKError);
4147
+ }
4148
+ toString() {
4149
+ return `${this.name} [${this.errorType}]: ${this.message}`;
4150
+ }
4151
+ };
4152
+ var ConnectorParseError = class extends ConnectSDKError {
4153
+ constructor(context, message) {
4154
+ super("CONNECTOR_PARSE_ERROR", context, message);
4155
+ this.name = "ConnectorParseError";
4156
+ }
4157
+ };
4158
+ var MissingOperationError = class extends ConnectSDKError {
4159
+ constructor(context, message) {
4160
+ super("MISSING_OPERATION_ERROR", context, message);
4161
+ this.name = "MissingOperationError";
4162
+ }
4163
+ };
4164
+ var InvalidOperationInputsError = class extends ConnectSDKError {
4165
+ constructor(context, message) {
4166
+ super("INVALID_OPERATION_INPUTS_ERROR", context, message);
4167
+ this.name = "InvalidOperationInputsError";
4168
+ }
4169
+ };
4170
+ var InvalidCursorError = class extends ConnectSDKError {
4171
+ constructor(context, message) {
4172
+ super("INVALID_CURSOR_ERROR", context, message);
4173
+ this.name = "InvalidCursorError";
4174
+ }
4175
+ };
4176
+
4177
+ //#endregion
4178
+ //#region src/runners/executeStepFunctions.ts
4179
+ const executeStepFunction = async ({ block, stepFunctionName, params, buildStepFunction = __stackone_core.StepFunctionsFactory.build }) => {
4180
+ const stepFunction = buildStepFunction({ functionName: stepFunctionName }).fn;
4181
+ const result = await stepFunction({
4182
+ block,
4183
+ params
4184
+ });
4185
+ const stepSnaphot = stepFunctionName === __stackone_core.StepFunctionName.MAP_FIELDS ? { [__stackone_core.StepFunctionName.MAP_FIELDS.toString()]: {
4186
+ output: { data: result.block.result },
4187
+ errors: result.errors,
4188
+ successful: result.successful
4189
+ } } : {};
4190
+ return {
4191
+ ...result.block,
4192
+ steps: {
4193
+ ...result?.block?.steps ?? {},
4194
+ ...stepSnaphot
4195
+ }
4196
+ };
4197
+ };
4198
+
4199
+ //#endregion
4200
+ //#region src/blocks/createBlockContext.ts
4201
+ const createBlockContext = ({ category, connectorKey, connectorVersion, authConfigKey, environment = "production", operation, accountSecureId, projectSecureId }) => {
4202
+ return {
4203
+ projectSecureId,
4204
+ accountSecureId,
4205
+ connectorKey,
4206
+ connectorVersion,
4207
+ category,
4208
+ service: "",
4209
+ resource: "",
4210
+ schema: operation?.schema?.key,
4211
+ operationType: operation?.operationType ?? "unknown",
4212
+ authenticationType: authConfigKey,
4213
+ environment
4214
+ };
4215
+ };
4216
+
4217
+ //#endregion
4218
+ //#region src/compositeIds/inputs.ts
4219
+ const decodeInputCompositeIdentifiers = (block) => {
4220
+ const compositeIdsConfig = block.operation?.compositeIdentifiers;
4221
+ const blockInputs = { ...block.inputs ?? {} };
4222
+ if (!compositeIdsConfig?.enabled || (0, __stackone_utils.isMissing)(blockInputs)) return block;
4223
+ const aliases = compositeIdsConfig.fields?.reduce((acc, field) => {
4224
+ field.components.forEach((component) => {
4225
+ if (component.alias) acc[component.name] = component.alias;
4226
+ });
4227
+ return acc;
4228
+ }, {});
4229
+ const identifierConfig = {
4230
+ version: compositeIdsConfig.version ?? __stackone_core.COMPOSITE_ID_LATEST_VERSION,
4231
+ aliases
4232
+ };
4233
+ processLevel(blockInputs, identifierConfig, block.logger);
4234
+ return {
4235
+ ...block,
4236
+ inputs: blockInputs
4237
+ };
4238
+ };
4239
+ const processLevel = (input, compositeIdentifierConfig, logger) => {
4240
+ for (const key in input) {
4241
+ const value = input[key];
4242
+ if (typeof value === "string" || Array.isArray(value) && value.every((item) => typeof item === "string")) processCompositeId(value, key, input, compositeIdentifierConfig, logger);
4243
+ else if (Array.isArray(value)) for (const item of value) processLevel(item, compositeIdentifierConfig, logger);
4244
+ else if (typeof value === "object" && value !== null) processLevel(value, compositeIdentifierConfig, logger);
4245
+ }
4246
+ };
4247
+ const processInputElements = (inputArray, key, compositeIdentifierConfig, logger) => {
4248
+ const compositeIdComponents = [];
4249
+ const nonCompositeIds = [];
4250
+ for (const inputElement of inputArray) try {
4251
+ const extractedComponents = (0, __stackone_core.decodeCompositeId)(inputElement, compositeIdentifierConfig);
4252
+ compositeIdComponents.push(extractedComponents);
4253
+ } catch (e) {
4254
+ logger?.debug({
4255
+ message: `Received ${key} with invalid composite ID, assuming it is not a composite ID`,
4256
+ category: "processCompositeId",
4257
+ context: {
4258
+ key,
4259
+ inputElement,
4260
+ compositeIdentifierConfig,
4261
+ error: e
4262
+ }
4263
+ });
4264
+ nonCompositeIds.push(inputElement);
4265
+ }
4266
+ return {
4267
+ compositeIdComponents,
4268
+ nonCompositeIds
4269
+ };
4270
+ };
4271
+ const setDecodedIds = (parentRecord, key, compositeIdComponents, isInputArray) => {
4272
+ const multipleIdsComponents = compositeIdComponents.filter((component) => Object.keys(component).length > 1);
4273
+ if (multipleIdsComponents.length > 0) parentRecord.decoded_ids = {
4274
+ ...parentRecord.decoded_ids ?? {},
4275
+ [key]: isInputArray ? multipleIdsComponents : multipleIdsComponents[0]
4276
+ };
4277
+ };
4278
+ const shouldSimplifyComponent = (component) => {
4279
+ const values = Object.values(component);
4280
+ return values.length === 1 && (typeof values[0] === "string" || typeof values[0] === "number");
4281
+ };
4282
+ const setSimplifiedIds = (parentRecord, key, compositeIdComponents, nonCompositeIds, isInputArray) => {
4283
+ if (!compositeIdComponents.every(shouldSimplifyComponent)) return;
4284
+ if (isInputArray) parentRecord[key] = [...compositeIdComponents.map((component) => Object.values(component)[0]), ...nonCompositeIds];
4285
+ else if (compositeIdComponents.length > 0) parentRecord[key] = Object.values(compositeIdComponents[0])[0];
4286
+ };
4287
+ const handleCompositeIdError = (error, key, logger) => {
4288
+ if (error instanceof __stackone_core.CoreError && error.type === "COMPOSITE_ID_MISSING_HEADER_ERROR") logger?.debug({ message: `Received ${key} with no composite ID header, assuming it is not a composite ID` });
4289
+ else logger?.warning({
4290
+ message: `Error processing composite ID for ${key}, ignoring it`,
4291
+ error
4292
+ });
4293
+ };
4294
+ const processCompositeId = (input, key, parentRecord, compositeIdentifierConfig, logger) => {
4295
+ try {
4296
+ const isInputArray = Array.isArray(input);
4297
+ const inputArray = isInputArray ? input : [input];
4298
+ if (inputArray.length === 0) return;
4299
+ const { compositeIdComponents, nonCompositeIds } = processInputElements(inputArray, key, compositeIdentifierConfig, logger);
4300
+ setDecodedIds(parentRecord, key, compositeIdComponents, isInputArray);
4301
+ setSimplifiedIds(parentRecord, key, compositeIdComponents, nonCompositeIds, isInputArray);
4302
+ } catch (e) {
4303
+ handleCompositeIdError(e, key, logger);
4304
+ }
4305
+ };
4306
+
4307
+ //#endregion
4308
+ //#region src/compositeIds/outputs.ts
4309
+ const REMOTE_FIELD_PREFIX = "remote_";
4310
+ const encodeResultCompositeIdentifiers = (block) => {
4311
+ const compositeIdsConfig = block.operation?.compositeIdentifiers;
4312
+ if (!compositeIdsConfig?.enabled) return block;
4313
+ const outputDataKey = "data";
4314
+ const dataOutput = block.outputs?.[outputDataKey];
4315
+ if ((0, __stackone_utils.isMissing)(dataOutput)) return block;
4316
+ const newData = Array.isArray(dataOutput) ? dataOutput.map((item) => mapCompositeIds(item, compositeIdsConfig)) : mapCompositeIds(dataOutput, compositeIdsConfig);
4317
+ return {
4318
+ ...block,
4319
+ outputs: {
4320
+ ...block.outputs ?? {},
4321
+ [outputDataKey]: newData
4322
+ }
4323
+ };
4324
+ };
4325
+ const mapCompositeIds = (data, config) => {
4326
+ const dataEncodedFromConfig = mapConfiguredCompositeIds(data, config);
4327
+ const encodedData = mapCompositeIdsFromInference(dataEncodedFromConfig);
4328
+ return {
4329
+ ...data,
4330
+ ...(0, __stackone_utils.isObject)(encodedData) ? encodedData : {}
4331
+ };
4332
+ };
4333
+ const mapConfiguredCompositeIds = (data, config) => {
4334
+ const version = config.version ?? __stackone_core.COMPOSITE_ID_LATEST_VERSION;
4335
+ const newData = {};
4336
+ config.fields?.forEach((field) => {
4337
+ const aliasesMap = {};
4338
+ const components = [];
4339
+ field.components.forEach((component) => {
4340
+ if (component.alias) aliasesMap[component.name] = component.alias;
4341
+ components.push({
4342
+ key: component.name,
4343
+ value: data[component.name]
4344
+ });
4345
+ });
4346
+ const identifier = components.length === 1 ? components[0] : { identifiers: components };
4347
+ const idConfig = {
4348
+ version,
4349
+ aliases: Object.keys(aliasesMap).length > 0 ? aliasesMap : void 0
4350
+ };
4351
+ const compositeId = (0, __stackone_core.encodeCompositeId)(identifier, idConfig);
4352
+ newData[field.targetFieldKey] = compositeId;
4353
+ if (field.remote) newData[`${REMOTE_FIELD_PREFIX}${field.remote}`] = data[field.remote];
4354
+ });
4355
+ return {
4356
+ ...data,
4357
+ ...newData
4358
+ };
4359
+ };
4360
+ const isIdField = (key) => {
4361
+ return key === "id" || /.+_id(s)?$/.test(key);
4362
+ };
4363
+ const isValidStringArray = (value) => {
4364
+ return Array.isArray(value) && value.every((v) => (0, __stackone_utils.isString)(v) && v.length > 0);
4365
+ };
4366
+ const shouldSkipEncoding = (value, key) => {
4367
+ return (0, __stackone_core.isCompositeId)(value) || key.startsWith(REMOTE_FIELD_PREFIX);
4368
+ };
4369
+ const encodeStringValue = (key, value) => {
4370
+ try {
4371
+ return (0, __stackone_core.encodeCompositeId)({
4372
+ key,
4373
+ value
4374
+ }, { version: __stackone_core.COMPOSITE_ID_LATEST_VERSION });
4375
+ } catch {
4376
+ return value;
4377
+ }
4378
+ };
4379
+ const processStringArrayField = (key, value, result) => {
4380
+ const encodedArray = value.map((v) => {
4381
+ if ((0, __stackone_utils.isString)(v) && v.length > 0 && !(0, __stackone_core.isCompositeId)(v)) return encodeStringValue(key, v);
4382
+ return v;
4383
+ });
4384
+ result[key] = encodedArray;
4385
+ result[`${REMOTE_FIELD_PREFIX}${key}`] = value;
4386
+ };
4387
+ const processStringField = (key, value, result) => {
4388
+ if (shouldSkipEncoding(value, key)) return;
4389
+ const compositeId = (0, __stackone_core.encodeCompositeId)({
4390
+ key,
4391
+ value
4392
+ }, { version: __stackone_core.COMPOSITE_ID_LATEST_VERSION });
4393
+ result[key] = compositeId;
4394
+ result[`remote_${key}`] = value;
4395
+ };
4396
+ const processIdField = (key, value, result) => {
4397
+ if (isValidStringArray(value)) processStringArrayField(key, value, result);
4398
+ else if ((0, __stackone_utils.isString)(value) && value.length > 0) processStringField(key, value, result);
4399
+ };
4400
+ const mapCompositeIdsFromInference = (data) => {
4401
+ if (Array.isArray(data)) return data.map((item) => mapCompositeIdsFromInference(item));
4402
+ if (!(0, __stackone_utils.isObject)(data)) return data;
4403
+ const result = { ...data };
4404
+ for (const [key, value] of Object.entries(data)) {
4405
+ if ((0, __stackone_utils.isObject)(value) || Array.isArray(value) && value.length > 0 && (0, __stackone_utils.isObject)(value[0])) result[key] = mapCompositeIdsFromInference(value);
4406
+ if (isIdField(key)) processIdField(key, value, result);
4407
+ }
4408
+ return result;
4409
+ };
4410
+
4411
+ //#endregion
4412
+ //#region src/pagination/utils.ts
4413
+ const getPageSize = (block, defaultValue) => {
4414
+ const inputPageSize = Number(block.inputs?.page_size);
4415
+ const pageSize = (0, __stackone_utils.notMissing)(block.inputs?.page_size) && (0, __stackone_utils.isNumber)(inputPageSize) && !Number.isNaN(inputPageSize) ? inputPageSize : block.operation?.cursor?.pageSize ?? defaultValue;
4416
+ return pageSize;
4417
+ };
4418
+
4419
+ //#endregion
4420
+ //#region src/pagination/virtualPagination.ts
4421
+ const virtualPaginateResult = (result, pageSize, steps, cursor) => {
4422
+ const data = (0, __stackone_utils.isMissing)(result) ? void 0 : result.data;
4423
+ const resultStepIndex = Object.keys(steps).length + 1;
4424
+ const emptyCursor = (0, __stackone_core.isCursorEmpty)({
4425
+ cursor,
4426
+ ignoreStepIndex: resultStepIndex
4427
+ });
4428
+ if (!(0, __stackone_utils.isObject)(result) || (0, __stackone_utils.isMissing)(data) || (data?.length ?? 0) <= pageSize) return {
4429
+ result,
4430
+ next: (0, __stackone_utils.notMissing)(cursor) && !emptyCursor ? (0, __stackone_core.minifyCursor)(cursor) : null
4431
+ };
4432
+ const pageNumber = cursor?.remote?.[resultStepIndex]?.pageNumber ?? 1;
4433
+ const startIndex = (pageNumber - 1) * pageSize;
4434
+ const endIndex = startIndex + pageSize;
4435
+ const slicedData = data.slice(startIndex, endIndex);
4436
+ const hasMorePages = data.length > endIndex || !emptyCursor;
4437
+ const pageCursor = (0, __stackone_core.updateCursor)({
4438
+ cursor,
4439
+ stepIndex: resultStepIndex,
4440
+ pageNumber: pageNumber + 1
4441
+ });
4442
+ return {
4443
+ result: {
4444
+ ...result,
4445
+ data: slicedData
4446
+ },
4447
+ next: hasMorePages ? (0, __stackone_core.minifyCursor)(pageCursor) : null
4448
+ };
4449
+ };
4450
+
4451
+ //#endregion
4452
+ //#region src/runners/runStepOperation.ts
4453
+ const runStepOperation = async ({ block, buildStepFunction = __stackone_core.StepFunctionsFactory.build, virtualPaginateResultFn = virtualPaginateResult, encodeResultCompositeIds = encodeResultCompositeIdentifiers, decodeInputCompositeIds = decodeInputCompositeIdentifiers }) => {
4454
+ const decodeBlock = decodeInputCompositeIds(block);
4455
+ const resultBlock = await executeStepsWorkflow({
4456
+ block: decodeBlock,
4457
+ buildStepFunction,
4458
+ virtualPaginateResultFn
4459
+ });
4460
+ return encodeResultCompositeIds(resultBlock);
4461
+ };
4462
+ const shouldSkipStepDueToCondition = (step, block) => {
4463
+ return step.condition ? !(0, __stackone_expressions.safeEvaluate)(step.condition, block) : false;
4464
+ };
4465
+ const buildStepParams = (step, blockAcc, stepIndex) => {
4466
+ const fn = step.stepFunction;
4467
+ return blockAcc.operation?.cursor.enabled ? {
4468
+ ...fn.params ?? {},
4469
+ cursor: {
4470
+ token: blockAcc.nextCursor?.remote?.[stepIndex]?.providerPageCursor,
4471
+ position: blockAcc.nextCursor?.remote?.[stepIndex]?.position
4472
+ }
4473
+ } : fn.params ?? {};
4474
+ };
4475
+ const handleStepFailure = (blockAcc, stepId, functionOutput, step, state) => {
4476
+ const updatedBlock = addStepResultToBlock({
4477
+ block: blockAcc,
4478
+ stepId,
4479
+ successful: false,
4480
+ functionOutput
4481
+ });
4482
+ const ignoreError = step.ignoreError ?? false;
4483
+ if (!ignoreError) {
4484
+ state.hasFatalError = true;
4485
+ state.errorStatusCode ??= functionOutput.output?.statusCode ?? 500;
4486
+ }
4487
+ return updatedBlock;
4488
+ };
4489
+ const executeStep = async (stepId, stepIndex, stepsToExecute, blockAcc, state, context) => {
4490
+ const step = stepsToExecute[stepId];
4491
+ const fn = step.stepFunction;
4492
+ const stepFunction = context.buildStepFunction({
4493
+ functionName: fn.functionName,
4494
+ version: fn.version,
4495
+ validateSchemas: true
4496
+ }).fn;
4497
+ if (shouldSkipStepDueToCondition(step, blockAcc)) return addStepResultToBlock({
4498
+ block: blockAcc,
4499
+ stepId,
4500
+ successful: true,
4501
+ skipped: true,
4502
+ message: "Step skipped due to condition not met."
4503
+ });
4504
+ if (state.hasFatalError) return addStepResultToBlock({
4505
+ block: blockAcc,
4506
+ stepId,
4507
+ successful: false,
4508
+ skipped: true,
4509
+ message: "Step skipped due to previous error."
4510
+ });
4511
+ const fnParams = buildStepParams(step, blockAcc, stepIndex);
4512
+ const functionOutput = await stepFunction({
4513
+ block: blockAcc,
4514
+ params: fnParams
4515
+ });
4516
+ if (functionOutput.successful === false) return handleStepFailure(blockAcc, stepId, functionOutput, step, state);
4517
+ const updatedCursor = blockAcc.operation?.cursor.enabled ? (0, __stackone_core.updateCursor)({
4518
+ cursor: blockAcc.nextCursor,
4519
+ stepIndex,
4520
+ providerPageCursor: functionOutput.output?.next,
4521
+ position: functionOutput.output?.position
4522
+ }) : void 0;
4523
+ return addStepResultToBlock({
4524
+ block: {
4525
+ ...functionOutput.block,
4526
+ nextCursor: updatedCursor
4527
+ },
4528
+ stepId,
4529
+ functionOutput
4530
+ });
4531
+ };
4532
+ const buildFinalResponse = (block, blockAcc, state, result, finalData) => {
4533
+ const isSuccessful = !state.hasFatalError;
4534
+ const finalStatusCode = isSuccessful ? block.operation?.responses.success.statusCode ?? 200 : state.errorStatusCode ?? 500;
4535
+ const outputs = (0, __stackone_utils.notMissing)(finalData) && (0, __stackone_utils.isObject)(finalData.result) ? {
4536
+ next: finalData.next,
4537
+ ...finalData.result
4538
+ } : result;
4539
+ return {
4540
+ ...blockAcc,
4541
+ outputs,
4542
+ response: {
4543
+ successful: isSuccessful,
4544
+ statusCode: finalStatusCode,
4545
+ message: !isSuccessful ? block.operation?.responses?.errors?.[finalStatusCode]?.description ?? __stackone_transport.HttpErrorMessages?.[finalStatusCode] ?? "Error while processing the request" : void 0
4546
+ }
4547
+ };
4548
+ };
4549
+ const executeStepsWorkflow = async ({ block, buildStepFunction = __stackone_core.StepFunctionsFactory.build, virtualPaginateResultFn = virtualPaginateResult }) => {
4550
+ const stepsToExecute = block.operation?.steps || {};
4551
+ let blockAcc = { ...block };
4552
+ const stepsIds = Object.keys(stepsToExecute);
4553
+ const pageSize = getPageSize(block, DEFAULT_PAGE_SIZE);
4554
+ const state = {
4555
+ hasFatalError: false,
4556
+ errorStatusCode: null
4557
+ };
4558
+ const context = {
4559
+ block,
4560
+ buildStepFunction,
4561
+ virtualPaginateResultFn
4562
+ };
4563
+ for (const [stepIndex, stepId] of stepsIds.entries()) blockAcc = await executeStep(stepId, stepIndex, stepsToExecute, blockAcc, state, context);
4564
+ const result = block.operation?.result ? evaluateResult(block.operation.result, blockAcc) : void 0;
4565
+ const finalData = block.operation?.cursor.enabled ? virtualPaginateResultFn(result, pageSize, stepsToExecute, blockAcc.nextCursor) : void 0;
4566
+ return buildFinalResponse(block, blockAcc, state, result, finalData);
4567
+ };
4568
+ const evaluateResult = (result, block) => {
4569
+ if ((0, __stackone_utils.isObject)(result)) return (0, __stackone_expressions.safeEvaluateRecord)(result, block);
4570
+ return (0, __stackone_expressions.safeEvaluate)(result, block);
4571
+ };
4572
+ const addStepResultToBlock = ({ block, stepId, successful, functionOutput, skipped, message }) => {
4573
+ return {
4574
+ ...block,
4575
+ steps: {
4576
+ ...block.steps,
4577
+ [stepId]: {
4578
+ successful: successful ?? functionOutput?.successful ?? false,
4579
+ errors: functionOutput?.errors,
4580
+ output: functionOutput?.output,
4581
+ skipped,
4582
+ message
4583
+ }
4584
+ }
4585
+ };
4586
+ };
4587
+
4588
+ //#endregion
4589
+ //#region src/runners/runConnectorOperation.ts
4590
+ const runConnectorOperation = async ({ account, connector, category, path, method = "get", queryParams, body, headers, logger, parseConnector = parseYamlConnector, getOperationFromUrlFn = getOperationFromUrl, parseOperationInputsFn = parseOperationInputs, createBlockContextFn = createBlockContext, createBlockFn = createBlock, runStepOperationFn = runStepOperation }) => {
4591
+ const authConfigKey = account.authConfigKey;
4592
+ const environment = account.environment ?? "production";
4593
+ const accountSecureId = account.secureId;
4594
+ const projectSecureId = account.projectSecureId;
4595
+ const credentials = account.credentials;
4596
+ const blockContext = createBlockContextFn({
4597
+ category,
4598
+ connectorKey: account.providerKey,
4599
+ connectorVersion: account.providerVersion,
4600
+ authConfigKey,
4601
+ environment,
4602
+ accountSecureId,
4603
+ projectSecureId
4604
+ });
4605
+ let parsedConnector;
4606
+ try {
4607
+ parsedConnector = (0, __stackone_utils.isString)(connector) ? parseConnector(connector) : connector;
4608
+ } catch {
4609
+ throw new ConnectorParseError(blockContext, "Error while parsing connector");
4610
+ }
4611
+ const matchingOperation = getOperationFromUrlFn(parsedConnector, path, method);
4612
+ if ((0, __stackone_utils.isMissing)(matchingOperation)) throw new MissingOperationError(blockContext, "No matching operation found");
4613
+ blockContext.operationType = matchingOperation.operation.operationType;
4614
+ blockContext.schema = matchingOperation.operation.schema?.key;
4615
+ const expandedCursor = processCursor(queryParams, blockContext);
4616
+ let operationInputs;
4617
+ try {
4618
+ operationInputs = parseOperationInputsFn(matchingOperation.operation, {
4619
+ query: queryParams,
4620
+ body,
4621
+ headers,
4622
+ path: matchingOperation.params
4623
+ });
4624
+ } catch {
4625
+ throw new InvalidOperationInputsError(blockContext, "Error while parsing operation inputs");
4626
+ }
4627
+ const block = await createBlockFn({
4628
+ inputs: operationInputs,
4629
+ context: blockContext,
4630
+ operation: matchingOperation.operation,
4631
+ credentials,
4632
+ nextCursor: expandedCursor,
4633
+ logger
4634
+ });
4635
+ return await runStepOperationFn({ block });
4636
+ };
4637
+ const processCursor = (queryParams, blockContext) => {
4638
+ const nextCursor = queryParams?.["next"];
4639
+ const expandedCursor = (0, __stackone_utils.notMissing)(nextCursor) && blockContext.operationType === "list" ? (0, __stackone_core.expandCursor)(nextCursor) : void 0;
4640
+ if (expandedCursor === null) throw new InvalidCursorError(blockContext, `Invalid cursor.`);
4641
+ return expandedCursor;
4642
+ };
4643
+
4644
+ //#endregion
4645
+ exports.ConnectSDKError = ConnectSDKError;
4646
+ exports.createBlock = createBlock;
4647
+ exports.executeStepFunction = executeStepFunction;
4648
+ exports.getOperationFromUrl = getOperationFromUrl;
4649
+ exports.parseOperationInputs = parseOperationInputs;
4650
+ exports.parseYamlConnector = parseYamlConnector;
4651
+ exports.runConnectorOperation = runConnectorOperation;
4652
+ exports.runStepOperation = runStepOperation;