From 27ac3c00ce6fde3ffd03beb3cdb2d1b5755a8222 Mon Sep 17 00:00:00 2001 From: QA Wolf bot Date: Mon, 11 Nov 2024 11:12:52 +0000 Subject: [PATCH] Version update to v1.0.3, revision 6634300 --- CHANGELOG.md | 4 + action.yml | 4 + dist/index.js | 4730 +++--------------------------------------- package.json | 5 +- src/index.ts | 5 +- src/validateInput.ts | 7 + 6 files changed, 264 insertions(+), 4491 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9144bf8..fcdaf87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +## v1.0.3 + +- Add `qawolf-base-url` optional input + ## v1.0.2 - Fix action name on documentation diff --git a/action.yml b/action.yml index 4d0bfa3..a6691f4 100644 --- a/action.yml +++ b/action.yml @@ -27,6 +27,10 @@ inputs: variables: description: "JSON-formatted environment variables for deployment to be tested. Refer to our official documentation for more details." required: false + qawolf-base-url: + required: false + description: > + The base URL of the QA Wolf API. outputs: run-id: description: "The run ID corresponding to the newly created run. It can be used with ci-greenlight integration." diff --git a/dist/index.js b/dist/index.js index 71b5555..0806083 100644 --- a/dist/index.js +++ b/dist/index.js @@ -25415,14 +25415,14 @@ module.exports = { /***/ }), -/***/ 3589: +/***/ 8872: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; -const util_1 = __nccwpck_require__(1888); +const util_1 = __nccwpck_require__(3306); exports.ZodIssueCode = util_1.util.arrayToEnum([ "invalid_type", "invalid_literal", @@ -25560,7 +25560,7 @@ ZodError.create = (issues) => { /***/ }), -/***/ 4115: +/***/ 5681: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -25570,7 +25570,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; -const en_1 = __importDefault(__nccwpck_require__(7481)); +const en_1 = __importDefault(__nccwpck_require__(3803)); exports.defaultErrorMap = en_1.default; let overrideErrorMap = en_1.default; function setErrorMap(map) { @@ -25585,7 +25585,7 @@ exports.getErrorMap = getErrorMap; /***/ }), -/***/ 621: +/***/ 7508: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -25601,17 +25601,17 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(4115), exports); -__exportStar(__nccwpck_require__(8154), exports); -__exportStar(__nccwpck_require__(34), exports); -__exportStar(__nccwpck_require__(1888), exports); -__exportStar(__nccwpck_require__(2251), exports); -__exportStar(__nccwpck_require__(3589), exports); +__exportStar(__nccwpck_require__(5681), exports); +__exportStar(__nccwpck_require__(4749), exports); +__exportStar(__nccwpck_require__(7001), exports); +__exportStar(__nccwpck_require__(3306), exports); +__exportStar(__nccwpck_require__(1129), exports); +__exportStar(__nccwpck_require__(8872), exports); /***/ }), -/***/ 8009: +/***/ 3750: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -25627,7 +25627,7 @@ var errorUtil; /***/ }), -/***/ 8154: +/***/ 4749: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -25637,8 +25637,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; -const errors_1 = __nccwpck_require__(4115); -const en_1 = __importDefault(__nccwpck_require__(7481)); +const errors_1 = __nccwpck_require__(5681); +const en_1 = __importDefault(__nccwpck_require__(3803)); const makeIssue = (params) => { const { data, path, errorMaps, issueData } = params; const fullPath = [...path, ...(issueData.path || [])]; @@ -25760,7 +25760,7 @@ exports.isAsync = isAsync; /***/ }), -/***/ 34: +/***/ 7001: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -25770,7 +25770,7 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), -/***/ 1888: +/***/ 3306: /***/ ((__unused_webpack_module, exports) => { "use strict"; @@ -25920,7 +25920,7 @@ exports.getParsedType = getParsedType; /***/ }), -/***/ 9102: +/***/ 6762: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -25949,22 +25949,22 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) { }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.z = void 0; -const z = __importStar(__nccwpck_require__(621)); +const z = __importStar(__nccwpck_require__(7508)); exports.z = z; -__exportStar(__nccwpck_require__(621), exports); +__exportStar(__nccwpck_require__(7508), exports); exports["default"] = z; /***/ }), -/***/ 7481: +/***/ 3803: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const util_1 = __nccwpck_require__(1888); -const ZodError_1 = __nccwpck_require__(3589); +const util_1 = __nccwpck_require__(3306); +const ZodError_1 = __nccwpck_require__(8872); const errorMap = (issue, _ctx) => { let message; switch (issue.code) { @@ -26094,7 +26094,7 @@ exports["default"] = errorMap; /***/ }), -/***/ 2251: +/***/ 1129: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; @@ -26114,4375 +26114,11 @@ var _ZodEnum_cache, _ZodNativeEnum_cache; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.datetimeRegex = exports.ZodType = void 0; exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = exports.discriminatedUnion = exports.date = void 0; -const errors_1 = __nccwpck_require__(4115); -const errorUtil_1 = __nccwpck_require__(8009); -const parseUtil_1 = __nccwpck_require__(8154); -const util_1 = __nccwpck_require__(1888); -const ZodError_1 = __nccwpck_require__(3589); -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (this._key instanceof Array) { - this._cachedPath.push(...this._path, ...this._key); - } - else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -const handleResult = (ctx, result) => { - if ((0, parseUtil_1.isValid)(result)) { - return { success: true, data: result.value }; - } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError_1.ZodError(ctx.common.issues); - this._error = error; - return this._error; - }, - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - var _a, _b; - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message !== null && message !== void 0 ? message : ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -class ZodType { - constructor(def) { - /** Alias of safeParseAsync */ - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - } - get description() { - return this._def.description; - } - _getType(input) { - return (0, util_1.getParsedType)(input.data); - } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }); - } - _processInputParams(input) { - return { - status: new parseUtil_1.ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: (0, util_1.getParsedType)(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - _parseSync(input) { - const result = this._parse(input); - if ((0, parseUtil_1.isAsync)(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - var _a; - const ctx = { - common: { - issues: [], - async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, - async: true, - }, - path: (params === null || params === void 0 ? void 0 : params.path) || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: (0, util_1.getParsedType)(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) - ? maybeAsyncResult - : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodError_1.ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } - else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" - ? refinementData(val, ctx) - : refinementData); - return false; - } - else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this, this._def); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description, - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -exports.ZodType = ZodType; -exports.Schema = ZodType; -exports.ZodSchema = ZodType; -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[0-9a-z]+$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/; -// const uuidRegex = -// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; -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; -const nanoidRegex = /^[a-z0-9_-]{21}$/i; -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)?)??$/; -// from https://stackoverflow.com/a/46181/1550155 -// old version: too slow, didn't support unicode -// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; -//old email regex -// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; -// eslint-disable-next-line -// const emailRegex = -// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; -// const emailRegex = -// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// const emailRegex = -// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; -const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -// const emailRegex = -// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex; -// faster, simpler, safer -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])$/; -const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -// simple -// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; -// no leap year validation -// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; -// with leap year validation -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])))`; -const dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - // let regex = `\\d{2}:\\d{2}:\\d{2}`; - let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`; - if (args.precision) { - regex = `${regex}\\.\\d{${args.precision}}`; - } - else if (args.precision == null) { - regex = `${regex}(\\.\\d+)?`; - } - return regex; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -exports.datetimeRegex = datetimeRegex; -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -class ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.string, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "email", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "emoji", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "uuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "nanoid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "cuid2", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ulid", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "url") { - try { - new URL(input.data); - } - catch (_a) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "url", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "regex", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "trim") { - input.data = input.data.trim(); - } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "date", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_string, - validation: "time", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "duration", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "ip", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - validation: "base64", - code: ZodError_1.ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodError_1.ZodIssueCode.invalid_string, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil_1.errorUtil.errToObj(message) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); - } - datetime(options) { - var _a, _b; - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, - local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options, - }); - } - return this._addCheck({ - kind: "time", - precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil_1.errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options === null || options === void 0 ? void 0 : options.position, - ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message), - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil_1.errorUtil.errToObj(message), - }); - } - /** - * @deprecated Use z.string().min(1) instead. - * @see {@link ZodString.min} - */ - nonempty(message) { - return this.min(1, errorUtil_1.errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -exports.ZodString = ZodString; -ZodString.create = (params) => { - var _a; - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); -}; -// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / Math.pow(10, decCount); -} -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.number, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util_1.util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil_1.errorUtil.toString(message), - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil_1.errorUtil.toString(message), - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || - (ch.kind === "multipleOf" && util_1.util.isInteger(ch.value))); - } - get isFinite() { - let max = null, min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || - ch.kind === "int" || - ch.kind === "multipleOf") { - return true; - } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -exports.ZodNumber = ZodNumber; -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - input.data = BigInt(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.bigint) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.bigint, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - let ctx = undefined; - const status = new parseUtil_1.ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive - ? input.data < check.value - : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive - ? input.data > check.value - : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil_1.errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil_1.errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -exports.ZodBigInt = ZodBigInt; -ZodBigInt.create = (params) => { - var _a; - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, - ...processCreateParams(params), - }); -}; -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.boolean, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodBoolean = ZodBoolean; -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - ...processCreateParams(params), - }); -}; -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.date, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_date, - }); - return parseUtil_1.INVALID; - } - const status = new parseUtil_1.ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } - else { - util_1.util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil_1.errorUtil.toString(message), - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -exports.ZodDate = ZodDate; -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); -}; -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.symbol, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodSymbol = ZodSymbol; -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); -}; -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.undefined, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodUndefined = ZodUndefined; -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); -}; -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.null, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodNull = ZodNull; -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); -}; -class ZodAny extends ZodType { - constructor() { - super(...arguments); - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - this._any = true; - } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodAny = ZodAny; -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); -}; -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - // required - this._unknown = true; - } - _parse(input) { - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodUnknown = ZodUnknown; -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); -}; -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.never, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } -} -exports.ZodNever = ZodNever; -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); -}; -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.void, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } -} -exports.ZodVoid = ZodVoid; -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); -}; -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return parseUtil_1.ParseStatus.mergeArray(status, result); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return parseUtil_1.ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - nonempty(message) { - return this.min(1, message); - } -} -exports.ZodArray = ZodArray; -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }); - } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } - else { - return schema; - } -} -class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - this.nonstrict = this.passthrough; - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util_1.util.objectKeys(shape); - return (this._cached = { shape, keys }); - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && - this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } - else if (unknownKeys === "strip") { - } - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } - else { - // run catchall validation - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); - } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); - }); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil_1.errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - var _a, _b, _c, _d; - const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); - } - pick(mask) { - const shape = {}; - util_1.util.objectKeys(mask).forEach((key) => { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - omit(mask) { - const shape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - }); - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } - else { - newShape[key] = fieldSchema.optional(); - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - required(mask) { - const newShape = {}; - util_1.util.objectKeys(this.shape).forEach((key) => { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } - else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - }); - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - keyof() { - return createZodEnum(util_1.util.objectKeys(this.shape)); - } -} -exports.ZodObject = ZodObject; -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - // return invalid - const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); - } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues) => new ZodError_1.ZodError(issues)); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union, - unionErrors, - }); - return parseUtil_1.INVALID; - } - } - get options() { - return this._def.options; - } -} -exports.ZodUnion = ZodUnion; -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); -}; -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } - else if (type instanceof ZodLiteral) { - return [type.value]; - } - else if (type instanceof ZodEnum) { - return type.options; - } - else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util_1.util.objectValues(type.enum); - } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } - else if (type instanceof ZodUndefined) { - return [undefined]; - } - else if (type instanceof ZodNull) { - return [null]; - } - else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } - else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } - else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } - else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } - else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } - else { - return []; - } -}; -class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return parseUtil_1.INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - // Get all the valid discriminator values - const optionsMap = new Map(); - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), - }); - } -} -exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; -function mergeValues(a, b) { - const aType = (0, util_1.getParsedType)(a); - const bType = (0, util_1.getParsedType)(b); - if (a === b) { - return { valid: true, data: a }; - } - else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { - const bKeys = util_1.util.objectKeys(b); - const sharedKeys = util_1.util - .objectKeys(a) - .filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - else if (aType === util_1.ZodParsedType.date && - bType === util_1.ZodParsedType.date && - +a === +b) { - return { valid: true, data: a }; - } - else { - return { valid: false }; - } -} -class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { - return parseUtil_1.INVALID; - } - const merged = mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_intersection_types, - }); - return parseUtil_1.INVALID; - } - if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); - } - else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); - } - } -} -exports.ZodIntersection = ZodIntersection; -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); -}; -class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.array) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.array, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - if (ctx.data.length < this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return parseUtil_1.INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); // filter nulls - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return parseUtil_1.ParseStatus.mergeArray(status, results); - }); - } - else { - return parseUtil_1.ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); - } -} -exports.ZodTuple = ZodTuple; -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); -}; -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.object) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.object, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (ctx.common.async) { - return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs); - } - else { - return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); - } -} -exports.ZodRecord = ZodRecord; -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.map) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.map, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; - }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return parseUtil_1.INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -exports.ZodMap = ZodMap; -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); -}; -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.set) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.set, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return parseUtil_1.INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) }, - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -exports.ZodSet = ZodSet; -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); -}; -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.function) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.function, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - function makeArgsIssue(args, error) { - return (0, parseUtil_1.makeIssue)({ - data: args, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - function makeReturnsIssue(returns, error) { - return (0, parseUtil_1.makeIssue)({ - data: returns, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - (0, errors_1.getErrorMap)(), - errors_1.defaultErrorMap, - ].filter((x) => !!x), - issueData: { - code: ZodError_1.ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return (0, parseUtil_1.OK)(async function (...args) { - const error = new ZodError_1.ZodError([]); - const parsedArgs = await me._def.args - .parseAsync(args, params) - .catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } - else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return (0, parseUtil_1.OK)(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: (args - ? args - : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }); - } -} -exports.ZodFunction = ZodFunction; -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -exports.ZodLazy = ZodLazy; -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); -}; -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return parseUtil_1.INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -exports.ZodLiteral = ZodLiteral; -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); -} -class ZodEnum extends ZodType { - constructor() { - super(...arguments); - _ZodEnum_cache.set(this, void 0); - } - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f"); - } - if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }); - } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef, - }); - } -} -exports.ZodEnum = ZodEnum; -_ZodEnum_cache = new WeakMap(); -ZodEnum.create = createZodEnum; -class ZodNativeEnum extends ZodType { - constructor() { - super(...arguments); - _ZodNativeEnum_cache.set(this, void 0); - } - _parse(input) { - const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== util_1.ZodParsedType.string && - ctx.parsedType !== util_1.ZodParsedType.number) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - expected: util_1.util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodError_1.ZodIssueCode.invalid_type, - }); - return parseUtil_1.INVALID; - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) { - __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util_1.util.getValidEnumValues(this._def.values)), "f"); - } - if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) { - const expectedValues = util_1.util.objectValues(nativeEnumValues); - (0, parseUtil_1.addIssueToContext)(ctx, { - received: ctx.data, - code: ZodError_1.ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return parseUtil_1.INVALID; - } - return (0, parseUtil_1.OK)(input.data); - } - get enum() { - return this._def.values; - } -} -exports.ZodNativeEnum = ZodNativeEnum; -_ZodNativeEnum_cache = new WeakMap(); -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); -}; -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== util_1.ZodParsedType.promise && - ctx.common.async === false) { - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.promise, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - const promisified = ctx.parsedType === util_1.ZodParsedType.promise - ? ctx.data - : Promise.resolve(ctx.data); - return (0, parseUtil_1.OK)(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } -} -exports.ZodPromise = ZodPromise; -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); -}; -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - (0, parseUtil_1.addIssueToContext)(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return parseUtil_1.INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_1.INVALID; - if (result.status === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - if (status.value === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - return result; - }); - } - else { - if (status.value === "aborted") - return parseUtil_1.INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return parseUtil_1.INVALID; - if (result.status === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - if (status.value === "dirty") - return (0, parseUtil_1.DIRTY)(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((inner) => { - if (inner.status === "aborted") - return parseUtil_1.INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!(0, parseUtil_1.isValid)(base)) - return base; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } - else { - return this._def.schema - ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) - .then((base) => { - if (!(0, parseUtil_1.isValid)(base)) - return base; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result })); - }); - } - } - util_1.util.assertNever(effect); - } -} -exports.ZodEffects = ZodEffects; -exports.ZodTransformer = ZodEffects; -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); -}; -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.undefined) { - return (0, parseUtil_1.OK)(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -exports.ZodOptional = ZodOptional; -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); -}; -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === util_1.ZodParsedType.null) { - return (0, parseUtil_1.OK)(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -exports.ZodNullable = ZodNullable; -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); -}; -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === util_1.ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - removeDefault() { - return this._def.innerType; - } -} -exports.ZodDefault = ZodDefault; -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" - ? params.default - : () => params.default, - ...processCreateParams(params), - }); -}; -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - // newCtx is used to not collect issues from inner types in ctx - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if ((0, parseUtil_1.isAsync)(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError_1.ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -exports.ZodCatch = ZodCatch; -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); -}; -class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== util_1.ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - (0, parseUtil_1.addIssueToContext)(ctx, { - code: ZodError_1.ZodIssueCode.invalid_type, - expected: util_1.ZodParsedType.nan, - received: ctx.parsedType, - }); - return parseUtil_1.INVALID; - } - return { status: "valid", value: input.data }; - } -} -exports.ZodNaN = ZodNaN; -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); -}; -exports.BRAND = Symbol("zod_brand"); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - unwrap() { - return this._def.type; - } -} -exports.ZodBranded = ZodBranded; -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return (0, parseUtil_1.DIRTY)(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); - } - else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return parseUtil_1.INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; - } - else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } -} -exports.ZodPipeline = ZodPipeline; -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if ((0, parseUtil_1.isValid)(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return (0, parseUtil_1.isAsync)(result) - ? result.then((data) => freeze(data)) - : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -exports.ZodReadonly = ZodReadonly; -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }); -}; -function custom(check, params = {}, -/** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ -fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - var _a, _b; - if (!check(data)) { - const p = typeof params === "function" - ? params(data) - : typeof params === "string" - ? { message: params } - : params; - const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; - const p2 = typeof p === "string" ? { message: p } : p; - ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); - } - }); - return ZodAny.create(); -} -exports.custom = custom; -exports.late = { - object: ZodObject.lazycreate, -}; -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); -// requires TS 4.4+ -class Class { - constructor(..._) { } -} -const instanceOfType = ( -// const instanceOfType = any>( -cls, params = { - message: `Input not instance of ${cls.name}`, -}) => custom((data) => data instanceof cls, params); -exports["instanceof"] = instanceOfType; -const stringType = ZodString.create; -exports.string = stringType; -const numberType = ZodNumber.create; -exports.number = numberType; -const nanType = ZodNaN.create; -exports.nan = nanType; -const bigIntType = ZodBigInt.create; -exports.bigint = bigIntType; -const booleanType = ZodBoolean.create; -exports.boolean = booleanType; -const dateType = ZodDate.create; -exports.date = dateType; -const symbolType = ZodSymbol.create; -exports.symbol = symbolType; -const undefinedType = ZodUndefined.create; -exports.undefined = undefinedType; -const nullType = ZodNull.create; -exports["null"] = nullType; -const anyType = ZodAny.create; -exports.any = anyType; -const unknownType = ZodUnknown.create; -exports.unknown = unknownType; -const neverType = ZodNever.create; -exports.never = neverType; -const voidType = ZodVoid.create; -exports["void"] = voidType; -const arrayType = ZodArray.create; -exports.array = arrayType; -const objectType = ZodObject.create; -exports.object = objectType; -const strictObjectType = ZodObject.strictCreate; -exports.strictObject = strictObjectType; -const unionType = ZodUnion.create; -exports.union = unionType; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -exports.discriminatedUnion = discriminatedUnionType; -const intersectionType = ZodIntersection.create; -exports.intersection = intersectionType; -const tupleType = ZodTuple.create; -exports.tuple = tupleType; -const recordType = ZodRecord.create; -exports.record = recordType; -const mapType = ZodMap.create; -exports.map = mapType; -const setType = ZodSet.create; -exports.set = setType; -const functionType = ZodFunction.create; -exports["function"] = functionType; -const lazyType = ZodLazy.create; -exports.lazy = lazyType; -const literalType = ZodLiteral.create; -exports.literal = literalType; -const enumType = ZodEnum.create; -exports["enum"] = enumType; -const nativeEnumType = ZodNativeEnum.create; -exports.nativeEnum = nativeEnumType; -const promiseType = ZodPromise.create; -exports.promise = promiseType; -const effectsType = ZodEffects.create; -exports.effect = effectsType; -exports.transformer = effectsType; -const optionalType = ZodOptional.create; -exports.optional = optionalType; -const nullableType = ZodNullable.create; -exports.nullable = nullableType; -const preprocessType = ZodEffects.createWithPreprocess; -exports.preprocess = preprocessType; -const pipelineType = ZodPipeline.create; -exports.pipeline = pipelineType; -const ostring = () => stringType().optional(); -exports.ostring = ostring; -const onumber = () => numberType().optional(); -exports.onumber = onumber; -const oboolean = () => booleanType().optional(); -exports.oboolean = oboolean; -exports.coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), -}; -exports.NEVER = parseUtil_1.INVALID; - - -/***/ }), - -/***/ 1436: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; -const util_1 = __nccwpck_require__(5462); -exports.ZodIssueCode = util_1.util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); -const quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -exports.quotelessJson = quotelessJson; -class ZodError extends Error { - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - get errors() { - return this.issues; - } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - // if (typeof el === "string") { - // curr[el] = curr[el] || { _errors: [] }; - // } else if (typeof el === "number") { - // const errorArray: any = []; - // errorArray._errors = []; - // curr[el] = curr[el] || errorArray; - // } - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -exports.ZodError = ZodError; -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - - -/***/ }), - -/***/ 5152: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; -const en_1 = __importDefault(__nccwpck_require__(3487)); -exports.defaultErrorMap = en_1.default; -let overrideErrorMap = en_1.default; -function setErrorMap(map) { - overrideErrorMap = map; -} -exports.setErrorMap = setErrorMap; -function getErrorMap() { - return overrideErrorMap; -} -exports.getErrorMap = getErrorMap; - - -/***/ }), - -/***/ 8217: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -__exportStar(__nccwpck_require__(5152), exports); -__exportStar(__nccwpck_require__(677), exports); -__exportStar(__nccwpck_require__(5352), exports); -__exportStar(__nccwpck_require__(5462), exports); -__exportStar(__nccwpck_require__(8111), exports); -__exportStar(__nccwpck_require__(1436), exports); - - -/***/ }), - -/***/ 1871: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.errorUtil = void 0; -var errorUtil; -(function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; -})(errorUtil = exports.errorUtil || (exports.errorUtil = {})); - - -/***/ }), - -/***/ 677: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; -const errors_1 = __nccwpck_require__(5152); -const en_1 = __importDefault(__nccwpck_require__(3487)); -const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message, - }; - } - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage, - }; -}; -exports.makeIssue = makeIssue; -exports.EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = (0, errors_1.getErrorMap)(); - const issue = (0, exports.makeIssue)({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, - ctx.schemaErrorMap, - overrideMap, - overrideMap === en_1.default ? undefined : en_1.default, // then global default map - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); -} -exports.addIssueToContext = addIssueToContext; -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return exports.INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return exports.INVALID; - if (value.status === "aborted") - return exports.INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && - (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -exports.ParseStatus = ParseStatus; -exports.INVALID = Object.freeze({ - status: "aborted", -}); -const DIRTY = (value) => ({ status: "dirty", value }); -exports.DIRTY = DIRTY; -const OK = (value) => ({ status: "valid", value }); -exports.OK = OK; -const isAborted = (x) => x.status === "aborted"; -exports.isAborted = isAborted; -const isDirty = (x) => x.status === "dirty"; -exports.isDirty = isDirty; -const isValid = (x) => x.status === "valid"; -exports.isValid = isValid; -const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; -exports.isAsync = isAsync; - - -/***/ }), - -/***/ 5352: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); - - -/***/ }), - -/***/ 5462: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; -var util; -(function (util) { - util.assertEqual = (val) => val; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban - ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array - .map((val) => (typeof val === "string" ? `'${val}'` : val)) - .join(separator); - } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util = exports.util || (exports.util = {})); -var objectUtil; -(function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, // second overwrites first - }; - }; -})(objectUtil = exports.objectUtil || (exports.objectUtil = {})); -exports.ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return exports.ZodParsedType.undefined; - case "string": - return exports.ZodParsedType.string; - case "number": - return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; - case "boolean": - return exports.ZodParsedType.boolean; - case "function": - return exports.ZodParsedType.function; - case "bigint": - return exports.ZodParsedType.bigint; - case "symbol": - return exports.ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return exports.ZodParsedType.array; - } - if (data === null) { - return exports.ZodParsedType.null; - } - if (data.then && - typeof data.then === "function" && - data.catch && - typeof data.catch === "function") { - return exports.ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return exports.ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return exports.ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return exports.ZodParsedType.date; - } - return exports.ZodParsedType.object; - default: - return exports.ZodParsedType.unknown; - } -}; -exports.getParsedType = getParsedType; - - -/***/ }), - -/***/ 7616: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.z = void 0; -const z = __importStar(__nccwpck_require__(8217)); -exports.z = z; -__exportStar(__nccwpck_require__(8217), exports); -exports["default"] = z; - - -/***/ }), - -/***/ 3487: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const util_1 = __nccwpck_require__(5462); -const ZodError_1 = __nccwpck_require__(1436); -const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodError_1.ZodIssueCode.invalid_type: - if (issue.received === util_1.ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodError_1.ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; - break; - case ZodError_1.ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; - break; - case ZodError_1.ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; - break; - case ZodError_1.ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodError_1.ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodError_1.ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodError_1.ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodError_1.ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } - else { - util_1.util.assertNever(issue.validation); - } - } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } - else { - message = "Invalid"; - } - break; - case ZodError_1.ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - 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}`; - 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))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact - ? `exactly` - : issue.inclusive - ? `less than or equal to` - : `less than`} ${issue.maximum}`; - 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))}`; - else - message = "Invalid input"; - break; - case ZodError_1.ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodError_1.ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodError_1.ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodError_1.ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util_1.util.assertNever(issue); - } - return { message }; -}; -exports["default"] = errorMap; - - -/***/ }), - -/***/ 8111: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _ZodEnum_cache, _ZodNativeEnum_cache; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodReadonly = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.datetimeRegex = exports.ZodType = void 0; -exports.NEVER = exports["void"] = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports["null"] = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports["instanceof"] = exports["function"] = exports["enum"] = exports.effect = exports.discriminatedUnion = exports.date = void 0; -const errors_1 = __nccwpck_require__(5152); -const errorUtil_1 = __nccwpck_require__(1871); -const parseUtil_1 = __nccwpck_require__(677); -const util_1 = __nccwpck_require__(5462); -const ZodError_1 = __nccwpck_require__(1436); +const errors_1 = __nccwpck_require__(5681); +const errorUtil_1 = __nccwpck_require__(3750); +const parseUtil_1 = __nccwpck_require__(4749); +const util_1 = __nccwpck_require__(3306); +const ZodError_1 = __nccwpck_require__(8872); class ParseInputLazyPath { constructor(parent, value, path, key) { this._cachedPath = []; @@ -34151,7 +29787,7 @@ exports.NEVER = parseUtil_1.INVALID; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.urlSchema = void 0; const tslib_1 = __nccwpck_require__(36); -const zod_1 = tslib_1.__importDefault(__nccwpck_require__(7616)); +const zod_1 = tslib_1.__importDefault(__nccwpck_require__(6762)); exports.urlSchema = zod_1.default.string().url(); @@ -34230,6 +29866,9 @@ function validateInput() { } validatedEnvironmentVariables = result.data; } + // NOTE: Returns an empty string if the value is not defined. + const rawQawolfBaseUrl = core.getInput("qawolf-base-url").trim(); + const qawolfBaseUrl = rawQawolfBaseUrl || undefined; return { apiKey: qawolfApiKey, deployConfig: { @@ -34242,6 +29881,7 @@ function validateInput() { variables: validatedEnvironmentVariables, }, isValid: true, + qawolfBaseUrl, }; } @@ -36104,8 +31744,8 @@ module.exports = parseParams Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(36); -tslib_1.__exportStar(__nccwpck_require__(3907), exports); tslib_1.__exportStar(__nccwpck_require__(9253), exports); +tslib_1.__exportStar(__nccwpck_require__(3907), exports); //# sourceMappingURL=index.js.map /***/ }), @@ -36117,7 +31757,7 @@ tslib_1.__exportStar(__nccwpck_require__(9253), exports); Object.defineProperty(exports, "__esModule", ({ value: true })); exports.fetchCiGreenlightStatus = fetchCiGreenlightStatus; -async function fetchCiGreenlightStatus({ serviceBase, apiKey }, { runId, }, { fetch: localFetch }) { +async function fetchCiGreenlightStatus({ apiKey, serviceBase }, { runId, }, { fetch: localFetch }) { try { const resp = await localFetch(new URL(`/api/v0/ci-greenlight/${encodeURIComponent(runId)}`, serviceBase), { headers: { @@ -36260,6 +31900,50 @@ async function postDeploySuccess({ apiKey, serviceBase }, { branch, commitUrl, d /***/ }), +/***/ 8419: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.callGenerateSignedUrlForRunInputsExecutablesStorage = callGenerateSignedUrlForRunInputsExecutablesStorage; +async function callGenerateSignedUrlForRunInputsExecutablesStorage({ apiKey, serviceBase }, { destinationFilePath }, { fetch: localFetch }) { + try { + const response = await localFetch(new URL(`${serviceBase}/api/v0/run-inputs-executables-signed-urls?file=${encodeURIComponent(destinationFilePath)}`), { + headers: { + Authorization: `Bearer ${apiKey}`, + "Content-Type": "application/json", + }, + method: "GET", + }); + if (response.status === 200) { + const json = (await response.json()); + return { + fileLocation: json.fileLocation, + httpStatus: response.status, + playgroundFileLocation: json.playgroundFileLocation, + signedUrl: json.signedUrl, + success: true, + }; + } + return { + errorMessage: await response.text(), + httpStatus: response.status, + success: false, + }; + } + catch (e) { + return { + errorMessage: "Network error, aborting request to generate signed URL", + httpStatus: 0, + success: false, + }; + } +} +//# sourceMappingURL=generate-signed-url-for-run-inputs-executables.js.map + +/***/ }), + /***/ 8048: /***/ ((__unused_webpack_module, exports) => { @@ -36280,21 +31964,22 @@ async function callGenerateSignedUrlForTempTeamStorage({ apiKey, serviceBase }, const json = (await response.json()); return { fileLocation: json.fileLocation, + httpStatus: response.status, playgroundFileLocation: json.playgroundFileLocation, signedUrl: json.signedUrl, success: true, }; } - else { - const error = await response.text(); - console.log(`ERROR: ${error}`); - return { - success: false, - }; - } + return { + errorMessage: await response.text(), + httpStatus: response.status, + success: false, + }; } catch (e) { return { + errorMessage: "Network error, aborting request to generate signed URL", + httpStatus: 0, success: false, }; } @@ -36316,7 +32001,7 @@ class GraphQLBadResponseError extends Error { this.name = "GraphQLBadResponseError"; } } -async function qawolfGraphql({ deps: { fetch: localFetch, log }, apiConfig: { apiKey, serviceBase }, name, query: queryGql, variables, }) { +async function qawolfGraphql({ apiConfig: { apiKey, serviceBase }, deps: { fetch: localFetch, log }, name, query: queryGql, variables, }) { try { const response = await localFetch(new URL(`/api/graphql`, serviceBase), { body: JSON.stringify({ @@ -36338,9 +32023,8 @@ async function qawolfGraphql({ deps: { fetch: localFetch, log }, apiConfig: { ap } if ("errors" in rawBody) { const extensionsCodes = rawBody.errors.flatMap((error) => error.extensions?.map?.((ext) => ext.code) ?? []); - for (const error of rawBody.errors) { + for (const error of rawBody.errors) log.warn(`❌ [GraphQL] error: ${error.message}`); - } const isUnauthenticated = extensionsCodes.includes("UNAUTHENTICATED"); const isForbidden = extensionsCodes.includes("FORBIDDEN"); const isInternal = extensionsCodes.includes("INTERNAL"); @@ -36392,8 +32076,9 @@ const mutationName = "notifyVCSBranchBuildDeployed"; const mutationGql = ` mutation NotifyVCSBranchBuildDeployed( $headVcsCommitId: String!, + $baseVcsBranch: String, $headEnvironmentVariablesJson: String!, - $baseEnvironmentAlias: String!, + $baseEnvironmentAlias: String, $headEnvironmentAlias: String!, $concurrencyLimit: Int, $headEnvironmentName: String, @@ -36403,6 +32088,7 @@ mutation NotifyVCSBranchBuildDeployed( ) { ${mutationName}( headVcsCommitId: $headVcsCommitId, + baseVcsBranch: $baseVcsBranch, headEnvironmentVariablesJson: $headEnvironmentVariablesJson, baseEnvironmentAlias: $baseEnvironmentAlias, headEnvironmentAlias: $headEnvironmentAlias, @@ -36419,14 +32105,15 @@ mutation NotifyVCSBranchBuildDeployed( runId } }`; -async function callNotifyVCSBranchBuildDeployedMutation(deps, apiConfig, { baseEnvironmentAlias, concurrencyLimit, headEnvironmentAlias, headEnvironmentName, headEnvironmentVariables, headVcsCommitId, headVcsCommitUrl, headVcsBranch, pullOrMergeRequestNumber, }) { +async function callNotifyVCSBranchBuildDeployedMutation(deps, apiConfig, { baseEnvironmentAlias, baseVcsBranch, concurrencyLimit, headEnvironmentAlias, headEnvironmentName, headEnvironmentVariables, headVcsBranch, headVcsCommitId, headVcsCommitUrl, pullOrMergeRequestNumber, }) { return (0, graphql_1.qawolfGraphql)({ apiConfig, deps, name: mutationName, query: mutationGql, variables: { - baseEnvironmentAlias, + baseEnvironmentAlias: baseEnvironmentAlias ?? null, + baseVcsBranch: baseVcsBranch ?? null, concurrencyLimit: concurrencyLimit ?? null, headEnvironmentAlias, headEnvironmentName, @@ -36486,21 +32173,21 @@ exports.callNotifyVCSBranchMergeCompletedMutation = callNotifyVCSBranchMergeComp const graphql_1 = __nccwpck_require__(406); const mutationName = "notifyVCSBranchMergeCompleted"; const mutationGql = ` -mutation NotifyVCSBranchMergeCompleted($baseEnvironmentAlias: String!, $headEnvironmentAlias: String!) { +mutation NotifyVCSBranchMergeCompleted($baseEnvironmentAlias: String, $headEnvironmentAlias: String!) { ${mutationName}(baseEnvironmentAlias: $baseEnvironmentAlias, headEnvironmentAlias: $headEnvironmentAlias) { outcome failureCode failureDetails } }`; -async function callNotifyVCSBranchMergeCompletedMutation(deps, apiConfig, { headEnvironmentAlias, baseEnvironmentAlias, }) { +async function callNotifyVCSBranchMergeCompletedMutation(deps, apiConfig, { baseEnvironmentAlias, headEnvironmentAlias, }) { return (0, graphql_1.qawolfGraphql)({ apiConfig, deps, name: mutationName, query: mutationGql, variables: { - baseEnvironmentAlias, + baseEnvironmentAlias: baseEnvironmentAlias ?? null, headEnvironmentAlias, }, // The type coercion highlights that we don't have runtime schema validation @@ -36589,8 +32276,9 @@ async function attemptNotifyDeploy(deps, apiConfig, config) { } if (responseState.failureReason === "network-error") log.error(`đŸšĢ Network error from deploy_success, aborting.`); - else if (responseState.failureReason === "5XX-server-error") + else if (responseState.failureReason === "5XX-server-error") { log.error(`đŸšĢ Server error from deploy_success (status ${responseState.httpStatus}), aborting. Please contact support.`); + } else if (responseState.failureReason === "4XX-client-error") { log.error(`đŸšĢ Unrecoverable error from deploy_success (status ${responseState.httpStatus}), aborting. Please contact support.`); } @@ -36600,9 +32288,8 @@ async function attemptNotifyDeploy(deps, apiConfig, config) { else if (responseState.failureReason === "401-unauthorized") { log.error(`đŸšĢ Unauthorized error from deploy_success (status ${responseState.httpStatus}), aborting. Please contact support.`); } - else { + else (0, utils_1.assertType)(responseState); - } if (responseState.failureReason === "network-error") { return { abortReason: "network-error", @@ -36626,7 +32313,60 @@ async function attemptNotifyDeploy(deps, apiConfig, config) { /***/ }), -/***/ 5592: +/***/ 7549: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.generateSignedUrlForRunInputsExecutablesStorage = generateSignedUrlForRunInputsExecutablesStorage; +const generate_signed_url_for_run_inputs_executables_1 = __nccwpck_require__(8419); +async function generateSignedUrlForRunInputsExecutablesStorage(deps, apiConfig, config) { + const { log } = deps; + if (!config.destinationFilePath) { + log.error(`đŸšĢ destinationFilePath is a required config parameter`); + return { + abortReason: "sdk-argument-validation-failed", + success: false, + }; + } + const responseState = await (0, generate_signed_url_for_run_inputs_executables_1.callGenerateSignedUrlForRunInputsExecutablesStorage)(apiConfig, config, deps); + if (!responseState.success) { + let abortReason = "XXX-other-http-code"; + if (responseState.httpStatus >= 500) { + abortReason = "5XX-server-error"; + log.error(`đŸšĢ Unrecoverable error (status ${responseState.httpStatus}) when generating signed upload url: aborting.`); + } + else { + if (responseState.httpStatus === 400) + abortReason = "400-invalid-request"; + else if (responseState.httpStatus === 401) + abortReason = "401-invalid-credentials"; + else if (responseState.httpStatus === 403) + abortReason = "403-forbidden"; + else if (responseState.httpStatus === 0) + abortReason = "client-network-error"; + log.error(`đŸšĢ Unrecoverable error (status ${responseState.httpStatus}) when generating signed upload url: ${responseState.errorMessage ? `${responseState.errorMessage}.` : ""} aborting.`); + } + return { + abortReason, + httpStatus: responseState.httpStatus, + success: false, + }; + } + log.info(`✅ Generated Signed Upload URL: ${responseState.signedUrl}.`); + return { + fileLocation: responseState.fileLocation, + playgroundFileLocation: responseState.playgroundFileLocation, + success: true, + uploadUrl: responseState.signedUrl, + }; +} +//# sourceMappingURL=generate-signed-url-for-run-inputs-executables.js.map + +/***/ }), + +/***/ 2160: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -36638,12 +32378,34 @@ async function generateSignedUrlForTempTeamStorage(deps, apiConfig, config) { const { log } = deps; if (!config.destinationFilePath) { log.error(`đŸšĢ destinationFilePath is a required config parameter`); - return { success: false }; + return { + abortReason: "sdk-argument-validation-failed", + success: false, + }; } const responseState = await (0, generate_signed_url_for_team_storage_1.callGenerateSignedUrlForTempTeamStorage)(apiConfig, config, deps); if (!responseState.success) { - log.error(`đŸšĢ Failed to generate signed URL for team storage. Please contact support.`); - return { success: false }; + let abortReason = "XXX-other-http-code"; + if (responseState.httpStatus >= 500) { + abortReason = "5XX-server-error"; + log.error(`đŸšĢ Unrecoverable error (status ${responseState.httpStatus}) when generating signed upload url: aborting.`); + } + else { + if (responseState.httpStatus === 400) + abortReason = "400-invalid-request"; + else if (responseState.httpStatus === 401) + abortReason = "401-invalid-credentials"; + else if (responseState.httpStatus === 403) + abortReason = "403-forbidden"; + else if (responseState.httpStatus === 0) + abortReason = "client-network-error"; + log.error(`đŸšĢ Unrecoverable error (status ${responseState.httpStatus}) when generating signed upload url: ${responseState.errorMessage ? `${responseState.errorMessage}.` : ""} aborting.`); + } + return { + abortReason, + httpStatus: responseState.httpStatus, + success: false, + }; } log.info(`✅ Generated Signed Upload URL: ${responseState.signedUrl}.`); return { @@ -36685,7 +32447,7 @@ const findOrCreateTrigger_1 = __nccwpck_require__(5562); const findRepositoryIdByName_1 = __nccwpck_require__(1202); const getEnvironmentVariablesFromEnvironment_1 = __nccwpck_require__(1035); const getTagsFromEnvironment_1 = __nccwpck_require__(931); -const createEnvironmentAction = async (deps, apiConfig, { branch, headRepoFullName, deploymentUrl, qaWolfTeamId, pr, variables, baseEnvironmentId, }) => { +const createEnvironmentAction = async (deps, apiConfig, { baseEnvironmentId, branch, deploymentUrl, headRepoFullName, pr, qaWolfTeamId, variables, }) => { deps.log.info("Creating environment for pull request..."); const environmentId = await (0, findOrCreateEnvironment_1.findOrCreateEnvironment)(deps, apiConfig, { baseEnvironmentId, @@ -36701,7 +32463,7 @@ const createEnvironmentAction = async (deps, apiConfig, { branch, headRepoFullNa : {}; if (typeof baseEnvironmentVariablesJSON !== "object") { deps.log.error("baseEnvironmentVariablesJSON is not an object"); - throw new Error("baseEnvironmentVariablesJSON is not an object"); + throw Error("baseEnvironmentVariablesJSON is not an object"); } const combinedEnvironmentVariables = { ...baseEnvironmentVariablesJSON, @@ -36843,7 +32605,9 @@ exports.deleteEnvironmentAction = deleteEnvironmentAction; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findOrCreateEnvironment = findOrCreateEnvironment; const constants_1 = __nccwpck_require__(9894); -async function findOrCreateEnvironment(deps, apiConfig, { branch, pr, qaWolfTeamId, baseEnvironmentId, }) { +// Migration debt, clean up when convenient +// eslint-disable-next-line @qawolf/restrict-names +async function findOrCreateEnvironment(deps, apiConfig, { baseEnvironmentId, branch, pr, qaWolfTeamId, }) { const retrievalResponse = await deps.fetch(constants_1.qawolfGraphQLEndpoint, { body: JSON.stringify({ query: ` @@ -36902,9 +32666,8 @@ async function findOrCreateEnvironment(deps, apiConfig, { branch, pr, qaWolfTeam }); const createionResponseJson = (await creationResponse.json()); deps.log.info(`Environment response: ${JSON.stringify(createionResponseJson)}`); - if (!createionResponseJson.data.createEnvironment.id) { + if (!createionResponseJson.data.createEnvironment.id) throw Error("Environment ID not found in response"); - } const multiBranchResponse = await deps.fetch(constants_1.qawolfGraphQLEndpoint, { body: JSON.stringify({ query: ` @@ -36929,9 +32692,8 @@ async function findOrCreateEnvironment(deps, apiConfig, { branch, pr, qaWolfTeam }); const multiBranchResponseJson = (await multiBranchResponse.json()); const hasMultipleBranches = multiBranchResponseJson.data.teamBranches.length > 1; - if (!hasMultipleBranches) { + if (!hasMultipleBranches) return createionResponseJson.data.createEnvironment.id; - } const sourceEnvironmentResponse = await deps.fetch(constants_1.qawolfGraphQLEndpoint, { body: JSON.stringify({ query: ` @@ -36957,9 +32719,8 @@ async function findOrCreateEnvironment(deps, apiConfig, { branch, pr, qaWolfTeam const sourceEnvironmentJson = (await sourceEnvironmentResponse.json()); const baseBranchId = sourceEnvironmentJson.data.environment.branchId; const targetBranchId = createionResponseJson.data.createEnvironment.branchId; - if (!baseBranchId) { + if (!baseBranchId) throw Error("Base branch ID not found in response"); - } deps.log.info(`Promoting workflows from branch ${baseBranchId} to ${targetBranchId}`); const promotionResponse = await deps.fetch(constants_1.qawolfGraphQLEndpoint, { body: JSON.stringify({ @@ -36987,9 +32748,8 @@ async function findOrCreateEnvironment(deps, apiConfig, { branch, pr, qaWolfTeam method: "post", }); const promotionResponseJson = await promotionResponse.json(); - if (!promotionResponseJson) { - throw new Error("Promotion failed"); - } + if (!promotionResponseJson) + throw Error("Promotion failed"); return createionResponseJson.data.createEnvironment.id; } //# sourceMappingURL=findOrCreateEnvironment.js.map @@ -37004,8 +32764,10 @@ async function findOrCreateEnvironment(deps, apiConfig, { branch, pr, qaWolfTeam Object.defineProperty(exports, "__esModule", ({ value: true })); exports.findOrCreateTrigger = findOrCreateTrigger; const constants_1 = __nccwpck_require__(9894); +// Migration debt, clean up when convenient +// eslint-disable-next-line @qawolf/restrict-names async function findOrCreateTrigger(deps, apiConfig, args) { - const { branch, environmentId, pr, repositoryId, qaWolfTeamId, tags } = args; + const { branch, environmentId, pr, qaWolfTeamId, repositoryId, tags } = args; const triggerName = `Deployments of ${pr ? `PR #${pr.number} - ${pr.title}` : `branch ${branch}`}`; const retrievalResponse = await deps.fetch(constants_1.qawolfGraphQLEndpoint, { body: JSON.stringify({ @@ -37089,9 +32851,8 @@ async function findOrCreateTrigger(deps, apiConfig, args) { const creationResponseJson = (await creationResponse.json()); deps.log.info(`Trigger response: ${JSON.stringify(creationResponseJson)}`); const triggerId = creationResponseJson.data?.createTrigger?.id; - if (!triggerId) { + if (!triggerId) throw Error("Trigger ID not found in response"); - } deps.log.info(`Trigger created with ID: ${triggerId}`); return triggerId; } @@ -37134,9 +32895,8 @@ async function findRepositoryIdByName(deps, apiConfig, { headRepoFullName, }) { const responseJson = (await response.json()); deps.log.info(`Repository response: ${JSON.stringify(responseJson)}`); const repositories = responseJson.data.codeHostingServiceRepositories; - if (!repositories[0]) { + if (!repositories[0]) return; - } return repositories[0].id; } //# sourceMappingURL=findRepositoryIdByName.js.map @@ -37179,9 +32939,8 @@ async function getEnvironmentIdForBranch(deps, apiConfig, branch) { const responseJson = (await response.json()); deps.log.info(`Trigger response: ${JSON.stringify(responseJson)}`); const triggers = responseJson.data.triggers; - if (!triggers || !triggers[0]) { + if (!triggers || !triggers[0]) throw Error(`No environment found for branch: ${branch}`); - } return triggers[0].environment_id; } //# sourceMappingURL=getEnvironmentIdForBranch.js.map @@ -37326,16 +33085,17 @@ const utils_1 = __nccwpck_require__(4793); // If you change these values, make sure you update the JSDoc // comments in the PollConfig type. const safeDefaults = { + abortOnSuperseded: false, maxRetries: 10, pollTimeout: 120 * 60 * 1000, retryInterval: 10 * 1000, runInProgressInterval: 30 * 1000, runUnderReviewInterval: 60 * 1000, }; -async function pollCiGreenlightStatus(deps, apiConfig, { runId, onRunStageChanged: onRunStageChanged = () => void 0, ...pollConfig }) { +async function pollCiGreenlightStatus(deps, apiConfig, { onRunStageChanged: onRunStageChanged = () => void 0, runId, ...pollConfig }) { let retries = 0; const { log } = deps; - const { maxRetries = safeDefaults.maxRetries, retryInterval = safeDefaults.retryInterval, runInProgressInterval = safeDefaults.runInProgressInterval, runUnderReviewInterval = safeDefaults.runUnderReviewInterval, pollTimeout = safeDefaults.pollTimeout, } = pollConfig; + const { abortOnSuperseded = safeDefaults.abortOnSuperseded, maxRetries = safeDefaults.maxRetries, pollTimeout = safeDefaults.pollTimeout, retryInterval = safeDefaults.retryInterval, runInProgressInterval = safeDefaults.runInProgressInterval, runUnderReviewInterval = safeDefaults.runUnderReviewInterval, } = pollConfig; let currentStatus = undefined; const startedAt = Date.now(); let hasTimedOut = false; @@ -37358,12 +33118,13 @@ async function pollCiGreenlightStatus(deps, apiConfig, { runId, onRunStageChange log.error(`đŸšĢ Unrecoverable error${responseState.httpStatus ? ` (status ${responseState.httpStatus})` : ""} from CI greenlight, aborting after ${maxRetries} attempts.`); - if (responseState.errorType === "network") + if (responseState.errorType === "network") { return { abortReason: "network-error", httpStatus: undefined, outcome: "aborted", }; + } let abortReason = "XXX-other-http-code"; if (responseState.errorType === "not-found") abortReason = "404-run-not-found"; @@ -37394,19 +33155,29 @@ async function pollCiGreenlightStatus(deps, apiConfig, { runId, onRunStageChange const previousStatus = currentStatus; currentStatus = greenlightStatus; if (!previousStatus || - previousStatus.runStage !== greenlightStatus.runStage) + previousStatus.runStage !== greenlightStatus.runStage) { try { await onRunStageChanged(greenlightStatus, previousStatus); } catch (e) { log.error(`Error in onRunStageChanged callback`, e); } + } const urlInfo = `See ${greenlightStatus.relevantRunUrl}`; const { greenlight, relevantRunId, relevantRunUrl, relevantRunWithBugsUrl, rootRunId, rootRunUrl, runStage, } = greenlightStatus; if (rootRunId !== relevantRunId) { - log.info(`Root run was superseded: + const supersedingDetails = ` - Root: ${rootRunUrl} - - Superseding: ${relevantRunUrl}`); + - Superseding: ${relevantRunUrl}`; + if (abortOnSuperseded) { + log.warn(`❌ Aborting due to superseded run (option 'abortOnSuperseded' is enabled).${supersedingDetails}`); + return { + abortReason: "superseded-run", + httpStatus: undefined, + outcome: "aborted", + }; + } + log.info(`Root run was superseded:${supersedingDetails}`); } if (runStage === "completed") { const { blockingBugsCount, blockingBugUrls = [], nonBlockingBugsCount, nonBlockingBugUrls = [], } = greenlightStatus; @@ -37459,10 +33230,8 @@ async function pollCiGreenlightStatus(deps, apiConfig, { runId, onRunStageChange log.info(`đŸ•ĩī¸ Run is under review... ${urlInfo}`); await (0, utils_1.sleep)(runUnderReviewInterval); } - else { - (0, utils_1.assertType)(runStage); - throw new Error(`Unexpected run stage: ${runStage}`); - } + else + throw Error(`Unexpected run stage: ${runStage}`); } log.warn(`❌ Poll timed out after ${pollTimeout / 1000}s. Aborting...`); return { @@ -37489,9 +33258,9 @@ const serviceBase_1 = __nccwpck_require__(1919); const notify_vcs_branch_build_deployed_1 = __nccwpck_require__(3385); const notify_vcs_branch_merge_canceled_1 = __nccwpck_require__(6093); const notify_vcs_branch_merge_completed_1 = __nccwpck_require__(7569); -tslib_1.__exportStar(__nccwpck_require__(8315), exports); tslib_1.__exportStar(__nccwpck_require__(5985), exports); -function makeVCSBranchTestingSDK({ apiKey, serviceBase = serviceBase_1.defaultServiceBase, }, { log = log_1.defaultLogDriver, fetch = fetch_1.defaultFetch, } = {}) { +tslib_1.__exportStar(__nccwpck_require__(8315), exports); +function makeVCSBranchTestingSDK({ apiKey, serviceBase = serviceBase_1.defaultServiceBase, }, { fetch = fetch_1.defaultFetch, log = log_1.defaultLogDriver, } = {}) { const deps = { fetch, log }; const apiConfig = { apiKey, serviceBase }; return { @@ -37538,7 +33307,7 @@ function arbitraryStringToEnvironmentAlias(arbitraryString) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.domainFailureToAbortResult = domainFailureToAbortResult; const utils_1 = __nccwpck_require__(4793); -function domainFailureToAbortResult({ log, result, methodName, }) { +function domainFailureToAbortResult({ log, methodName, result, }) { switch (result.failureCode) { case "run-creation-failed": log.error(`❌ [${methodName}] Run creation failed: ${result.failureDetails}. Aborting.`); @@ -37584,7 +33353,7 @@ function domainFailureToAbortResult({ log, result, methodName, }) { }; default: (0, utils_1.assertType)(result.failureCode); - throw new Error(`[${methodName}] Unreachable code detected. This is a bug.`); + throw Error(`[${methodName}] Unreachable code detected. This is a bug.`); } } //# sourceMappingURL=domain-failure.js.map @@ -37618,7 +33387,7 @@ function graphQLErrorToAbortResult({ graphQLPayload, log, methodName, }) { return { abortReason: "invalid-input", outcome: "aborted" }; default: (0, utils_1.assertType)(graphQLPayload.errorCode); - throw new Error("Unreachable code detected. This is a bug."); + throw Error("Unreachable code detected. This is a bug."); } } //# sourceMappingURL=graphql-error.js.map @@ -37633,7 +33402,7 @@ function graphQLErrorToAbortResult({ graphQLPayload, log, methodName, }) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.retryWithExponentialBackoff = retryWithExponentialBackoff; const utils_1 = __nccwpck_require__(4793); -async function retryWithExponentialBackoff({ maxRetries, runOnce, log, methodName, retriableAbortReasons, }) { +async function retryWithExponentialBackoff({ log, maxRetries, methodName, retriableAbortReasons, runOnce, }) { let attemptNumber = 0; let result; do { @@ -37642,9 +33411,8 @@ async function retryWithExponentialBackoff({ maxRetries, runOnce, log, methodNam result = await runOnce(); // If success or non-recoverable error, return immediately if (result.outcome === "success" || - !retriableAbortReasons.includes(result.abortReason)) { + !retriableAbortReasons.includes(result.abortReason)) return result; - } // Exit if max retries reached if (attemptNumber >= maxRetries + 1) return result; @@ -37672,23 +33440,15 @@ const domain_failure_1 = __nccwpck_require__(4435); const graphql_error_1 = __nccwpck_require__(6852); const retry_1 = __nccwpck_require__(9358); async function runNotifyVCSBranchBuildDeployedOnce(deps, apiConfig, input) { - const { baseEnvironmentsMapping, baseVcsBranch, headEnvironmentAlias, headEnvironmentName, headEnvironmentVariables, headVcsCommitId, concurrencyLimit, headVcsCommitUrl, headVcsBranch, pullOrMergeRequestNumber, } = input; + const { baseEnvironmentsMapping, baseVcsBranch, concurrencyLimit, headEnvironmentAlias, headEnvironmentName, headEnvironmentVariables, headVcsBranch, headVcsCommitId, headVcsCommitUrl, pullOrMergeRequestNumber, } = input; const log = deps.log; - const baseEnvironmentAlias = baseEnvironmentsMapping.find((mapping) => mapping.vcsBranch === baseVcsBranch)?.environmentAlias; - if (baseEnvironmentAlias === undefined) { - log.error(`❌ [notifyVCSBranchBuildDeployed] Could not find a base environment for VCS branch '${baseVcsBranch}'. Make sure you provide ` + - "a mapping for this base branch in the 'baseEnvironmentsMapping' field."); - return { - abortReason: "missing-vcs-branch-to-environment-alias-mapping", - outcome: "aborted", - }; - } + const baseEnvironmentAlias = baseEnvironmentsMapping?.find((mapping) => mapping.vcsBranch === baseVcsBranch)?.environmentAlias; let finalConcurrencyLimit = concurrencyLimit; if (typeof concurrencyLimit === "number") { - if (concurrencyLimit === Infinity) { + if (concurrencyLimit === Infinity) finalConcurrencyLimit = 0; - } - else if (isNaN(concurrencyLimit) || !Number.isInteger(concurrencyLimit)) { + else if (Number.isNaN(concurrencyLimit) || + !Number.isInteger(concurrencyLimit)) { log.error(`❌ [notifyVCSBranchBuildDeployed] Invalid concurrency limit '${concurrencyLimit}'. Must be a positive integer.`); return { abortReason: "invalid-input", @@ -37705,6 +33465,7 @@ async function runNotifyVCSBranchBuildDeployedOnce(deps, apiConfig, input) { } const resp = await (0, notify_vcs_branch_build_deployed_mutation_1.callNotifyVCSBranchBuildDeployedMutation)(deps, apiConfig, { baseEnvironmentAlias, + baseVcsBranch, concurrencyLimit: finalConcurrencyLimit, headEnvironmentAlias, headEnvironmentName, @@ -37829,14 +33590,9 @@ const retry_1 = __nccwpck_require__(9358); async function runNotifyVCSBranchMergeCompletedOnce(deps, apiConfig, input) { const log = deps.log; const { baseEnvironmentsMapping, baseVcsBranch: vcsBaseBranch } = input; - const baseEnvironmentAlias = baseEnvironmentsMapping.find((mapping) => mapping.vcsBranch === vcsBaseBranch)?.environmentAlias; + const baseEnvironmentAlias = baseEnvironmentsMapping?.find((mapping) => mapping.vcsBranch === vcsBaseBranch)?.environmentAlias; if (baseEnvironmentAlias === undefined) { - log.error(`❌ [notifyVCSBranchMergeCompleted] Could not find a base environment for VCS branch '${vcsBaseBranch}'. Make sure you provide ` + - "a mapping for this base branch in the 'baseEnvironmentsMapping' field."); - return { - abortReason: "missing-vcs-branch-to-environment-alias-mapping", - outcome: "aborted", - }; + log.info(`ℹī¸ [notifyVCSBranchMergeCompleted] Could not find a base environment for VCS branch '${vcsBaseBranch}'. Fall back to use the default base environment`); } const resp = await (0, notify_vcs_branch_merge_completed_mutation_1.callNotifyVCSBranchMergeCompletedMutation)(deps, apiConfig, { baseEnvironmentAlias, @@ -37903,13 +33659,14 @@ const fetch_1 = __nccwpck_require__(3704); const log_1 = __nccwpck_require__(4734); const serviceBase_1 = __nccwpck_require__(1919); const attempt_deploy_1 = __nccwpck_require__(289); -const generate_signed_url_for_team_storage_1 = __nccwpck_require__(5592); +const generate_signed_url_for_run_inputs_executables_1 = __nccwpck_require__(7549); +const generate_signed_url_for_team_storage_1 = __nccwpck_require__(2160); const index_1 = __nccwpck_require__(4500); const poll_ci_greenlight_1 = __nccwpck_require__(9218); const vcsBranchTesting_1 = __nccwpck_require__(2799); -function makeQaWolfSdk({ apiKey, serviceBase = serviceBase_1.defaultServiceBase, }, { log = log_1.defaultLogDriver, fetch = fetch_1.defaultFetch, } = {}) { +function makeQaWolfSdk({ apiKey, serviceBase = serviceBase_1.defaultServiceBase, }, { fetch = fetch_1.defaultFetch, log = log_1.defaultLogDriver, } = {}) { if (typeof fetch !== "function") { - throw new Error(`QA Wolf CI-SDK requires fetch to be defined. Make sure you are using NodeJS 18+, OR pass a fetch polyfill to the makeQaWolfSdk function. + throw Error(`QA Wolf CI-SDK requires fetch to be defined. Make sure you are using NodeJS 18+, OR pass a fetch polyfill to the makeQaWolfSdk function. We recommend 'undici' package for that purpose. See the Requirement section of our README for more guidance.`); } const deps = { @@ -37929,6 +33686,7 @@ We recommend 'undici' package for that purpose. See the Requirement section of o */ experimental_testPreview: index_1.testPreview.bind(null, deps, apiConfig), experimental_vcsBranchTesting: (0, vcsBranchTesting_1.makeVCSBranchTestingSDK)(apiConfig, deps), + generateSignedUrlForRunInputsExecutablesStorage: generate_signed_url_for_run_inputs_executables_1.generateSignedUrlForRunInputsExecutablesStorage.bind(null, deps, apiConfig), generateSignedUrlForTempTeamStorage: generate_signed_url_for_team_storage_1.generateSignedUrlForTempTeamStorage.bind(null, deps, apiConfig), pollCiGreenlightStatus: poll_ci_greenlight_1.pollCiGreenlightStatus.bind(null, deps, apiConfig), }; @@ -37977,9 +33735,9 @@ exports.buildFetchWithTimeout = buildFetchWithTimeout; Object.defineProperty(exports, "__esModule", ({ value: true })); const tslib_1 = __nccwpck_require__(36); -tslib_1.__exportStar(__nccwpck_require__(8053), exports); tslib_1.__exportStar(__nccwpck_require__(8362), exports); tslib_1.__exportStar(__nccwpck_require__(6650), exports); +tslib_1.__exportStar(__nccwpck_require__(8053), exports); //# sourceMappingURL=index.js.map /***/ }), @@ -38012,15 +33770,13 @@ exports.coreLogDriver = { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stringifyUnknown = stringifyUnknown; function stringifyUnknown(value) { - if (value === null || value === undefined) { + if (value === null || value === undefined) return ""; - } if (typeof value === "string") return value; if (value instanceof Error) { - if ("message" in value && typeof value.message === "string") { + if ("message" in value && typeof value.message === "string") return value.message; - } return value.toString(); } try { @@ -38043,7 +33799,7 @@ function stringifyUnknown(value) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.jsonEnvironmentsMappingSchema = exports.jsonEnvironmentVariablesSchema = void 0; const tslib_1 = __nccwpck_require__(36); -const zod_1 = tslib_1.__importDefault(__nccwpck_require__(9102)); +const zod_1 = tslib_1.__importDefault(__nccwpck_require__(6762)); const environmentVariablesSchema = zod_1.default.record(zod_1.default.string(), zod_1.default.string()); exports.jsonEnvironmentVariablesSchema = zod_1.default .string() @@ -38140,8 +33896,8 @@ async function runGitHubAction() { core.setFailed(`Action input is invalid: ${validationResult.error}`); return; } - const { deployConfig, apiKey } = validationResult; - const { attemptNotifyDeploy } = (0, ci_sdk_1.makeQaWolfSdk)({ apiKey }, { + const { apiKey, deployConfig, qawolfBaseUrl } = validationResult; + const { attemptNotifyDeploy } = (0, ci_sdk_1.makeQaWolfSdk)({ apiKey, serviceBase: qawolfBaseUrl }, { // Replace default log driver with core logging. log: ci_utils_1.coreLogDriver, }); diff --git a/package.json b/package.json index 8587293..85f8847 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@qawolf/notify-qawolf-on-deploy-action", - "version": "v1.0.2", + "version": "v1.0.3", "type": "commonjs", "main": "dist/index.js", "engines": { @@ -10,7 +10,8 @@ "build": "ncc build src/index.ts -o dist", "build:clean": "tsc --build --clean && rm -rf ./dist", "lint": "eslint . --ext js,jsx,mjs,ts,tsx --quiet && prettier --check .", - "lint:fix": "eslint . --ext js,jsx,mjs,ts,tsx --fix --quiet && prettier --write .", + "lint:fix": "eslint . --ext js,jsx,mjs,ts,tsx --fix --quiet && prettier --log-level=warn --write .", + "lint:warnings": "eslint . --ext js,jsx,mjs,ts,tsx", "test": "jest --passWithNoTests", "test:watch": "npm run test -- --watch", "tsc:check": "tsc" diff --git a/src/index.ts b/src/index.ts index 88b130b..7a1f1de 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ import * as core from "@actions/core"; + import { makeQaWolfSdk } from "@qawolf/ci-sdk"; import { coreLogDriver, stringifyUnknown } from "@qawolf/ci-utils"; @@ -11,9 +12,9 @@ async function runGitHubAction() { core.setFailed(`Action input is invalid: ${validationResult.error}`); return; } - const { deployConfig, apiKey } = validationResult; + const { apiKey, deployConfig, qawolfBaseUrl } = validationResult; const { attemptNotifyDeploy } = makeQaWolfSdk( - { apiKey }, + { apiKey, serviceBase: qawolfBaseUrl }, { // Replace default log driver with core logging. log: coreLogDriver, diff --git a/src/validateInput.ts b/src/validateInput.ts index 8e8eb75..5615737 100644 --- a/src/validateInput.ts +++ b/src/validateInput.ts @@ -1,4 +1,5 @@ import * as core from "@actions/core"; + import { type DeployConfig } from "@qawolf/ci-sdk"; import { type EnvironmentVariables, @@ -12,6 +13,7 @@ export function validateInput(): apiKey: string; deployConfig: Omit; isValid: true; + qawolfBaseUrl: string | undefined; } | { error: string; @@ -87,6 +89,10 @@ export function validateInput(): validatedEnvironmentVariables = result.data; } + // NOTE: Returns an empty string if the value is not defined. + const rawQawolfBaseUrl = core.getInput("qawolf-base-url").trim(); + const qawolfBaseUrl = rawQawolfBaseUrl || undefined; + return { apiKey: qawolfApiKey, deployConfig: { @@ -99,5 +105,6 @@ export function validateInput(): variables: validatedEnvironmentVariables, }, isValid: true, + qawolfBaseUrl, }; }