git-coco 0.14.8 → 0.14.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,7 @@ import prettyMilliseconds from 'pretty-ms';
18
18
  import { ChatAnthropic } from '@langchain/anthropic';
19
19
  import { ChatOllama } from '@langchain/ollama';
20
20
  import { ChatOpenAI } from '@langchain/openai';
21
- import { JsonOutputParser, BaseOutputParser } from '@langchain/core/output_parsers';
21
+ import { StructuredOutputParser, BaseOutputParser } from '@langchain/core/output_parsers';
22
22
  import { simpleGit } from 'simple-git';
23
23
  import pQueue from 'p-queue';
24
24
  import { Document, BaseDocumentTransformer } from '@langchain/core/documents';
@@ -55,7 +55,7 @@ import * as readline from 'readline';
55
55
  /**
56
56
  * Current build version from package.json
57
57
  */
58
- const BUILD_VERSION = "0.14.8";
58
+ const BUILD_VERSION = "0.14.10";
59
59
 
60
60
  const isInteractive = (config) => {
61
61
  return config?.mode === 'interactive' || !!config?.interactive;
@@ -710,6 +710,10 @@ const schema$1 = {
710
710
  "type": "number",
711
711
  "description": "Maximum number of tokens to generate in the completion. -1 returns as many tokens as possible given the prompt and the model's maximum context size."
712
712
  },
713
+ "maxCompletionTokens": {
714
+ "type": "number",
715
+ "description": "Maximum number of tokens to generate in the completion. -1 returns as many tokens as possible given the prompt and the model's maximum context size. Alias for `maxTokens` for reasoning models."
716
+ },
713
717
  "topP": {
714
718
  "type": "number",
715
719
  "description": "Total probability mass of tokens to consider at each step"
@@ -748,7 +752,8 @@ const schema$1 = {
748
752
  },
749
753
  "modelName": {
750
754
  "type": "string",
751
- "description": "Model name to use Alias for `model`"
755
+ "description": "Model name to use Alias for `model`",
756
+ "deprecated": "Use \"model\" instead."
752
757
  },
753
758
  "model": {
754
759
  "type": "string",
@@ -1776,75 +1781,4314 @@ class Logger {
1776
1781
  };
1777
1782
  return this;
1778
1783
  }
1779
- log(message, options = { color: 'blue' }) {
1780
- if (this.config?.silent) {
1781
- return this;
1784
+ log(message, options = { color: 'blue' }) {
1785
+ if (this.config?.silent) {
1786
+ return this;
1787
+ }
1788
+ let outputMessage = message;
1789
+ if (options.color) {
1790
+ outputMessage = chalk[options.color](outputMessage);
1791
+ }
1792
+ console.log(outputMessage);
1793
+ return this;
1794
+ }
1795
+ verbose(message, options = {}) {
1796
+ if (!this.config?.verbose || this.config?.silent) {
1797
+ return this;
1798
+ }
1799
+ this.log(message, options);
1800
+ return this;
1801
+ }
1802
+ startTimer() {
1803
+ this.timerStart = now();
1804
+ return this;
1805
+ }
1806
+ stopTimer(message, options = { color: 'yellow' }) {
1807
+ if (!this.config?.verbose || !this.timerStart || this.config?.silent) {
1808
+ return this;
1809
+ }
1810
+ const elapsedTime = prettyMilliseconds(now() - this.timerStart);
1811
+ let outputMessage = message ? `${message} (⏲ ${elapsedTime})` : `⏲ ${elapsedTime}`;
1812
+ if (options.color) {
1813
+ outputMessage = chalk[options.color](outputMessage);
1814
+ }
1815
+ console.log(outputMessage);
1816
+ return this;
1817
+ }
1818
+ startSpinner(message, options = { color: 'green' }) {
1819
+ if (this.config?.silent) {
1820
+ return this;
1821
+ }
1822
+ const spinnerMessage = options.color ? chalk[options.color](message) : message;
1823
+ this.spinner = ora(spinnerMessage).start();
1824
+ return this;
1825
+ }
1826
+ stopSpinner(message = '', options = { mode: 'succeed', color: 'green' }) {
1827
+ if (this.config?.silent) {
1828
+ return this;
1829
+ }
1830
+ const spinnerMessage = options?.color ? chalk[options.color](message) : message;
1831
+ this.spinner?.[options.mode || 'succeed'](spinnerMessage);
1832
+ this.spinner = null;
1833
+ return this;
1834
+ }
1835
+ }
1836
+
1837
+ function commandExecutor(handler) {
1838
+ return async (argv) => {
1839
+ const options = loadConfig(argv);
1840
+ const logger = new Logger(options);
1841
+ try {
1842
+ await handler(argv, logger);
1843
+ }
1844
+ catch (error) {
1845
+ logger.log('\nFailed to execute command', { color: 'yellow' });
1846
+ logger.verbose(`\nError: "${error.message}"`, { color: 'red' });
1847
+ logger.log('\nThanks for using coco, make it a great day! 👋🤖', { color: 'blue' });
1848
+ process.exit(0);
1849
+ }
1850
+ };
1851
+ }
1852
+
1853
+ var util;
1854
+ (function (util) {
1855
+ util.assertEqual = (val) => val;
1856
+ function assertIs(_arg) { }
1857
+ util.assertIs = assertIs;
1858
+ function assertNever(_x) {
1859
+ throw new Error();
1860
+ }
1861
+ util.assertNever = assertNever;
1862
+ util.arrayToEnum = (items) => {
1863
+ const obj = {};
1864
+ for (const item of items) {
1865
+ obj[item] = item;
1866
+ }
1867
+ return obj;
1868
+ };
1869
+ util.getValidEnumValues = (obj) => {
1870
+ const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
1871
+ const filtered = {};
1872
+ for (const k of validKeys) {
1873
+ filtered[k] = obj[k];
1874
+ }
1875
+ return util.objectValues(filtered);
1876
+ };
1877
+ util.objectValues = (obj) => {
1878
+ return util.objectKeys(obj).map(function (e) {
1879
+ return obj[e];
1880
+ });
1881
+ };
1882
+ util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
1883
+ ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
1884
+ : (object) => {
1885
+ const keys = [];
1886
+ for (const key in object) {
1887
+ if (Object.prototype.hasOwnProperty.call(object, key)) {
1888
+ keys.push(key);
1889
+ }
1890
+ }
1891
+ return keys;
1892
+ };
1893
+ util.find = (arr, checker) => {
1894
+ for (const item of arr) {
1895
+ if (checker(item))
1896
+ return item;
1897
+ }
1898
+ return undefined;
1899
+ };
1900
+ util.isInteger = typeof Number.isInteger === "function"
1901
+ ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
1902
+ : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
1903
+ function joinValues(array, separator = " | ") {
1904
+ return array
1905
+ .map((val) => (typeof val === "string" ? `'${val}'` : val))
1906
+ .join(separator);
1907
+ }
1908
+ util.joinValues = joinValues;
1909
+ util.jsonStringifyReplacer = (_, value) => {
1910
+ if (typeof value === "bigint") {
1911
+ return value.toString();
1912
+ }
1913
+ return value;
1914
+ };
1915
+ })(util || (util = {}));
1916
+ var objectUtil;
1917
+ (function (objectUtil) {
1918
+ objectUtil.mergeShapes = (first, second) => {
1919
+ return {
1920
+ ...first,
1921
+ ...second, // second overwrites first
1922
+ };
1923
+ };
1924
+ })(objectUtil || (objectUtil = {}));
1925
+ const ZodParsedType = util.arrayToEnum([
1926
+ "string",
1927
+ "nan",
1928
+ "number",
1929
+ "integer",
1930
+ "float",
1931
+ "boolean",
1932
+ "date",
1933
+ "bigint",
1934
+ "symbol",
1935
+ "function",
1936
+ "undefined",
1937
+ "null",
1938
+ "array",
1939
+ "object",
1940
+ "unknown",
1941
+ "promise",
1942
+ "void",
1943
+ "never",
1944
+ "map",
1945
+ "set",
1946
+ ]);
1947
+ const getParsedType = (data) => {
1948
+ const t = typeof data;
1949
+ switch (t) {
1950
+ case "undefined":
1951
+ return ZodParsedType.undefined;
1952
+ case "string":
1953
+ return ZodParsedType.string;
1954
+ case "number":
1955
+ return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
1956
+ case "boolean":
1957
+ return ZodParsedType.boolean;
1958
+ case "function":
1959
+ return ZodParsedType.function;
1960
+ case "bigint":
1961
+ return ZodParsedType.bigint;
1962
+ case "symbol":
1963
+ return ZodParsedType.symbol;
1964
+ case "object":
1965
+ if (Array.isArray(data)) {
1966
+ return ZodParsedType.array;
1967
+ }
1968
+ if (data === null) {
1969
+ return ZodParsedType.null;
1970
+ }
1971
+ if (data.then &&
1972
+ typeof data.then === "function" &&
1973
+ data.catch &&
1974
+ typeof data.catch === "function") {
1975
+ return ZodParsedType.promise;
1976
+ }
1977
+ if (typeof Map !== "undefined" && data instanceof Map) {
1978
+ return ZodParsedType.map;
1979
+ }
1980
+ if (typeof Set !== "undefined" && data instanceof Set) {
1981
+ return ZodParsedType.set;
1982
+ }
1983
+ if (typeof Date !== "undefined" && data instanceof Date) {
1984
+ return ZodParsedType.date;
1985
+ }
1986
+ return ZodParsedType.object;
1987
+ default:
1988
+ return ZodParsedType.unknown;
1989
+ }
1990
+ };
1991
+
1992
+ const ZodIssueCode = util.arrayToEnum([
1993
+ "invalid_type",
1994
+ "invalid_literal",
1995
+ "custom",
1996
+ "invalid_union",
1997
+ "invalid_union_discriminator",
1998
+ "invalid_enum_value",
1999
+ "unrecognized_keys",
2000
+ "invalid_arguments",
2001
+ "invalid_return_type",
2002
+ "invalid_date",
2003
+ "invalid_string",
2004
+ "too_small",
2005
+ "too_big",
2006
+ "invalid_intersection_types",
2007
+ "not_multiple_of",
2008
+ "not_finite",
2009
+ ]);
2010
+ const quotelessJson = (obj) => {
2011
+ const json = JSON.stringify(obj, null, 2);
2012
+ return json.replace(/"([^"]+)":/g, "$1:");
2013
+ };
2014
+ class ZodError extends Error {
2015
+ constructor(issues) {
2016
+ super();
2017
+ this.issues = [];
2018
+ this.addIssue = (sub) => {
2019
+ this.issues = [...this.issues, sub];
2020
+ };
2021
+ this.addIssues = (subs = []) => {
2022
+ this.issues = [...this.issues, ...subs];
2023
+ };
2024
+ const actualProto = new.target.prototype;
2025
+ if (Object.setPrototypeOf) {
2026
+ // eslint-disable-next-line ban/ban
2027
+ Object.setPrototypeOf(this, actualProto);
2028
+ }
2029
+ else {
2030
+ this.__proto__ = actualProto;
2031
+ }
2032
+ this.name = "ZodError";
2033
+ this.issues = issues;
2034
+ }
2035
+ get errors() {
2036
+ return this.issues;
2037
+ }
2038
+ format(_mapper) {
2039
+ const mapper = _mapper ||
2040
+ function (issue) {
2041
+ return issue.message;
2042
+ };
2043
+ const fieldErrors = { _errors: [] };
2044
+ const processError = (error) => {
2045
+ for (const issue of error.issues) {
2046
+ if (issue.code === "invalid_union") {
2047
+ issue.unionErrors.map(processError);
2048
+ }
2049
+ else if (issue.code === "invalid_return_type") {
2050
+ processError(issue.returnTypeError);
2051
+ }
2052
+ else if (issue.code === "invalid_arguments") {
2053
+ processError(issue.argumentsError);
2054
+ }
2055
+ else if (issue.path.length === 0) {
2056
+ fieldErrors._errors.push(mapper(issue));
2057
+ }
2058
+ else {
2059
+ let curr = fieldErrors;
2060
+ let i = 0;
2061
+ while (i < issue.path.length) {
2062
+ const el = issue.path[i];
2063
+ const terminal = i === issue.path.length - 1;
2064
+ if (!terminal) {
2065
+ curr[el] = curr[el] || { _errors: [] };
2066
+ // if (typeof el === "string") {
2067
+ // curr[el] = curr[el] || { _errors: [] };
2068
+ // } else if (typeof el === "number") {
2069
+ // const errorArray: any = [];
2070
+ // errorArray._errors = [];
2071
+ // curr[el] = curr[el] || errorArray;
2072
+ // }
2073
+ }
2074
+ else {
2075
+ curr[el] = curr[el] || { _errors: [] };
2076
+ curr[el]._errors.push(mapper(issue));
2077
+ }
2078
+ curr = curr[el];
2079
+ i++;
2080
+ }
2081
+ }
2082
+ }
2083
+ };
2084
+ processError(this);
2085
+ return fieldErrors;
2086
+ }
2087
+ static assert(value) {
2088
+ if (!(value instanceof ZodError)) {
2089
+ throw new Error(`Not a ZodError: ${value}`);
2090
+ }
2091
+ }
2092
+ toString() {
2093
+ return this.message;
2094
+ }
2095
+ get message() {
2096
+ return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
2097
+ }
2098
+ get isEmpty() {
2099
+ return this.issues.length === 0;
2100
+ }
2101
+ flatten(mapper = (issue) => issue.message) {
2102
+ const fieldErrors = {};
2103
+ const formErrors = [];
2104
+ for (const sub of this.issues) {
2105
+ if (sub.path.length > 0) {
2106
+ fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
2107
+ fieldErrors[sub.path[0]].push(mapper(sub));
2108
+ }
2109
+ else {
2110
+ formErrors.push(mapper(sub));
2111
+ }
2112
+ }
2113
+ return { formErrors, fieldErrors };
2114
+ }
2115
+ get formErrors() {
2116
+ return this.flatten();
2117
+ }
2118
+ }
2119
+ ZodError.create = (issues) => {
2120
+ const error = new ZodError(issues);
2121
+ return error;
2122
+ };
2123
+
2124
+ const errorMap = (issue, _ctx) => {
2125
+ let message;
2126
+ switch (issue.code) {
2127
+ case ZodIssueCode.invalid_type:
2128
+ if (issue.received === ZodParsedType.undefined) {
2129
+ message = "Required";
2130
+ }
2131
+ else {
2132
+ message = `Expected ${issue.expected}, received ${issue.received}`;
2133
+ }
2134
+ break;
2135
+ case ZodIssueCode.invalid_literal:
2136
+ message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;
2137
+ break;
2138
+ case ZodIssueCode.unrecognized_keys:
2139
+ message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`;
2140
+ break;
2141
+ case ZodIssueCode.invalid_union:
2142
+ message = `Invalid input`;
2143
+ break;
2144
+ case ZodIssueCode.invalid_union_discriminator:
2145
+ message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;
2146
+ break;
2147
+ case ZodIssueCode.invalid_enum_value:
2148
+ message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;
2149
+ break;
2150
+ case ZodIssueCode.invalid_arguments:
2151
+ message = `Invalid function arguments`;
2152
+ break;
2153
+ case ZodIssueCode.invalid_return_type:
2154
+ message = `Invalid function return type`;
2155
+ break;
2156
+ case ZodIssueCode.invalid_date:
2157
+ message = `Invalid date`;
2158
+ break;
2159
+ case ZodIssueCode.invalid_string:
2160
+ if (typeof issue.validation === "object") {
2161
+ if ("includes" in issue.validation) {
2162
+ message = `Invalid input: must include "${issue.validation.includes}"`;
2163
+ if (typeof issue.validation.position === "number") {
2164
+ message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
2165
+ }
2166
+ }
2167
+ else if ("startsWith" in issue.validation) {
2168
+ message = `Invalid input: must start with "${issue.validation.startsWith}"`;
2169
+ }
2170
+ else if ("endsWith" in issue.validation) {
2171
+ message = `Invalid input: must end with "${issue.validation.endsWith}"`;
2172
+ }
2173
+ else {
2174
+ util.assertNever(issue.validation);
2175
+ }
2176
+ }
2177
+ else if (issue.validation !== "regex") {
2178
+ message = `Invalid ${issue.validation}`;
2179
+ }
2180
+ else {
2181
+ message = "Invalid";
2182
+ }
2183
+ break;
2184
+ case ZodIssueCode.too_small:
2185
+ if (issue.type === "array")
2186
+ message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;
2187
+ else if (issue.type === "string")
2188
+ message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
2189
+ else if (issue.type === "number")
2190
+ message = `Number must be ${issue.exact
2191
+ ? `exactly equal to `
2192
+ : issue.inclusive
2193
+ ? `greater than or equal to `
2194
+ : `greater than `}${issue.minimum}`;
2195
+ else if (issue.type === "date")
2196
+ message = `Date must be ${issue.exact
2197
+ ? `exactly equal to `
2198
+ : issue.inclusive
2199
+ ? `greater than or equal to `
2200
+ : `greater than `}${new Date(Number(issue.minimum))}`;
2201
+ else
2202
+ message = "Invalid input";
2203
+ break;
2204
+ case ZodIssueCode.too_big:
2205
+ if (issue.type === "array")
2206
+ message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;
2207
+ else if (issue.type === "string")
2208
+ message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
2209
+ else if (issue.type === "number")
2210
+ message = `Number must be ${issue.exact
2211
+ ? `exactly`
2212
+ : issue.inclusive
2213
+ ? `less than or equal to`
2214
+ : `less than`} ${issue.maximum}`;
2215
+ else if (issue.type === "bigint")
2216
+ message = `BigInt must be ${issue.exact
2217
+ ? `exactly`
2218
+ : issue.inclusive
2219
+ ? `less than or equal to`
2220
+ : `less than`} ${issue.maximum}`;
2221
+ else if (issue.type === "date")
2222
+ message = `Date must be ${issue.exact
2223
+ ? `exactly`
2224
+ : issue.inclusive
2225
+ ? `smaller than or equal to`
2226
+ : `smaller than`} ${new Date(Number(issue.maximum))}`;
2227
+ else
2228
+ message = "Invalid input";
2229
+ break;
2230
+ case ZodIssueCode.custom:
2231
+ message = `Invalid input`;
2232
+ break;
2233
+ case ZodIssueCode.invalid_intersection_types:
2234
+ message = `Intersection results could not be merged`;
2235
+ break;
2236
+ case ZodIssueCode.not_multiple_of:
2237
+ message = `Number must be a multiple of ${issue.multipleOf}`;
2238
+ break;
2239
+ case ZodIssueCode.not_finite:
2240
+ message = "Number must be finite";
2241
+ break;
2242
+ default:
2243
+ message = _ctx.defaultError;
2244
+ util.assertNever(issue);
2245
+ }
2246
+ return { message };
2247
+ };
2248
+
2249
+ let overrideErrorMap = errorMap;
2250
+ function setErrorMap(map) {
2251
+ overrideErrorMap = map;
2252
+ }
2253
+ function getErrorMap() {
2254
+ return overrideErrorMap;
2255
+ }
2256
+
2257
+ const makeIssue = (params) => {
2258
+ const { data, path, errorMaps, issueData } = params;
2259
+ const fullPath = [...path, ...(issueData.path || [])];
2260
+ const fullIssue = {
2261
+ ...issueData,
2262
+ path: fullPath,
2263
+ };
2264
+ if (issueData.message !== undefined) {
2265
+ return {
2266
+ ...issueData,
2267
+ path: fullPath,
2268
+ message: issueData.message,
2269
+ };
2270
+ }
2271
+ let errorMessage = "";
2272
+ const maps = errorMaps
2273
+ .filter((m) => !!m)
2274
+ .slice()
2275
+ .reverse();
2276
+ for (const map of maps) {
2277
+ errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;
2278
+ }
2279
+ return {
2280
+ ...issueData,
2281
+ path: fullPath,
2282
+ message: errorMessage,
2283
+ };
2284
+ };
2285
+ const EMPTY_PATH = [];
2286
+ function addIssueToContext(ctx, issueData) {
2287
+ const overrideMap = getErrorMap();
2288
+ const issue = makeIssue({
2289
+ issueData: issueData,
2290
+ data: ctx.data,
2291
+ path: ctx.path,
2292
+ errorMaps: [
2293
+ ctx.common.contextualErrorMap,
2294
+ ctx.schemaErrorMap,
2295
+ overrideMap,
2296
+ overrideMap === errorMap ? undefined : errorMap, // then global default map
2297
+ ].filter((x) => !!x),
2298
+ });
2299
+ ctx.common.issues.push(issue);
2300
+ }
2301
+ class ParseStatus {
2302
+ constructor() {
2303
+ this.value = "valid";
2304
+ }
2305
+ dirty() {
2306
+ if (this.value === "valid")
2307
+ this.value = "dirty";
2308
+ }
2309
+ abort() {
2310
+ if (this.value !== "aborted")
2311
+ this.value = "aborted";
2312
+ }
2313
+ static mergeArray(status, results) {
2314
+ const arrayValue = [];
2315
+ for (const s of results) {
2316
+ if (s.status === "aborted")
2317
+ return INVALID;
2318
+ if (s.status === "dirty")
2319
+ status.dirty();
2320
+ arrayValue.push(s.value);
2321
+ }
2322
+ return { status: status.value, value: arrayValue };
2323
+ }
2324
+ static async mergeObjectAsync(status, pairs) {
2325
+ const syncPairs = [];
2326
+ for (const pair of pairs) {
2327
+ const key = await pair.key;
2328
+ const value = await pair.value;
2329
+ syncPairs.push({
2330
+ key,
2331
+ value,
2332
+ });
2333
+ }
2334
+ return ParseStatus.mergeObjectSync(status, syncPairs);
2335
+ }
2336
+ static mergeObjectSync(status, pairs) {
2337
+ const finalObject = {};
2338
+ for (const pair of pairs) {
2339
+ const { key, value } = pair;
2340
+ if (key.status === "aborted")
2341
+ return INVALID;
2342
+ if (value.status === "aborted")
2343
+ return INVALID;
2344
+ if (key.status === "dirty")
2345
+ status.dirty();
2346
+ if (value.status === "dirty")
2347
+ status.dirty();
2348
+ if (key.value !== "__proto__" &&
2349
+ (typeof value.value !== "undefined" || pair.alwaysSet)) {
2350
+ finalObject[key.value] = value.value;
2351
+ }
2352
+ }
2353
+ return { status: status.value, value: finalObject };
2354
+ }
2355
+ }
2356
+ const INVALID = Object.freeze({
2357
+ status: "aborted",
2358
+ });
2359
+ const DIRTY = (value) => ({ status: "dirty", value });
2360
+ const OK = (value) => ({ status: "valid", value });
2361
+ const isAborted = (x) => x.status === "aborted";
2362
+ const isDirty = (x) => x.status === "dirty";
2363
+ const isValid = (x) => x.status === "valid";
2364
+ const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
2365
+
2366
+ /******************************************************************************
2367
+ Copyright (c) Microsoft Corporation.
2368
+
2369
+ Permission to use, copy, modify, and/or distribute this software for any
2370
+ purpose with or without fee is hereby granted.
2371
+
2372
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2373
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2374
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2375
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2376
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2377
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2378
+ PERFORMANCE OF THIS SOFTWARE.
2379
+ ***************************************************************************** */
2380
+
2381
+ function __classPrivateFieldGet(receiver, state, kind, f) {
2382
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
2383
+ 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");
2384
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
2385
+ }
2386
+
2387
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
2388
+ if (kind === "m") throw new TypeError("Private method is not writable");
2389
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
2390
+ 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");
2391
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
2392
+ }
2393
+
2394
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
2395
+ var e = new Error(message);
2396
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2397
+ };
2398
+
2399
+ var errorUtil;
2400
+ (function (errorUtil) {
2401
+ errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
2402
+ errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
2403
+ })(errorUtil || (errorUtil = {}));
2404
+
2405
+ var _ZodEnum_cache, _ZodNativeEnum_cache;
2406
+ class ParseInputLazyPath {
2407
+ constructor(parent, value, path, key) {
2408
+ this._cachedPath = [];
2409
+ this.parent = parent;
2410
+ this.data = value;
2411
+ this._path = path;
2412
+ this._key = key;
2413
+ }
2414
+ get path() {
2415
+ if (!this._cachedPath.length) {
2416
+ if (this._key instanceof Array) {
2417
+ this._cachedPath.push(...this._path, ...this._key);
2418
+ }
2419
+ else {
2420
+ this._cachedPath.push(...this._path, this._key);
2421
+ }
2422
+ }
2423
+ return this._cachedPath;
2424
+ }
2425
+ }
2426
+ const handleResult$1 = (ctx, result) => {
2427
+ if (isValid(result)) {
2428
+ return { success: true, data: result.value };
2429
+ }
2430
+ else {
2431
+ if (!ctx.common.issues.length) {
2432
+ throw new Error("Validation failed but no issues detected.");
2433
+ }
2434
+ return {
2435
+ success: false,
2436
+ get error() {
2437
+ if (this._error)
2438
+ return this._error;
2439
+ const error = new ZodError(ctx.common.issues);
2440
+ this._error = error;
2441
+ return this._error;
2442
+ },
2443
+ };
2444
+ }
2445
+ };
2446
+ function processCreateParams(params) {
2447
+ if (!params)
2448
+ return {};
2449
+ const { errorMap, invalid_type_error, required_error, description } = params;
2450
+ if (errorMap && (invalid_type_error || required_error)) {
2451
+ throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
2452
+ }
2453
+ if (errorMap)
2454
+ return { errorMap: errorMap, description };
2455
+ const customMap = (iss, ctx) => {
2456
+ var _a, _b;
2457
+ const { message } = params;
2458
+ if (iss.code === "invalid_enum_value") {
2459
+ return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
2460
+ }
2461
+ if (typeof ctx.data === "undefined") {
2462
+ return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
2463
+ }
2464
+ if (iss.code !== "invalid_type")
2465
+ return { message: ctx.defaultError };
2466
+ return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
2467
+ };
2468
+ return { errorMap: customMap, description };
2469
+ }
2470
+ class ZodType {
2471
+ constructor(def) {
2472
+ /** Alias of safeParseAsync */
2473
+ this.spa = this.safeParseAsync;
2474
+ this._def = def;
2475
+ this.parse = this.parse.bind(this);
2476
+ this.safeParse = this.safeParse.bind(this);
2477
+ this.parseAsync = this.parseAsync.bind(this);
2478
+ this.safeParseAsync = this.safeParseAsync.bind(this);
2479
+ this.spa = this.spa.bind(this);
2480
+ this.refine = this.refine.bind(this);
2481
+ this.refinement = this.refinement.bind(this);
2482
+ this.superRefine = this.superRefine.bind(this);
2483
+ this.optional = this.optional.bind(this);
2484
+ this.nullable = this.nullable.bind(this);
2485
+ this.nullish = this.nullish.bind(this);
2486
+ this.array = this.array.bind(this);
2487
+ this.promise = this.promise.bind(this);
2488
+ this.or = this.or.bind(this);
2489
+ this.and = this.and.bind(this);
2490
+ this.transform = this.transform.bind(this);
2491
+ this.brand = this.brand.bind(this);
2492
+ this.default = this.default.bind(this);
2493
+ this.catch = this.catch.bind(this);
2494
+ this.describe = this.describe.bind(this);
2495
+ this.pipe = this.pipe.bind(this);
2496
+ this.readonly = this.readonly.bind(this);
2497
+ this.isNullable = this.isNullable.bind(this);
2498
+ this.isOptional = this.isOptional.bind(this);
2499
+ }
2500
+ get description() {
2501
+ return this._def.description;
2502
+ }
2503
+ _getType(input) {
2504
+ return getParsedType(input.data);
2505
+ }
2506
+ _getOrReturnCtx(input, ctx) {
2507
+ return (ctx || {
2508
+ common: input.parent.common,
2509
+ data: input.data,
2510
+ parsedType: getParsedType(input.data),
2511
+ schemaErrorMap: this._def.errorMap,
2512
+ path: input.path,
2513
+ parent: input.parent,
2514
+ });
2515
+ }
2516
+ _processInputParams(input) {
2517
+ return {
2518
+ status: new ParseStatus(),
2519
+ ctx: {
2520
+ common: input.parent.common,
2521
+ data: input.data,
2522
+ parsedType: getParsedType(input.data),
2523
+ schemaErrorMap: this._def.errorMap,
2524
+ path: input.path,
2525
+ parent: input.parent,
2526
+ },
2527
+ };
2528
+ }
2529
+ _parseSync(input) {
2530
+ const result = this._parse(input);
2531
+ if (isAsync(result)) {
2532
+ throw new Error("Synchronous parse encountered promise.");
2533
+ }
2534
+ return result;
2535
+ }
2536
+ _parseAsync(input) {
2537
+ const result = this._parse(input);
2538
+ return Promise.resolve(result);
2539
+ }
2540
+ parse(data, params) {
2541
+ const result = this.safeParse(data, params);
2542
+ if (result.success)
2543
+ return result.data;
2544
+ throw result.error;
2545
+ }
2546
+ safeParse(data, params) {
2547
+ var _a;
2548
+ const ctx = {
2549
+ common: {
2550
+ issues: [],
2551
+ async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
2552
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
2553
+ },
2554
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
2555
+ schemaErrorMap: this._def.errorMap,
2556
+ parent: null,
2557
+ data,
2558
+ parsedType: getParsedType(data),
2559
+ };
2560
+ const result = this._parseSync({ data, path: ctx.path, parent: ctx });
2561
+ return handleResult$1(ctx, result);
2562
+ }
2563
+ async parseAsync(data, params) {
2564
+ const result = await this.safeParseAsync(data, params);
2565
+ if (result.success)
2566
+ return result.data;
2567
+ throw result.error;
2568
+ }
2569
+ async safeParseAsync(data, params) {
2570
+ const ctx = {
2571
+ common: {
2572
+ issues: [],
2573
+ contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
2574
+ async: true,
2575
+ },
2576
+ path: (params === null || params === void 0 ? void 0 : params.path) || [],
2577
+ schemaErrorMap: this._def.errorMap,
2578
+ parent: null,
2579
+ data,
2580
+ parsedType: getParsedType(data),
2581
+ };
2582
+ const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
2583
+ const result = await (isAsync(maybeAsyncResult)
2584
+ ? maybeAsyncResult
2585
+ : Promise.resolve(maybeAsyncResult));
2586
+ return handleResult$1(ctx, result);
2587
+ }
2588
+ refine(check, message) {
2589
+ const getIssueProperties = (val) => {
2590
+ if (typeof message === "string" || typeof message === "undefined") {
2591
+ return { message };
2592
+ }
2593
+ else if (typeof message === "function") {
2594
+ return message(val);
2595
+ }
2596
+ else {
2597
+ return message;
2598
+ }
2599
+ };
2600
+ return this._refinement((val, ctx) => {
2601
+ const result = check(val);
2602
+ const setError = () => ctx.addIssue({
2603
+ code: ZodIssueCode.custom,
2604
+ ...getIssueProperties(val),
2605
+ });
2606
+ if (typeof Promise !== "undefined" && result instanceof Promise) {
2607
+ return result.then((data) => {
2608
+ if (!data) {
2609
+ setError();
2610
+ return false;
2611
+ }
2612
+ else {
2613
+ return true;
2614
+ }
2615
+ });
2616
+ }
2617
+ if (!result) {
2618
+ setError();
2619
+ return false;
2620
+ }
2621
+ else {
2622
+ return true;
2623
+ }
2624
+ });
2625
+ }
2626
+ refinement(check, refinementData) {
2627
+ return this._refinement((val, ctx) => {
2628
+ if (!check(val)) {
2629
+ ctx.addIssue(typeof refinementData === "function"
2630
+ ? refinementData(val, ctx)
2631
+ : refinementData);
2632
+ return false;
2633
+ }
2634
+ else {
2635
+ return true;
2636
+ }
2637
+ });
2638
+ }
2639
+ _refinement(refinement) {
2640
+ return new ZodEffects({
2641
+ schema: this,
2642
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
2643
+ effect: { type: "refinement", refinement },
2644
+ });
2645
+ }
2646
+ superRefine(refinement) {
2647
+ return this._refinement(refinement);
2648
+ }
2649
+ optional() {
2650
+ return ZodOptional.create(this, this._def);
2651
+ }
2652
+ nullable() {
2653
+ return ZodNullable.create(this, this._def);
2654
+ }
2655
+ nullish() {
2656
+ return this.nullable().optional();
2657
+ }
2658
+ array() {
2659
+ return ZodArray.create(this, this._def);
2660
+ }
2661
+ promise() {
2662
+ return ZodPromise.create(this, this._def);
2663
+ }
2664
+ or(option) {
2665
+ return ZodUnion.create([this, option], this._def);
2666
+ }
2667
+ and(incoming) {
2668
+ return ZodIntersection.create(this, incoming, this._def);
2669
+ }
2670
+ transform(transform) {
2671
+ return new ZodEffects({
2672
+ ...processCreateParams(this._def),
2673
+ schema: this,
2674
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
2675
+ effect: { type: "transform", transform },
2676
+ });
2677
+ }
2678
+ default(def) {
2679
+ const defaultValueFunc = typeof def === "function" ? def : () => def;
2680
+ return new ZodDefault({
2681
+ ...processCreateParams(this._def),
2682
+ innerType: this,
2683
+ defaultValue: defaultValueFunc,
2684
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
2685
+ });
2686
+ }
2687
+ brand() {
2688
+ return new ZodBranded({
2689
+ typeName: ZodFirstPartyTypeKind.ZodBranded,
2690
+ type: this,
2691
+ ...processCreateParams(this._def),
2692
+ });
2693
+ }
2694
+ catch(def) {
2695
+ const catchValueFunc = typeof def === "function" ? def : () => def;
2696
+ return new ZodCatch({
2697
+ ...processCreateParams(this._def),
2698
+ innerType: this,
2699
+ catchValue: catchValueFunc,
2700
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
2701
+ });
2702
+ }
2703
+ describe(description) {
2704
+ const This = this.constructor;
2705
+ return new This({
2706
+ ...this._def,
2707
+ description,
2708
+ });
2709
+ }
2710
+ pipe(target) {
2711
+ return ZodPipeline.create(this, target);
2712
+ }
2713
+ readonly() {
2714
+ return ZodReadonly.create(this);
2715
+ }
2716
+ isOptional() {
2717
+ return this.safeParse(undefined).success;
2718
+ }
2719
+ isNullable() {
2720
+ return this.safeParse(null).success;
2721
+ }
2722
+ }
2723
+ const cuidRegex = /^c[^\s-]{8,}$/i;
2724
+ const cuid2Regex = /^[0-9a-z]+$/;
2725
+ const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
2726
+ // const uuidRegex =
2727
+ // /^([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;
2728
+ 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;
2729
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
2730
+ 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)?)??$/;
2731
+ // from https://stackoverflow.com/a/46181/1550155
2732
+ // old version: too slow, didn't support unicode
2733
+ // 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;
2734
+ //old email regex
2735
+ // const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i;
2736
+ // eslint-disable-next-line
2737
+ // const emailRegex =
2738
+ // /^(([^<>()[\]\\.,;:\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,})+))$/;
2739
+ // const emailRegex =
2740
+ // /^[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])?)*$/;
2741
+ // const emailRegex =
2742
+ // /^(?:[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;
2743
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
2744
+ // const emailRegex =
2745
+ // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
2746
+ // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
2747
+ const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
2748
+ let emojiRegex$1;
2749
+ // faster, simpler, safer
2750
+ 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])$/;
2751
+ 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})))$/;
2752
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
2753
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
2754
+ // simple
2755
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
2756
+ // no leap year validation
2757
+ // 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))`;
2758
+ // with leap year validation
2759
+ 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])))`;
2760
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
2761
+ function timeRegexSource(args) {
2762
+ // let regex = `\\d{2}:\\d{2}:\\d{2}`;
2763
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
2764
+ if (args.precision) {
2765
+ regex = `${regex}\\.\\d{${args.precision}}`;
2766
+ }
2767
+ else if (args.precision == null) {
2768
+ regex = `${regex}(\\.\\d+)?`;
2769
+ }
2770
+ return regex;
2771
+ }
2772
+ function timeRegex(args) {
2773
+ return new RegExp(`^${timeRegexSource(args)}$`);
2774
+ }
2775
+ // Adapted from https://stackoverflow.com/a/3143231
2776
+ function datetimeRegex(args) {
2777
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
2778
+ const opts = [];
2779
+ opts.push(args.local ? `Z?` : `Z`);
2780
+ if (args.offset)
2781
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
2782
+ regex = `${regex}(${opts.join("|")})`;
2783
+ return new RegExp(`^${regex}$`);
2784
+ }
2785
+ function isValidIP(ip, version) {
2786
+ if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
2787
+ return true;
2788
+ }
2789
+ if ((version === "v6" || !version) && ipv6Regex.test(ip)) {
2790
+ return true;
2791
+ }
2792
+ return false;
2793
+ }
2794
+ class ZodString extends ZodType {
2795
+ _parse(input) {
2796
+ if (this._def.coerce) {
2797
+ input.data = String(input.data);
2798
+ }
2799
+ const parsedType = this._getType(input);
2800
+ if (parsedType !== ZodParsedType.string) {
2801
+ const ctx = this._getOrReturnCtx(input);
2802
+ addIssueToContext(ctx, {
2803
+ code: ZodIssueCode.invalid_type,
2804
+ expected: ZodParsedType.string,
2805
+ received: ctx.parsedType,
2806
+ });
2807
+ return INVALID;
2808
+ }
2809
+ const status = new ParseStatus();
2810
+ let ctx = undefined;
2811
+ for (const check of this._def.checks) {
2812
+ if (check.kind === "min") {
2813
+ if (input.data.length < check.value) {
2814
+ ctx = this._getOrReturnCtx(input, ctx);
2815
+ addIssueToContext(ctx, {
2816
+ code: ZodIssueCode.too_small,
2817
+ minimum: check.value,
2818
+ type: "string",
2819
+ inclusive: true,
2820
+ exact: false,
2821
+ message: check.message,
2822
+ });
2823
+ status.dirty();
2824
+ }
2825
+ }
2826
+ else if (check.kind === "max") {
2827
+ if (input.data.length > check.value) {
2828
+ ctx = this._getOrReturnCtx(input, ctx);
2829
+ addIssueToContext(ctx, {
2830
+ code: ZodIssueCode.too_big,
2831
+ maximum: check.value,
2832
+ type: "string",
2833
+ inclusive: true,
2834
+ exact: false,
2835
+ message: check.message,
2836
+ });
2837
+ status.dirty();
2838
+ }
2839
+ }
2840
+ else if (check.kind === "length") {
2841
+ const tooBig = input.data.length > check.value;
2842
+ const tooSmall = input.data.length < check.value;
2843
+ if (tooBig || tooSmall) {
2844
+ ctx = this._getOrReturnCtx(input, ctx);
2845
+ if (tooBig) {
2846
+ addIssueToContext(ctx, {
2847
+ code: ZodIssueCode.too_big,
2848
+ maximum: check.value,
2849
+ type: "string",
2850
+ inclusive: true,
2851
+ exact: true,
2852
+ message: check.message,
2853
+ });
2854
+ }
2855
+ else if (tooSmall) {
2856
+ addIssueToContext(ctx, {
2857
+ code: ZodIssueCode.too_small,
2858
+ minimum: check.value,
2859
+ type: "string",
2860
+ inclusive: true,
2861
+ exact: true,
2862
+ message: check.message,
2863
+ });
2864
+ }
2865
+ status.dirty();
2866
+ }
2867
+ }
2868
+ else if (check.kind === "email") {
2869
+ if (!emailRegex.test(input.data)) {
2870
+ ctx = this._getOrReturnCtx(input, ctx);
2871
+ addIssueToContext(ctx, {
2872
+ validation: "email",
2873
+ code: ZodIssueCode.invalid_string,
2874
+ message: check.message,
2875
+ });
2876
+ status.dirty();
2877
+ }
2878
+ }
2879
+ else if (check.kind === "emoji") {
2880
+ if (!emojiRegex$1) {
2881
+ emojiRegex$1 = new RegExp(_emojiRegex, "u");
2882
+ }
2883
+ if (!emojiRegex$1.test(input.data)) {
2884
+ ctx = this._getOrReturnCtx(input, ctx);
2885
+ addIssueToContext(ctx, {
2886
+ validation: "emoji",
2887
+ code: ZodIssueCode.invalid_string,
2888
+ message: check.message,
2889
+ });
2890
+ status.dirty();
2891
+ }
2892
+ }
2893
+ else if (check.kind === "uuid") {
2894
+ if (!uuidRegex.test(input.data)) {
2895
+ ctx = this._getOrReturnCtx(input, ctx);
2896
+ addIssueToContext(ctx, {
2897
+ validation: "uuid",
2898
+ code: ZodIssueCode.invalid_string,
2899
+ message: check.message,
2900
+ });
2901
+ status.dirty();
2902
+ }
2903
+ }
2904
+ else if (check.kind === "nanoid") {
2905
+ if (!nanoidRegex.test(input.data)) {
2906
+ ctx = this._getOrReturnCtx(input, ctx);
2907
+ addIssueToContext(ctx, {
2908
+ validation: "nanoid",
2909
+ code: ZodIssueCode.invalid_string,
2910
+ message: check.message,
2911
+ });
2912
+ status.dirty();
2913
+ }
2914
+ }
2915
+ else if (check.kind === "cuid") {
2916
+ if (!cuidRegex.test(input.data)) {
2917
+ ctx = this._getOrReturnCtx(input, ctx);
2918
+ addIssueToContext(ctx, {
2919
+ validation: "cuid",
2920
+ code: ZodIssueCode.invalid_string,
2921
+ message: check.message,
2922
+ });
2923
+ status.dirty();
2924
+ }
2925
+ }
2926
+ else if (check.kind === "cuid2") {
2927
+ if (!cuid2Regex.test(input.data)) {
2928
+ ctx = this._getOrReturnCtx(input, ctx);
2929
+ addIssueToContext(ctx, {
2930
+ validation: "cuid2",
2931
+ code: ZodIssueCode.invalid_string,
2932
+ message: check.message,
2933
+ });
2934
+ status.dirty();
2935
+ }
2936
+ }
2937
+ else if (check.kind === "ulid") {
2938
+ if (!ulidRegex.test(input.data)) {
2939
+ ctx = this._getOrReturnCtx(input, ctx);
2940
+ addIssueToContext(ctx, {
2941
+ validation: "ulid",
2942
+ code: ZodIssueCode.invalid_string,
2943
+ message: check.message,
2944
+ });
2945
+ status.dirty();
2946
+ }
2947
+ }
2948
+ else if (check.kind === "url") {
2949
+ try {
2950
+ new URL(input.data);
2951
+ }
2952
+ catch (_a) {
2953
+ ctx = this._getOrReturnCtx(input, ctx);
2954
+ addIssueToContext(ctx, {
2955
+ validation: "url",
2956
+ code: ZodIssueCode.invalid_string,
2957
+ message: check.message,
2958
+ });
2959
+ status.dirty();
2960
+ }
2961
+ }
2962
+ else if (check.kind === "regex") {
2963
+ check.regex.lastIndex = 0;
2964
+ const testResult = check.regex.test(input.data);
2965
+ if (!testResult) {
2966
+ ctx = this._getOrReturnCtx(input, ctx);
2967
+ addIssueToContext(ctx, {
2968
+ validation: "regex",
2969
+ code: ZodIssueCode.invalid_string,
2970
+ message: check.message,
2971
+ });
2972
+ status.dirty();
2973
+ }
2974
+ }
2975
+ else if (check.kind === "trim") {
2976
+ input.data = input.data.trim();
2977
+ }
2978
+ else if (check.kind === "includes") {
2979
+ if (!input.data.includes(check.value, check.position)) {
2980
+ ctx = this._getOrReturnCtx(input, ctx);
2981
+ addIssueToContext(ctx, {
2982
+ code: ZodIssueCode.invalid_string,
2983
+ validation: { includes: check.value, position: check.position },
2984
+ message: check.message,
2985
+ });
2986
+ status.dirty();
2987
+ }
2988
+ }
2989
+ else if (check.kind === "toLowerCase") {
2990
+ input.data = input.data.toLowerCase();
2991
+ }
2992
+ else if (check.kind === "toUpperCase") {
2993
+ input.data = input.data.toUpperCase();
2994
+ }
2995
+ else if (check.kind === "startsWith") {
2996
+ if (!input.data.startsWith(check.value)) {
2997
+ ctx = this._getOrReturnCtx(input, ctx);
2998
+ addIssueToContext(ctx, {
2999
+ code: ZodIssueCode.invalid_string,
3000
+ validation: { startsWith: check.value },
3001
+ message: check.message,
3002
+ });
3003
+ status.dirty();
3004
+ }
3005
+ }
3006
+ else if (check.kind === "endsWith") {
3007
+ if (!input.data.endsWith(check.value)) {
3008
+ ctx = this._getOrReturnCtx(input, ctx);
3009
+ addIssueToContext(ctx, {
3010
+ code: ZodIssueCode.invalid_string,
3011
+ validation: { endsWith: check.value },
3012
+ message: check.message,
3013
+ });
3014
+ status.dirty();
3015
+ }
3016
+ }
3017
+ else if (check.kind === "datetime") {
3018
+ const regex = datetimeRegex(check);
3019
+ if (!regex.test(input.data)) {
3020
+ ctx = this._getOrReturnCtx(input, ctx);
3021
+ addIssueToContext(ctx, {
3022
+ code: ZodIssueCode.invalid_string,
3023
+ validation: "datetime",
3024
+ message: check.message,
3025
+ });
3026
+ status.dirty();
3027
+ }
3028
+ }
3029
+ else if (check.kind === "date") {
3030
+ const regex = dateRegex;
3031
+ if (!regex.test(input.data)) {
3032
+ ctx = this._getOrReturnCtx(input, ctx);
3033
+ addIssueToContext(ctx, {
3034
+ code: ZodIssueCode.invalid_string,
3035
+ validation: "date",
3036
+ message: check.message,
3037
+ });
3038
+ status.dirty();
3039
+ }
3040
+ }
3041
+ else if (check.kind === "time") {
3042
+ const regex = timeRegex(check);
3043
+ if (!regex.test(input.data)) {
3044
+ ctx = this._getOrReturnCtx(input, ctx);
3045
+ addIssueToContext(ctx, {
3046
+ code: ZodIssueCode.invalid_string,
3047
+ validation: "time",
3048
+ message: check.message,
3049
+ });
3050
+ status.dirty();
3051
+ }
3052
+ }
3053
+ else if (check.kind === "duration") {
3054
+ if (!durationRegex.test(input.data)) {
3055
+ ctx = this._getOrReturnCtx(input, ctx);
3056
+ addIssueToContext(ctx, {
3057
+ validation: "duration",
3058
+ code: ZodIssueCode.invalid_string,
3059
+ message: check.message,
3060
+ });
3061
+ status.dirty();
3062
+ }
3063
+ }
3064
+ else if (check.kind === "ip") {
3065
+ if (!isValidIP(input.data, check.version)) {
3066
+ ctx = this._getOrReturnCtx(input, ctx);
3067
+ addIssueToContext(ctx, {
3068
+ validation: "ip",
3069
+ code: ZodIssueCode.invalid_string,
3070
+ message: check.message,
3071
+ });
3072
+ status.dirty();
3073
+ }
3074
+ }
3075
+ else if (check.kind === "base64") {
3076
+ if (!base64Regex.test(input.data)) {
3077
+ ctx = this._getOrReturnCtx(input, ctx);
3078
+ addIssueToContext(ctx, {
3079
+ validation: "base64",
3080
+ code: ZodIssueCode.invalid_string,
3081
+ message: check.message,
3082
+ });
3083
+ status.dirty();
3084
+ }
3085
+ }
3086
+ else {
3087
+ util.assertNever(check);
3088
+ }
3089
+ }
3090
+ return { status: status.value, value: input.data };
3091
+ }
3092
+ _regex(regex, validation, message) {
3093
+ return this.refinement((data) => regex.test(data), {
3094
+ validation,
3095
+ code: ZodIssueCode.invalid_string,
3096
+ ...errorUtil.errToObj(message),
3097
+ });
3098
+ }
3099
+ _addCheck(check) {
3100
+ return new ZodString({
3101
+ ...this._def,
3102
+ checks: [...this._def.checks, check],
3103
+ });
3104
+ }
3105
+ email(message) {
3106
+ return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
3107
+ }
3108
+ url(message) {
3109
+ return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
3110
+ }
3111
+ emoji(message) {
3112
+ return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
3113
+ }
3114
+ uuid(message) {
3115
+ return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
3116
+ }
3117
+ nanoid(message) {
3118
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
3119
+ }
3120
+ cuid(message) {
3121
+ return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
3122
+ }
3123
+ cuid2(message) {
3124
+ return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
3125
+ }
3126
+ ulid(message) {
3127
+ return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
3128
+ }
3129
+ base64(message) {
3130
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
3131
+ }
3132
+ ip(options) {
3133
+ return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
3134
+ }
3135
+ datetime(options) {
3136
+ var _a, _b;
3137
+ if (typeof options === "string") {
3138
+ return this._addCheck({
3139
+ kind: "datetime",
3140
+ precision: null,
3141
+ offset: false,
3142
+ local: false,
3143
+ message: options,
3144
+ });
3145
+ }
3146
+ return this._addCheck({
3147
+ kind: "datetime",
3148
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
3149
+ offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
3150
+ local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
3151
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
3152
+ });
3153
+ }
3154
+ date(message) {
3155
+ return this._addCheck({ kind: "date", message });
3156
+ }
3157
+ time(options) {
3158
+ if (typeof options === "string") {
3159
+ return this._addCheck({
3160
+ kind: "time",
3161
+ precision: null,
3162
+ message: options,
3163
+ });
3164
+ }
3165
+ return this._addCheck({
3166
+ kind: "time",
3167
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
3168
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
3169
+ });
3170
+ }
3171
+ duration(message) {
3172
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
3173
+ }
3174
+ regex(regex, message) {
3175
+ return this._addCheck({
3176
+ kind: "regex",
3177
+ regex: regex,
3178
+ ...errorUtil.errToObj(message),
3179
+ });
3180
+ }
3181
+ includes(value, options) {
3182
+ return this._addCheck({
3183
+ kind: "includes",
3184
+ value: value,
3185
+ position: options === null || options === void 0 ? void 0 : options.position,
3186
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
3187
+ });
3188
+ }
3189
+ startsWith(value, message) {
3190
+ return this._addCheck({
3191
+ kind: "startsWith",
3192
+ value: value,
3193
+ ...errorUtil.errToObj(message),
3194
+ });
3195
+ }
3196
+ endsWith(value, message) {
3197
+ return this._addCheck({
3198
+ kind: "endsWith",
3199
+ value: value,
3200
+ ...errorUtil.errToObj(message),
3201
+ });
3202
+ }
3203
+ min(minLength, message) {
3204
+ return this._addCheck({
3205
+ kind: "min",
3206
+ value: minLength,
3207
+ ...errorUtil.errToObj(message),
3208
+ });
3209
+ }
3210
+ max(maxLength, message) {
3211
+ return this._addCheck({
3212
+ kind: "max",
3213
+ value: maxLength,
3214
+ ...errorUtil.errToObj(message),
3215
+ });
3216
+ }
3217
+ length(len, message) {
3218
+ return this._addCheck({
3219
+ kind: "length",
3220
+ value: len,
3221
+ ...errorUtil.errToObj(message),
3222
+ });
3223
+ }
3224
+ /**
3225
+ * @deprecated Use z.string().min(1) instead.
3226
+ * @see {@link ZodString.min}
3227
+ */
3228
+ nonempty(message) {
3229
+ return this.min(1, errorUtil.errToObj(message));
3230
+ }
3231
+ trim() {
3232
+ return new ZodString({
3233
+ ...this._def,
3234
+ checks: [...this._def.checks, { kind: "trim" }],
3235
+ });
3236
+ }
3237
+ toLowerCase() {
3238
+ return new ZodString({
3239
+ ...this._def,
3240
+ checks: [...this._def.checks, { kind: "toLowerCase" }],
3241
+ });
3242
+ }
3243
+ toUpperCase() {
3244
+ return new ZodString({
3245
+ ...this._def,
3246
+ checks: [...this._def.checks, { kind: "toUpperCase" }],
3247
+ });
3248
+ }
3249
+ get isDatetime() {
3250
+ return !!this._def.checks.find((ch) => ch.kind === "datetime");
3251
+ }
3252
+ get isDate() {
3253
+ return !!this._def.checks.find((ch) => ch.kind === "date");
3254
+ }
3255
+ get isTime() {
3256
+ return !!this._def.checks.find((ch) => ch.kind === "time");
3257
+ }
3258
+ get isDuration() {
3259
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
3260
+ }
3261
+ get isEmail() {
3262
+ return !!this._def.checks.find((ch) => ch.kind === "email");
3263
+ }
3264
+ get isURL() {
3265
+ return !!this._def.checks.find((ch) => ch.kind === "url");
3266
+ }
3267
+ get isEmoji() {
3268
+ return !!this._def.checks.find((ch) => ch.kind === "emoji");
3269
+ }
3270
+ get isUUID() {
3271
+ return !!this._def.checks.find((ch) => ch.kind === "uuid");
3272
+ }
3273
+ get isNANOID() {
3274
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
3275
+ }
3276
+ get isCUID() {
3277
+ return !!this._def.checks.find((ch) => ch.kind === "cuid");
3278
+ }
3279
+ get isCUID2() {
3280
+ return !!this._def.checks.find((ch) => ch.kind === "cuid2");
3281
+ }
3282
+ get isULID() {
3283
+ return !!this._def.checks.find((ch) => ch.kind === "ulid");
3284
+ }
3285
+ get isIP() {
3286
+ return !!this._def.checks.find((ch) => ch.kind === "ip");
3287
+ }
3288
+ get isBase64() {
3289
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
3290
+ }
3291
+ get minLength() {
3292
+ let min = null;
3293
+ for (const ch of this._def.checks) {
3294
+ if (ch.kind === "min") {
3295
+ if (min === null || ch.value > min)
3296
+ min = ch.value;
3297
+ }
3298
+ }
3299
+ return min;
3300
+ }
3301
+ get maxLength() {
3302
+ let max = null;
3303
+ for (const ch of this._def.checks) {
3304
+ if (ch.kind === "max") {
3305
+ if (max === null || ch.value < max)
3306
+ max = ch.value;
3307
+ }
3308
+ }
3309
+ return max;
3310
+ }
3311
+ }
3312
+ ZodString.create = (params) => {
3313
+ var _a;
3314
+ return new ZodString({
3315
+ checks: [],
3316
+ typeName: ZodFirstPartyTypeKind.ZodString,
3317
+ coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
3318
+ ...processCreateParams(params),
3319
+ });
3320
+ };
3321
+ // https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034
3322
+ function floatSafeRemainder(val, step) {
3323
+ const valDecCount = (val.toString().split(".")[1] || "").length;
3324
+ const stepDecCount = (step.toString().split(".")[1] || "").length;
3325
+ const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
3326
+ const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
3327
+ const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
3328
+ return (valInt % stepInt) / Math.pow(10, decCount);
3329
+ }
3330
+ class ZodNumber extends ZodType {
3331
+ constructor() {
3332
+ super(...arguments);
3333
+ this.min = this.gte;
3334
+ this.max = this.lte;
3335
+ this.step = this.multipleOf;
3336
+ }
3337
+ _parse(input) {
3338
+ if (this._def.coerce) {
3339
+ input.data = Number(input.data);
3340
+ }
3341
+ const parsedType = this._getType(input);
3342
+ if (parsedType !== ZodParsedType.number) {
3343
+ const ctx = this._getOrReturnCtx(input);
3344
+ addIssueToContext(ctx, {
3345
+ code: ZodIssueCode.invalid_type,
3346
+ expected: ZodParsedType.number,
3347
+ received: ctx.parsedType,
3348
+ });
3349
+ return INVALID;
3350
+ }
3351
+ let ctx = undefined;
3352
+ const status = new ParseStatus();
3353
+ for (const check of this._def.checks) {
3354
+ if (check.kind === "int") {
3355
+ if (!util.isInteger(input.data)) {
3356
+ ctx = this._getOrReturnCtx(input, ctx);
3357
+ addIssueToContext(ctx, {
3358
+ code: ZodIssueCode.invalid_type,
3359
+ expected: "integer",
3360
+ received: "float",
3361
+ message: check.message,
3362
+ });
3363
+ status.dirty();
3364
+ }
3365
+ }
3366
+ else if (check.kind === "min") {
3367
+ const tooSmall = check.inclusive
3368
+ ? input.data < check.value
3369
+ : input.data <= check.value;
3370
+ if (tooSmall) {
3371
+ ctx = this._getOrReturnCtx(input, ctx);
3372
+ addIssueToContext(ctx, {
3373
+ code: ZodIssueCode.too_small,
3374
+ minimum: check.value,
3375
+ type: "number",
3376
+ inclusive: check.inclusive,
3377
+ exact: false,
3378
+ message: check.message,
3379
+ });
3380
+ status.dirty();
3381
+ }
3382
+ }
3383
+ else if (check.kind === "max") {
3384
+ const tooBig = check.inclusive
3385
+ ? input.data > check.value
3386
+ : input.data >= check.value;
3387
+ if (tooBig) {
3388
+ ctx = this._getOrReturnCtx(input, ctx);
3389
+ addIssueToContext(ctx, {
3390
+ code: ZodIssueCode.too_big,
3391
+ maximum: check.value,
3392
+ type: "number",
3393
+ inclusive: check.inclusive,
3394
+ exact: false,
3395
+ message: check.message,
3396
+ });
3397
+ status.dirty();
3398
+ }
3399
+ }
3400
+ else if (check.kind === "multipleOf") {
3401
+ if (floatSafeRemainder(input.data, check.value) !== 0) {
3402
+ ctx = this._getOrReturnCtx(input, ctx);
3403
+ addIssueToContext(ctx, {
3404
+ code: ZodIssueCode.not_multiple_of,
3405
+ multipleOf: check.value,
3406
+ message: check.message,
3407
+ });
3408
+ status.dirty();
3409
+ }
3410
+ }
3411
+ else if (check.kind === "finite") {
3412
+ if (!Number.isFinite(input.data)) {
3413
+ ctx = this._getOrReturnCtx(input, ctx);
3414
+ addIssueToContext(ctx, {
3415
+ code: ZodIssueCode.not_finite,
3416
+ message: check.message,
3417
+ });
3418
+ status.dirty();
3419
+ }
3420
+ }
3421
+ else {
3422
+ util.assertNever(check);
3423
+ }
3424
+ }
3425
+ return { status: status.value, value: input.data };
3426
+ }
3427
+ gte(value, message) {
3428
+ return this.setLimit("min", value, true, errorUtil.toString(message));
3429
+ }
3430
+ gt(value, message) {
3431
+ return this.setLimit("min", value, false, errorUtil.toString(message));
3432
+ }
3433
+ lte(value, message) {
3434
+ return this.setLimit("max", value, true, errorUtil.toString(message));
3435
+ }
3436
+ lt(value, message) {
3437
+ return this.setLimit("max", value, false, errorUtil.toString(message));
3438
+ }
3439
+ setLimit(kind, value, inclusive, message) {
3440
+ return new ZodNumber({
3441
+ ...this._def,
3442
+ checks: [
3443
+ ...this._def.checks,
3444
+ {
3445
+ kind,
3446
+ value,
3447
+ inclusive,
3448
+ message: errorUtil.toString(message),
3449
+ },
3450
+ ],
3451
+ });
3452
+ }
3453
+ _addCheck(check) {
3454
+ return new ZodNumber({
3455
+ ...this._def,
3456
+ checks: [...this._def.checks, check],
3457
+ });
3458
+ }
3459
+ int(message) {
3460
+ return this._addCheck({
3461
+ kind: "int",
3462
+ message: errorUtil.toString(message),
3463
+ });
3464
+ }
3465
+ positive(message) {
3466
+ return this._addCheck({
3467
+ kind: "min",
3468
+ value: 0,
3469
+ inclusive: false,
3470
+ message: errorUtil.toString(message),
3471
+ });
3472
+ }
3473
+ negative(message) {
3474
+ return this._addCheck({
3475
+ kind: "max",
3476
+ value: 0,
3477
+ inclusive: false,
3478
+ message: errorUtil.toString(message),
3479
+ });
3480
+ }
3481
+ nonpositive(message) {
3482
+ return this._addCheck({
3483
+ kind: "max",
3484
+ value: 0,
3485
+ inclusive: true,
3486
+ message: errorUtil.toString(message),
3487
+ });
3488
+ }
3489
+ nonnegative(message) {
3490
+ return this._addCheck({
3491
+ kind: "min",
3492
+ value: 0,
3493
+ inclusive: true,
3494
+ message: errorUtil.toString(message),
3495
+ });
3496
+ }
3497
+ multipleOf(value, message) {
3498
+ return this._addCheck({
3499
+ kind: "multipleOf",
3500
+ value: value,
3501
+ message: errorUtil.toString(message),
3502
+ });
3503
+ }
3504
+ finite(message) {
3505
+ return this._addCheck({
3506
+ kind: "finite",
3507
+ message: errorUtil.toString(message),
3508
+ });
3509
+ }
3510
+ safe(message) {
3511
+ return this._addCheck({
3512
+ kind: "min",
3513
+ inclusive: true,
3514
+ value: Number.MIN_SAFE_INTEGER,
3515
+ message: errorUtil.toString(message),
3516
+ })._addCheck({
3517
+ kind: "max",
3518
+ inclusive: true,
3519
+ value: Number.MAX_SAFE_INTEGER,
3520
+ message: errorUtil.toString(message),
3521
+ });
3522
+ }
3523
+ get minValue() {
3524
+ let min = null;
3525
+ for (const ch of this._def.checks) {
3526
+ if (ch.kind === "min") {
3527
+ if (min === null || ch.value > min)
3528
+ min = ch.value;
3529
+ }
3530
+ }
3531
+ return min;
3532
+ }
3533
+ get maxValue() {
3534
+ let max = null;
3535
+ for (const ch of this._def.checks) {
3536
+ if (ch.kind === "max") {
3537
+ if (max === null || ch.value < max)
3538
+ max = ch.value;
3539
+ }
3540
+ }
3541
+ return max;
3542
+ }
3543
+ get isInt() {
3544
+ return !!this._def.checks.find((ch) => ch.kind === "int" ||
3545
+ (ch.kind === "multipleOf" && util.isInteger(ch.value)));
3546
+ }
3547
+ get isFinite() {
3548
+ let max = null, min = null;
3549
+ for (const ch of this._def.checks) {
3550
+ if (ch.kind === "finite" ||
3551
+ ch.kind === "int" ||
3552
+ ch.kind === "multipleOf") {
3553
+ return true;
3554
+ }
3555
+ else if (ch.kind === "min") {
3556
+ if (min === null || ch.value > min)
3557
+ min = ch.value;
3558
+ }
3559
+ else if (ch.kind === "max") {
3560
+ if (max === null || ch.value < max)
3561
+ max = ch.value;
3562
+ }
3563
+ }
3564
+ return Number.isFinite(min) && Number.isFinite(max);
3565
+ }
3566
+ }
3567
+ ZodNumber.create = (params) => {
3568
+ return new ZodNumber({
3569
+ checks: [],
3570
+ typeName: ZodFirstPartyTypeKind.ZodNumber,
3571
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
3572
+ ...processCreateParams(params),
3573
+ });
3574
+ };
3575
+ class ZodBigInt extends ZodType {
3576
+ constructor() {
3577
+ super(...arguments);
3578
+ this.min = this.gte;
3579
+ this.max = this.lte;
3580
+ }
3581
+ _parse(input) {
3582
+ if (this._def.coerce) {
3583
+ input.data = BigInt(input.data);
3584
+ }
3585
+ const parsedType = this._getType(input);
3586
+ if (parsedType !== ZodParsedType.bigint) {
3587
+ const ctx = this._getOrReturnCtx(input);
3588
+ addIssueToContext(ctx, {
3589
+ code: ZodIssueCode.invalid_type,
3590
+ expected: ZodParsedType.bigint,
3591
+ received: ctx.parsedType,
3592
+ });
3593
+ return INVALID;
3594
+ }
3595
+ let ctx = undefined;
3596
+ const status = new ParseStatus();
3597
+ for (const check of this._def.checks) {
3598
+ if (check.kind === "min") {
3599
+ const tooSmall = check.inclusive
3600
+ ? input.data < check.value
3601
+ : input.data <= check.value;
3602
+ if (tooSmall) {
3603
+ ctx = this._getOrReturnCtx(input, ctx);
3604
+ addIssueToContext(ctx, {
3605
+ code: ZodIssueCode.too_small,
3606
+ type: "bigint",
3607
+ minimum: check.value,
3608
+ inclusive: check.inclusive,
3609
+ message: check.message,
3610
+ });
3611
+ status.dirty();
3612
+ }
3613
+ }
3614
+ else if (check.kind === "max") {
3615
+ const tooBig = check.inclusive
3616
+ ? input.data > check.value
3617
+ : input.data >= check.value;
3618
+ if (tooBig) {
3619
+ ctx = this._getOrReturnCtx(input, ctx);
3620
+ addIssueToContext(ctx, {
3621
+ code: ZodIssueCode.too_big,
3622
+ type: "bigint",
3623
+ maximum: check.value,
3624
+ inclusive: check.inclusive,
3625
+ message: check.message,
3626
+ });
3627
+ status.dirty();
3628
+ }
3629
+ }
3630
+ else if (check.kind === "multipleOf") {
3631
+ if (input.data % check.value !== BigInt(0)) {
3632
+ ctx = this._getOrReturnCtx(input, ctx);
3633
+ addIssueToContext(ctx, {
3634
+ code: ZodIssueCode.not_multiple_of,
3635
+ multipleOf: check.value,
3636
+ message: check.message,
3637
+ });
3638
+ status.dirty();
3639
+ }
3640
+ }
3641
+ else {
3642
+ util.assertNever(check);
3643
+ }
3644
+ }
3645
+ return { status: status.value, value: input.data };
3646
+ }
3647
+ gte(value, message) {
3648
+ return this.setLimit("min", value, true, errorUtil.toString(message));
3649
+ }
3650
+ gt(value, message) {
3651
+ return this.setLimit("min", value, false, errorUtil.toString(message));
3652
+ }
3653
+ lte(value, message) {
3654
+ return this.setLimit("max", value, true, errorUtil.toString(message));
3655
+ }
3656
+ lt(value, message) {
3657
+ return this.setLimit("max", value, false, errorUtil.toString(message));
3658
+ }
3659
+ setLimit(kind, value, inclusive, message) {
3660
+ return new ZodBigInt({
3661
+ ...this._def,
3662
+ checks: [
3663
+ ...this._def.checks,
3664
+ {
3665
+ kind,
3666
+ value,
3667
+ inclusive,
3668
+ message: errorUtil.toString(message),
3669
+ },
3670
+ ],
3671
+ });
3672
+ }
3673
+ _addCheck(check) {
3674
+ return new ZodBigInt({
3675
+ ...this._def,
3676
+ checks: [...this._def.checks, check],
3677
+ });
3678
+ }
3679
+ positive(message) {
3680
+ return this._addCheck({
3681
+ kind: "min",
3682
+ value: BigInt(0),
3683
+ inclusive: false,
3684
+ message: errorUtil.toString(message),
3685
+ });
3686
+ }
3687
+ negative(message) {
3688
+ return this._addCheck({
3689
+ kind: "max",
3690
+ value: BigInt(0),
3691
+ inclusive: false,
3692
+ message: errorUtil.toString(message),
3693
+ });
3694
+ }
3695
+ nonpositive(message) {
3696
+ return this._addCheck({
3697
+ kind: "max",
3698
+ value: BigInt(0),
3699
+ inclusive: true,
3700
+ message: errorUtil.toString(message),
3701
+ });
3702
+ }
3703
+ nonnegative(message) {
3704
+ return this._addCheck({
3705
+ kind: "min",
3706
+ value: BigInt(0),
3707
+ inclusive: true,
3708
+ message: errorUtil.toString(message),
3709
+ });
3710
+ }
3711
+ multipleOf(value, message) {
3712
+ return this._addCheck({
3713
+ kind: "multipleOf",
3714
+ value,
3715
+ message: errorUtil.toString(message),
3716
+ });
3717
+ }
3718
+ get minValue() {
3719
+ let min = null;
3720
+ for (const ch of this._def.checks) {
3721
+ if (ch.kind === "min") {
3722
+ if (min === null || ch.value > min)
3723
+ min = ch.value;
3724
+ }
3725
+ }
3726
+ return min;
3727
+ }
3728
+ get maxValue() {
3729
+ let max = null;
3730
+ for (const ch of this._def.checks) {
3731
+ if (ch.kind === "max") {
3732
+ if (max === null || ch.value < max)
3733
+ max = ch.value;
3734
+ }
3735
+ }
3736
+ return max;
3737
+ }
3738
+ }
3739
+ ZodBigInt.create = (params) => {
3740
+ var _a;
3741
+ return new ZodBigInt({
3742
+ checks: [],
3743
+ typeName: ZodFirstPartyTypeKind.ZodBigInt,
3744
+ coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
3745
+ ...processCreateParams(params),
3746
+ });
3747
+ };
3748
+ class ZodBoolean extends ZodType {
3749
+ _parse(input) {
3750
+ if (this._def.coerce) {
3751
+ input.data = Boolean(input.data);
3752
+ }
3753
+ const parsedType = this._getType(input);
3754
+ if (parsedType !== ZodParsedType.boolean) {
3755
+ const ctx = this._getOrReturnCtx(input);
3756
+ addIssueToContext(ctx, {
3757
+ code: ZodIssueCode.invalid_type,
3758
+ expected: ZodParsedType.boolean,
3759
+ received: ctx.parsedType,
3760
+ });
3761
+ return INVALID;
3762
+ }
3763
+ return OK(input.data);
3764
+ }
3765
+ }
3766
+ ZodBoolean.create = (params) => {
3767
+ return new ZodBoolean({
3768
+ typeName: ZodFirstPartyTypeKind.ZodBoolean,
3769
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
3770
+ ...processCreateParams(params),
3771
+ });
3772
+ };
3773
+ class ZodDate extends ZodType {
3774
+ _parse(input) {
3775
+ if (this._def.coerce) {
3776
+ input.data = new Date(input.data);
3777
+ }
3778
+ const parsedType = this._getType(input);
3779
+ if (parsedType !== ZodParsedType.date) {
3780
+ const ctx = this._getOrReturnCtx(input);
3781
+ addIssueToContext(ctx, {
3782
+ code: ZodIssueCode.invalid_type,
3783
+ expected: ZodParsedType.date,
3784
+ received: ctx.parsedType,
3785
+ });
3786
+ return INVALID;
3787
+ }
3788
+ if (isNaN(input.data.getTime())) {
3789
+ const ctx = this._getOrReturnCtx(input);
3790
+ addIssueToContext(ctx, {
3791
+ code: ZodIssueCode.invalid_date,
3792
+ });
3793
+ return INVALID;
3794
+ }
3795
+ const status = new ParseStatus();
3796
+ let ctx = undefined;
3797
+ for (const check of this._def.checks) {
3798
+ if (check.kind === "min") {
3799
+ if (input.data.getTime() < check.value) {
3800
+ ctx = this._getOrReturnCtx(input, ctx);
3801
+ addIssueToContext(ctx, {
3802
+ code: ZodIssueCode.too_small,
3803
+ message: check.message,
3804
+ inclusive: true,
3805
+ exact: false,
3806
+ minimum: check.value,
3807
+ type: "date",
3808
+ });
3809
+ status.dirty();
3810
+ }
3811
+ }
3812
+ else if (check.kind === "max") {
3813
+ if (input.data.getTime() > check.value) {
3814
+ ctx = this._getOrReturnCtx(input, ctx);
3815
+ addIssueToContext(ctx, {
3816
+ code: ZodIssueCode.too_big,
3817
+ message: check.message,
3818
+ inclusive: true,
3819
+ exact: false,
3820
+ maximum: check.value,
3821
+ type: "date",
3822
+ });
3823
+ status.dirty();
3824
+ }
3825
+ }
3826
+ else {
3827
+ util.assertNever(check);
3828
+ }
3829
+ }
3830
+ return {
3831
+ status: status.value,
3832
+ value: new Date(input.data.getTime()),
3833
+ };
3834
+ }
3835
+ _addCheck(check) {
3836
+ return new ZodDate({
3837
+ ...this._def,
3838
+ checks: [...this._def.checks, check],
3839
+ });
3840
+ }
3841
+ min(minDate, message) {
3842
+ return this._addCheck({
3843
+ kind: "min",
3844
+ value: minDate.getTime(),
3845
+ message: errorUtil.toString(message),
3846
+ });
3847
+ }
3848
+ max(maxDate, message) {
3849
+ return this._addCheck({
3850
+ kind: "max",
3851
+ value: maxDate.getTime(),
3852
+ message: errorUtil.toString(message),
3853
+ });
3854
+ }
3855
+ get minDate() {
3856
+ let min = null;
3857
+ for (const ch of this._def.checks) {
3858
+ if (ch.kind === "min") {
3859
+ if (min === null || ch.value > min)
3860
+ min = ch.value;
3861
+ }
3862
+ }
3863
+ return min != null ? new Date(min) : null;
3864
+ }
3865
+ get maxDate() {
3866
+ let max = null;
3867
+ for (const ch of this._def.checks) {
3868
+ if (ch.kind === "max") {
3869
+ if (max === null || ch.value < max)
3870
+ max = ch.value;
3871
+ }
3872
+ }
3873
+ return max != null ? new Date(max) : null;
3874
+ }
3875
+ }
3876
+ ZodDate.create = (params) => {
3877
+ return new ZodDate({
3878
+ checks: [],
3879
+ coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
3880
+ typeName: ZodFirstPartyTypeKind.ZodDate,
3881
+ ...processCreateParams(params),
3882
+ });
3883
+ };
3884
+ class ZodSymbol extends ZodType {
3885
+ _parse(input) {
3886
+ const parsedType = this._getType(input);
3887
+ if (parsedType !== ZodParsedType.symbol) {
3888
+ const ctx = this._getOrReturnCtx(input);
3889
+ addIssueToContext(ctx, {
3890
+ code: ZodIssueCode.invalid_type,
3891
+ expected: ZodParsedType.symbol,
3892
+ received: ctx.parsedType,
3893
+ });
3894
+ return INVALID;
3895
+ }
3896
+ return OK(input.data);
3897
+ }
3898
+ }
3899
+ ZodSymbol.create = (params) => {
3900
+ return new ZodSymbol({
3901
+ typeName: ZodFirstPartyTypeKind.ZodSymbol,
3902
+ ...processCreateParams(params),
3903
+ });
3904
+ };
3905
+ class ZodUndefined extends ZodType {
3906
+ _parse(input) {
3907
+ const parsedType = this._getType(input);
3908
+ if (parsedType !== ZodParsedType.undefined) {
3909
+ const ctx = this._getOrReturnCtx(input);
3910
+ addIssueToContext(ctx, {
3911
+ code: ZodIssueCode.invalid_type,
3912
+ expected: ZodParsedType.undefined,
3913
+ received: ctx.parsedType,
3914
+ });
3915
+ return INVALID;
3916
+ }
3917
+ return OK(input.data);
3918
+ }
3919
+ }
3920
+ ZodUndefined.create = (params) => {
3921
+ return new ZodUndefined({
3922
+ typeName: ZodFirstPartyTypeKind.ZodUndefined,
3923
+ ...processCreateParams(params),
3924
+ });
3925
+ };
3926
+ class ZodNull extends ZodType {
3927
+ _parse(input) {
3928
+ const parsedType = this._getType(input);
3929
+ if (parsedType !== ZodParsedType.null) {
3930
+ const ctx = this._getOrReturnCtx(input);
3931
+ addIssueToContext(ctx, {
3932
+ code: ZodIssueCode.invalid_type,
3933
+ expected: ZodParsedType.null,
3934
+ received: ctx.parsedType,
3935
+ });
3936
+ return INVALID;
3937
+ }
3938
+ return OK(input.data);
3939
+ }
3940
+ }
3941
+ ZodNull.create = (params) => {
3942
+ return new ZodNull({
3943
+ typeName: ZodFirstPartyTypeKind.ZodNull,
3944
+ ...processCreateParams(params),
3945
+ });
3946
+ };
3947
+ class ZodAny extends ZodType {
3948
+ constructor() {
3949
+ super(...arguments);
3950
+ // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.
3951
+ this._any = true;
3952
+ }
3953
+ _parse(input) {
3954
+ return OK(input.data);
3955
+ }
3956
+ }
3957
+ ZodAny.create = (params) => {
3958
+ return new ZodAny({
3959
+ typeName: ZodFirstPartyTypeKind.ZodAny,
3960
+ ...processCreateParams(params),
3961
+ });
3962
+ };
3963
+ class ZodUnknown extends ZodType {
3964
+ constructor() {
3965
+ super(...arguments);
3966
+ // required
3967
+ this._unknown = true;
3968
+ }
3969
+ _parse(input) {
3970
+ return OK(input.data);
3971
+ }
3972
+ }
3973
+ ZodUnknown.create = (params) => {
3974
+ return new ZodUnknown({
3975
+ typeName: ZodFirstPartyTypeKind.ZodUnknown,
3976
+ ...processCreateParams(params),
3977
+ });
3978
+ };
3979
+ class ZodNever extends ZodType {
3980
+ _parse(input) {
3981
+ const ctx = this._getOrReturnCtx(input);
3982
+ addIssueToContext(ctx, {
3983
+ code: ZodIssueCode.invalid_type,
3984
+ expected: ZodParsedType.never,
3985
+ received: ctx.parsedType,
3986
+ });
3987
+ return INVALID;
3988
+ }
3989
+ }
3990
+ ZodNever.create = (params) => {
3991
+ return new ZodNever({
3992
+ typeName: ZodFirstPartyTypeKind.ZodNever,
3993
+ ...processCreateParams(params),
3994
+ });
3995
+ };
3996
+ class ZodVoid extends ZodType {
3997
+ _parse(input) {
3998
+ const parsedType = this._getType(input);
3999
+ if (parsedType !== ZodParsedType.undefined) {
4000
+ const ctx = this._getOrReturnCtx(input);
4001
+ addIssueToContext(ctx, {
4002
+ code: ZodIssueCode.invalid_type,
4003
+ expected: ZodParsedType.void,
4004
+ received: ctx.parsedType,
4005
+ });
4006
+ return INVALID;
4007
+ }
4008
+ return OK(input.data);
4009
+ }
4010
+ }
4011
+ ZodVoid.create = (params) => {
4012
+ return new ZodVoid({
4013
+ typeName: ZodFirstPartyTypeKind.ZodVoid,
4014
+ ...processCreateParams(params),
4015
+ });
4016
+ };
4017
+ class ZodArray extends ZodType {
4018
+ _parse(input) {
4019
+ const { ctx, status } = this._processInputParams(input);
4020
+ const def = this._def;
4021
+ if (ctx.parsedType !== ZodParsedType.array) {
4022
+ addIssueToContext(ctx, {
4023
+ code: ZodIssueCode.invalid_type,
4024
+ expected: ZodParsedType.array,
4025
+ received: ctx.parsedType,
4026
+ });
4027
+ return INVALID;
4028
+ }
4029
+ if (def.exactLength !== null) {
4030
+ const tooBig = ctx.data.length > def.exactLength.value;
4031
+ const tooSmall = ctx.data.length < def.exactLength.value;
4032
+ if (tooBig || tooSmall) {
4033
+ addIssueToContext(ctx, {
4034
+ code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
4035
+ minimum: (tooSmall ? def.exactLength.value : undefined),
4036
+ maximum: (tooBig ? def.exactLength.value : undefined),
4037
+ type: "array",
4038
+ inclusive: true,
4039
+ exact: true,
4040
+ message: def.exactLength.message,
4041
+ });
4042
+ status.dirty();
4043
+ }
4044
+ }
4045
+ if (def.minLength !== null) {
4046
+ if (ctx.data.length < def.minLength.value) {
4047
+ addIssueToContext(ctx, {
4048
+ code: ZodIssueCode.too_small,
4049
+ minimum: def.minLength.value,
4050
+ type: "array",
4051
+ inclusive: true,
4052
+ exact: false,
4053
+ message: def.minLength.message,
4054
+ });
4055
+ status.dirty();
4056
+ }
4057
+ }
4058
+ if (def.maxLength !== null) {
4059
+ if (ctx.data.length > def.maxLength.value) {
4060
+ addIssueToContext(ctx, {
4061
+ code: ZodIssueCode.too_big,
4062
+ maximum: def.maxLength.value,
4063
+ type: "array",
4064
+ inclusive: true,
4065
+ exact: false,
4066
+ message: def.maxLength.message,
4067
+ });
4068
+ status.dirty();
4069
+ }
4070
+ }
4071
+ if (ctx.common.async) {
4072
+ return Promise.all([...ctx.data].map((item, i) => {
4073
+ return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));
4074
+ })).then((result) => {
4075
+ return ParseStatus.mergeArray(status, result);
4076
+ });
4077
+ }
4078
+ const result = [...ctx.data].map((item, i) => {
4079
+ return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));
4080
+ });
4081
+ return ParseStatus.mergeArray(status, result);
4082
+ }
4083
+ get element() {
4084
+ return this._def.type;
4085
+ }
4086
+ min(minLength, message) {
4087
+ return new ZodArray({
4088
+ ...this._def,
4089
+ minLength: { value: minLength, message: errorUtil.toString(message) },
4090
+ });
4091
+ }
4092
+ max(maxLength, message) {
4093
+ return new ZodArray({
4094
+ ...this._def,
4095
+ maxLength: { value: maxLength, message: errorUtil.toString(message) },
4096
+ });
4097
+ }
4098
+ length(len, message) {
4099
+ return new ZodArray({
4100
+ ...this._def,
4101
+ exactLength: { value: len, message: errorUtil.toString(message) },
4102
+ });
4103
+ }
4104
+ nonempty(message) {
4105
+ return this.min(1, message);
4106
+ }
4107
+ }
4108
+ ZodArray.create = (schema, params) => {
4109
+ return new ZodArray({
4110
+ type: schema,
4111
+ minLength: null,
4112
+ maxLength: null,
4113
+ exactLength: null,
4114
+ typeName: ZodFirstPartyTypeKind.ZodArray,
4115
+ ...processCreateParams(params),
4116
+ });
4117
+ };
4118
+ function deepPartialify(schema) {
4119
+ if (schema instanceof ZodObject) {
4120
+ const newShape = {};
4121
+ for (const key in schema.shape) {
4122
+ const fieldSchema = schema.shape[key];
4123
+ newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
4124
+ }
4125
+ return new ZodObject({
4126
+ ...schema._def,
4127
+ shape: () => newShape,
4128
+ });
4129
+ }
4130
+ else if (schema instanceof ZodArray) {
4131
+ return new ZodArray({
4132
+ ...schema._def,
4133
+ type: deepPartialify(schema.element),
4134
+ });
4135
+ }
4136
+ else if (schema instanceof ZodOptional) {
4137
+ return ZodOptional.create(deepPartialify(schema.unwrap()));
4138
+ }
4139
+ else if (schema instanceof ZodNullable) {
4140
+ return ZodNullable.create(deepPartialify(schema.unwrap()));
4141
+ }
4142
+ else if (schema instanceof ZodTuple) {
4143
+ return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
4144
+ }
4145
+ else {
4146
+ return schema;
4147
+ }
4148
+ }
4149
+ class ZodObject extends ZodType {
4150
+ constructor() {
4151
+ super(...arguments);
4152
+ this._cached = null;
4153
+ /**
4154
+ * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.
4155
+ * If you want to pass through unknown properties, use `.passthrough()` instead.
4156
+ */
4157
+ this.nonstrict = this.passthrough;
4158
+ // extend<
4159
+ // Augmentation extends ZodRawShape,
4160
+ // NewOutput extends util.flatten<{
4161
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
4162
+ // ? Augmentation[k]["_output"]
4163
+ // : k extends keyof Output
4164
+ // ? Output[k]
4165
+ // : never;
4166
+ // }>,
4167
+ // NewInput extends util.flatten<{
4168
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
4169
+ // ? Augmentation[k]["_input"]
4170
+ // : k extends keyof Input
4171
+ // ? Input[k]
4172
+ // : never;
4173
+ // }>
4174
+ // >(
4175
+ // augmentation: Augmentation
4176
+ // ): ZodObject<
4177
+ // extendShape<T, Augmentation>,
4178
+ // UnknownKeys,
4179
+ // Catchall,
4180
+ // NewOutput,
4181
+ // NewInput
4182
+ // > {
4183
+ // return new ZodObject({
4184
+ // ...this._def,
4185
+ // shape: () => ({
4186
+ // ...this._def.shape(),
4187
+ // ...augmentation,
4188
+ // }),
4189
+ // }) as any;
4190
+ // }
4191
+ /**
4192
+ * @deprecated Use `.extend` instead
4193
+ * */
4194
+ this.augment = this.extend;
4195
+ }
4196
+ _getCached() {
4197
+ if (this._cached !== null)
4198
+ return this._cached;
4199
+ const shape = this._def.shape();
4200
+ const keys = util.objectKeys(shape);
4201
+ return (this._cached = { shape, keys });
4202
+ }
4203
+ _parse(input) {
4204
+ const parsedType = this._getType(input);
4205
+ if (parsedType !== ZodParsedType.object) {
4206
+ const ctx = this._getOrReturnCtx(input);
4207
+ addIssueToContext(ctx, {
4208
+ code: ZodIssueCode.invalid_type,
4209
+ expected: ZodParsedType.object,
4210
+ received: ctx.parsedType,
4211
+ });
4212
+ return INVALID;
4213
+ }
4214
+ const { status, ctx } = this._processInputParams(input);
4215
+ const { shape, keys: shapeKeys } = this._getCached();
4216
+ const extraKeys = [];
4217
+ if (!(this._def.catchall instanceof ZodNever &&
4218
+ this._def.unknownKeys === "strip")) {
4219
+ for (const key in ctx.data) {
4220
+ if (!shapeKeys.includes(key)) {
4221
+ extraKeys.push(key);
4222
+ }
4223
+ }
4224
+ }
4225
+ const pairs = [];
4226
+ for (const key of shapeKeys) {
4227
+ const keyValidator = shape[key];
4228
+ const value = ctx.data[key];
4229
+ pairs.push({
4230
+ key: { status: "valid", value: key },
4231
+ value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
4232
+ alwaysSet: key in ctx.data,
4233
+ });
4234
+ }
4235
+ if (this._def.catchall instanceof ZodNever) {
4236
+ const unknownKeys = this._def.unknownKeys;
4237
+ if (unknownKeys === "passthrough") {
4238
+ for (const key of extraKeys) {
4239
+ pairs.push({
4240
+ key: { status: "valid", value: key },
4241
+ value: { status: "valid", value: ctx.data[key] },
4242
+ });
4243
+ }
4244
+ }
4245
+ else if (unknownKeys === "strict") {
4246
+ if (extraKeys.length > 0) {
4247
+ addIssueToContext(ctx, {
4248
+ code: ZodIssueCode.unrecognized_keys,
4249
+ keys: extraKeys,
4250
+ });
4251
+ status.dirty();
4252
+ }
4253
+ }
4254
+ else if (unknownKeys === "strip") ;
4255
+ else {
4256
+ throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
4257
+ }
4258
+ }
4259
+ else {
4260
+ // run catchall validation
4261
+ const catchall = this._def.catchall;
4262
+ for (const key of extraKeys) {
4263
+ const value = ctx.data[key];
4264
+ pairs.push({
4265
+ key: { status: "valid", value: key },
4266
+ value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)
4267
+ ),
4268
+ alwaysSet: key in ctx.data,
4269
+ });
4270
+ }
4271
+ }
4272
+ if (ctx.common.async) {
4273
+ return Promise.resolve()
4274
+ .then(async () => {
4275
+ const syncPairs = [];
4276
+ for (const pair of pairs) {
4277
+ const key = await pair.key;
4278
+ const value = await pair.value;
4279
+ syncPairs.push({
4280
+ key,
4281
+ value,
4282
+ alwaysSet: pair.alwaysSet,
4283
+ });
4284
+ }
4285
+ return syncPairs;
4286
+ })
4287
+ .then((syncPairs) => {
4288
+ return ParseStatus.mergeObjectSync(status, syncPairs);
4289
+ });
4290
+ }
4291
+ else {
4292
+ return ParseStatus.mergeObjectSync(status, pairs);
4293
+ }
4294
+ }
4295
+ get shape() {
4296
+ return this._def.shape();
4297
+ }
4298
+ strict(message) {
4299
+ errorUtil.errToObj;
4300
+ return new ZodObject({
4301
+ ...this._def,
4302
+ unknownKeys: "strict",
4303
+ ...(message !== undefined
4304
+ ? {
4305
+ errorMap: (issue, ctx) => {
4306
+ var _a, _b, _c, _d;
4307
+ 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;
4308
+ if (issue.code === "unrecognized_keys")
4309
+ return {
4310
+ message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
4311
+ };
4312
+ return {
4313
+ message: defaultError,
4314
+ };
4315
+ },
4316
+ }
4317
+ : {}),
4318
+ });
4319
+ }
4320
+ strip() {
4321
+ return new ZodObject({
4322
+ ...this._def,
4323
+ unknownKeys: "strip",
4324
+ });
4325
+ }
4326
+ passthrough() {
4327
+ return new ZodObject({
4328
+ ...this._def,
4329
+ unknownKeys: "passthrough",
4330
+ });
4331
+ }
4332
+ // const AugmentFactory =
4333
+ // <Def extends ZodObjectDef>(def: Def) =>
4334
+ // <Augmentation extends ZodRawShape>(
4335
+ // augmentation: Augmentation
4336
+ // ): ZodObject<
4337
+ // extendShape<ReturnType<Def["shape"]>, Augmentation>,
4338
+ // Def["unknownKeys"],
4339
+ // Def["catchall"]
4340
+ // > => {
4341
+ // return new ZodObject({
4342
+ // ...def,
4343
+ // shape: () => ({
4344
+ // ...def.shape(),
4345
+ // ...augmentation,
4346
+ // }),
4347
+ // }) as any;
4348
+ // };
4349
+ extend(augmentation) {
4350
+ return new ZodObject({
4351
+ ...this._def,
4352
+ shape: () => ({
4353
+ ...this._def.shape(),
4354
+ ...augmentation,
4355
+ }),
4356
+ });
4357
+ }
4358
+ /**
4359
+ * Prior to zod@1.0.12 there was a bug in the
4360
+ * inferred type of merged objects. Please
4361
+ * upgrade if you are experiencing issues.
4362
+ */
4363
+ merge(merging) {
4364
+ const merged = new ZodObject({
4365
+ unknownKeys: merging._def.unknownKeys,
4366
+ catchall: merging._def.catchall,
4367
+ shape: () => ({
4368
+ ...this._def.shape(),
4369
+ ...merging._def.shape(),
4370
+ }),
4371
+ typeName: ZodFirstPartyTypeKind.ZodObject,
4372
+ });
4373
+ return merged;
4374
+ }
4375
+ // merge<
4376
+ // Incoming extends AnyZodObject,
4377
+ // Augmentation extends Incoming["shape"],
4378
+ // NewOutput extends {
4379
+ // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
4380
+ // ? Augmentation[k]["_output"]
4381
+ // : k extends keyof Output
4382
+ // ? Output[k]
4383
+ // : never;
4384
+ // },
4385
+ // NewInput extends {
4386
+ // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
4387
+ // ? Augmentation[k]["_input"]
4388
+ // : k extends keyof Input
4389
+ // ? Input[k]
4390
+ // : never;
4391
+ // }
4392
+ // >(
4393
+ // merging: Incoming
4394
+ // ): ZodObject<
4395
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
4396
+ // Incoming["_def"]["unknownKeys"],
4397
+ // Incoming["_def"]["catchall"],
4398
+ // NewOutput,
4399
+ // NewInput
4400
+ // > {
4401
+ // const merged: any = new ZodObject({
4402
+ // unknownKeys: merging._def.unknownKeys,
4403
+ // catchall: merging._def.catchall,
4404
+ // shape: () =>
4405
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
4406
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
4407
+ // }) as any;
4408
+ // return merged;
4409
+ // }
4410
+ setKey(key, schema) {
4411
+ return this.augment({ [key]: schema });
4412
+ }
4413
+ // merge<Incoming extends AnyZodObject>(
4414
+ // merging: Incoming
4415
+ // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
4416
+ // ZodObject<
4417
+ // extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
4418
+ // Incoming["_def"]["unknownKeys"],
4419
+ // Incoming["_def"]["catchall"]
4420
+ // > {
4421
+ // // const mergedShape = objectUtil.mergeShapes(
4422
+ // // this._def.shape(),
4423
+ // // merging._def.shape()
4424
+ // // );
4425
+ // const merged: any = new ZodObject({
4426
+ // unknownKeys: merging._def.unknownKeys,
4427
+ // catchall: merging._def.catchall,
4428
+ // shape: () =>
4429
+ // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
4430
+ // typeName: ZodFirstPartyTypeKind.ZodObject,
4431
+ // }) as any;
4432
+ // return merged;
4433
+ // }
4434
+ catchall(index) {
4435
+ return new ZodObject({
4436
+ ...this._def,
4437
+ catchall: index,
4438
+ });
4439
+ }
4440
+ pick(mask) {
4441
+ const shape = {};
4442
+ util.objectKeys(mask).forEach((key) => {
4443
+ if (mask[key] && this.shape[key]) {
4444
+ shape[key] = this.shape[key];
4445
+ }
4446
+ });
4447
+ return new ZodObject({
4448
+ ...this._def,
4449
+ shape: () => shape,
4450
+ });
4451
+ }
4452
+ omit(mask) {
4453
+ const shape = {};
4454
+ util.objectKeys(this.shape).forEach((key) => {
4455
+ if (!mask[key]) {
4456
+ shape[key] = this.shape[key];
4457
+ }
4458
+ });
4459
+ return new ZodObject({
4460
+ ...this._def,
4461
+ shape: () => shape,
4462
+ });
4463
+ }
4464
+ /**
4465
+ * @deprecated
4466
+ */
4467
+ deepPartial() {
4468
+ return deepPartialify(this);
4469
+ }
4470
+ partial(mask) {
4471
+ const newShape = {};
4472
+ util.objectKeys(this.shape).forEach((key) => {
4473
+ const fieldSchema = this.shape[key];
4474
+ if (mask && !mask[key]) {
4475
+ newShape[key] = fieldSchema;
4476
+ }
4477
+ else {
4478
+ newShape[key] = fieldSchema.optional();
4479
+ }
4480
+ });
4481
+ return new ZodObject({
4482
+ ...this._def,
4483
+ shape: () => newShape,
4484
+ });
4485
+ }
4486
+ required(mask) {
4487
+ const newShape = {};
4488
+ util.objectKeys(this.shape).forEach((key) => {
4489
+ if (mask && !mask[key]) {
4490
+ newShape[key] = this.shape[key];
4491
+ }
4492
+ else {
4493
+ const fieldSchema = this.shape[key];
4494
+ let newField = fieldSchema;
4495
+ while (newField instanceof ZodOptional) {
4496
+ newField = newField._def.innerType;
4497
+ }
4498
+ newShape[key] = newField;
4499
+ }
4500
+ });
4501
+ return new ZodObject({
4502
+ ...this._def,
4503
+ shape: () => newShape,
4504
+ });
4505
+ }
4506
+ keyof() {
4507
+ return createZodEnum(util.objectKeys(this.shape));
4508
+ }
4509
+ }
4510
+ ZodObject.create = (shape, params) => {
4511
+ return new ZodObject({
4512
+ shape: () => shape,
4513
+ unknownKeys: "strip",
4514
+ catchall: ZodNever.create(),
4515
+ typeName: ZodFirstPartyTypeKind.ZodObject,
4516
+ ...processCreateParams(params),
4517
+ });
4518
+ };
4519
+ ZodObject.strictCreate = (shape, params) => {
4520
+ return new ZodObject({
4521
+ shape: () => shape,
4522
+ unknownKeys: "strict",
4523
+ catchall: ZodNever.create(),
4524
+ typeName: ZodFirstPartyTypeKind.ZodObject,
4525
+ ...processCreateParams(params),
4526
+ });
4527
+ };
4528
+ ZodObject.lazycreate = (shape, params) => {
4529
+ return new ZodObject({
4530
+ shape,
4531
+ unknownKeys: "strip",
4532
+ catchall: ZodNever.create(),
4533
+ typeName: ZodFirstPartyTypeKind.ZodObject,
4534
+ ...processCreateParams(params),
4535
+ });
4536
+ };
4537
+ class ZodUnion extends ZodType {
4538
+ _parse(input) {
4539
+ const { ctx } = this._processInputParams(input);
4540
+ const options = this._def.options;
4541
+ function handleResults(results) {
4542
+ // return first issue-free validation if it exists
4543
+ for (const result of results) {
4544
+ if (result.result.status === "valid") {
4545
+ return result.result;
4546
+ }
4547
+ }
4548
+ for (const result of results) {
4549
+ if (result.result.status === "dirty") {
4550
+ // add issues from dirty option
4551
+ ctx.common.issues.push(...result.ctx.common.issues);
4552
+ return result.result;
4553
+ }
4554
+ }
4555
+ // return invalid
4556
+ const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
4557
+ addIssueToContext(ctx, {
4558
+ code: ZodIssueCode.invalid_union,
4559
+ unionErrors,
4560
+ });
4561
+ return INVALID;
4562
+ }
4563
+ if (ctx.common.async) {
4564
+ return Promise.all(options.map(async (option) => {
4565
+ const childCtx = {
4566
+ ...ctx,
4567
+ common: {
4568
+ ...ctx.common,
4569
+ issues: [],
4570
+ },
4571
+ parent: null,
4572
+ };
4573
+ return {
4574
+ result: await option._parseAsync({
4575
+ data: ctx.data,
4576
+ path: ctx.path,
4577
+ parent: childCtx,
4578
+ }),
4579
+ ctx: childCtx,
4580
+ };
4581
+ })).then(handleResults);
4582
+ }
4583
+ else {
4584
+ let dirty = undefined;
4585
+ const issues = [];
4586
+ for (const option of options) {
4587
+ const childCtx = {
4588
+ ...ctx,
4589
+ common: {
4590
+ ...ctx.common,
4591
+ issues: [],
4592
+ },
4593
+ parent: null,
4594
+ };
4595
+ const result = option._parseSync({
4596
+ data: ctx.data,
4597
+ path: ctx.path,
4598
+ parent: childCtx,
4599
+ });
4600
+ if (result.status === "valid") {
4601
+ return result;
4602
+ }
4603
+ else if (result.status === "dirty" && !dirty) {
4604
+ dirty = { result, ctx: childCtx };
4605
+ }
4606
+ if (childCtx.common.issues.length) {
4607
+ issues.push(childCtx.common.issues);
4608
+ }
4609
+ }
4610
+ if (dirty) {
4611
+ ctx.common.issues.push(...dirty.ctx.common.issues);
4612
+ return dirty.result;
4613
+ }
4614
+ const unionErrors = issues.map((issues) => new ZodError(issues));
4615
+ addIssueToContext(ctx, {
4616
+ code: ZodIssueCode.invalid_union,
4617
+ unionErrors,
4618
+ });
4619
+ return INVALID;
4620
+ }
4621
+ }
4622
+ get options() {
4623
+ return this._def.options;
4624
+ }
4625
+ }
4626
+ ZodUnion.create = (types, params) => {
4627
+ return new ZodUnion({
4628
+ options: types,
4629
+ typeName: ZodFirstPartyTypeKind.ZodUnion,
4630
+ ...processCreateParams(params),
4631
+ });
4632
+ };
4633
+ /////////////////////////////////////////////////////
4634
+ /////////////////////////////////////////////////////
4635
+ ////////// //////////
4636
+ ////////// ZodDiscriminatedUnion //////////
4637
+ ////////// //////////
4638
+ /////////////////////////////////////////////////////
4639
+ /////////////////////////////////////////////////////
4640
+ const getDiscriminator = (type) => {
4641
+ if (type instanceof ZodLazy) {
4642
+ return getDiscriminator(type.schema);
4643
+ }
4644
+ else if (type instanceof ZodEffects) {
4645
+ return getDiscriminator(type.innerType());
4646
+ }
4647
+ else if (type instanceof ZodLiteral) {
4648
+ return [type.value];
4649
+ }
4650
+ else if (type instanceof ZodEnum) {
4651
+ return type.options;
4652
+ }
4653
+ else if (type instanceof ZodNativeEnum) {
4654
+ // eslint-disable-next-line ban/ban
4655
+ return util.objectValues(type.enum);
4656
+ }
4657
+ else if (type instanceof ZodDefault) {
4658
+ return getDiscriminator(type._def.innerType);
4659
+ }
4660
+ else if (type instanceof ZodUndefined) {
4661
+ return [undefined];
4662
+ }
4663
+ else if (type instanceof ZodNull) {
4664
+ return [null];
4665
+ }
4666
+ else if (type instanceof ZodOptional) {
4667
+ return [undefined, ...getDiscriminator(type.unwrap())];
4668
+ }
4669
+ else if (type instanceof ZodNullable) {
4670
+ return [null, ...getDiscriminator(type.unwrap())];
4671
+ }
4672
+ else if (type instanceof ZodBranded) {
4673
+ return getDiscriminator(type.unwrap());
4674
+ }
4675
+ else if (type instanceof ZodReadonly) {
4676
+ return getDiscriminator(type.unwrap());
4677
+ }
4678
+ else if (type instanceof ZodCatch) {
4679
+ return getDiscriminator(type._def.innerType);
4680
+ }
4681
+ else {
4682
+ return [];
4683
+ }
4684
+ };
4685
+ class ZodDiscriminatedUnion extends ZodType {
4686
+ _parse(input) {
4687
+ const { ctx } = this._processInputParams(input);
4688
+ if (ctx.parsedType !== ZodParsedType.object) {
4689
+ addIssueToContext(ctx, {
4690
+ code: ZodIssueCode.invalid_type,
4691
+ expected: ZodParsedType.object,
4692
+ received: ctx.parsedType,
4693
+ });
4694
+ return INVALID;
4695
+ }
4696
+ const discriminator = this.discriminator;
4697
+ const discriminatorValue = ctx.data[discriminator];
4698
+ const option = this.optionsMap.get(discriminatorValue);
4699
+ if (!option) {
4700
+ addIssueToContext(ctx, {
4701
+ code: ZodIssueCode.invalid_union_discriminator,
4702
+ options: Array.from(this.optionsMap.keys()),
4703
+ path: [discriminator],
4704
+ });
4705
+ return INVALID;
4706
+ }
4707
+ if (ctx.common.async) {
4708
+ return option._parseAsync({
4709
+ data: ctx.data,
4710
+ path: ctx.path,
4711
+ parent: ctx,
4712
+ });
4713
+ }
4714
+ else {
4715
+ return option._parseSync({
4716
+ data: ctx.data,
4717
+ path: ctx.path,
4718
+ parent: ctx,
4719
+ });
4720
+ }
4721
+ }
4722
+ get discriminator() {
4723
+ return this._def.discriminator;
4724
+ }
4725
+ get options() {
4726
+ return this._def.options;
4727
+ }
4728
+ get optionsMap() {
4729
+ return this._def.optionsMap;
4730
+ }
4731
+ /**
4732
+ * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
4733
+ * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
4734
+ * have a different value for each object in the union.
4735
+ * @param discriminator the name of the discriminator property
4736
+ * @param types an array of object schemas
4737
+ * @param params
4738
+ */
4739
+ static create(discriminator, options, params) {
4740
+ // Get all the valid discriminator values
4741
+ const optionsMap = new Map();
4742
+ // try {
4743
+ for (const type of options) {
4744
+ const discriminatorValues = getDiscriminator(type.shape[discriminator]);
4745
+ if (!discriminatorValues.length) {
4746
+ throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
4747
+ }
4748
+ for (const value of discriminatorValues) {
4749
+ if (optionsMap.has(value)) {
4750
+ throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
4751
+ }
4752
+ optionsMap.set(value, type);
4753
+ }
4754
+ }
4755
+ return new ZodDiscriminatedUnion({
4756
+ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
4757
+ discriminator,
4758
+ options,
4759
+ optionsMap,
4760
+ ...processCreateParams(params),
4761
+ });
4762
+ }
4763
+ }
4764
+ function mergeValues(a, b) {
4765
+ const aType = getParsedType(a);
4766
+ const bType = getParsedType(b);
4767
+ if (a === b) {
4768
+ return { valid: true, data: a };
4769
+ }
4770
+ else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
4771
+ const bKeys = util.objectKeys(b);
4772
+ const sharedKeys = util
4773
+ .objectKeys(a)
4774
+ .filter((key) => bKeys.indexOf(key) !== -1);
4775
+ const newObj = { ...a, ...b };
4776
+ for (const key of sharedKeys) {
4777
+ const sharedValue = mergeValues(a[key], b[key]);
4778
+ if (!sharedValue.valid) {
4779
+ return { valid: false };
4780
+ }
4781
+ newObj[key] = sharedValue.data;
4782
+ }
4783
+ return { valid: true, data: newObj };
4784
+ }
4785
+ else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
4786
+ if (a.length !== b.length) {
4787
+ return { valid: false };
4788
+ }
4789
+ const newArray = [];
4790
+ for (let index = 0; index < a.length; index++) {
4791
+ const itemA = a[index];
4792
+ const itemB = b[index];
4793
+ const sharedValue = mergeValues(itemA, itemB);
4794
+ if (!sharedValue.valid) {
4795
+ return { valid: false };
4796
+ }
4797
+ newArray.push(sharedValue.data);
4798
+ }
4799
+ return { valid: true, data: newArray };
4800
+ }
4801
+ else if (aType === ZodParsedType.date &&
4802
+ bType === ZodParsedType.date &&
4803
+ +a === +b) {
4804
+ return { valid: true, data: a };
4805
+ }
4806
+ else {
4807
+ return { valid: false };
4808
+ }
4809
+ }
4810
+ class ZodIntersection extends ZodType {
4811
+ _parse(input) {
4812
+ const { status, ctx } = this._processInputParams(input);
4813
+ const handleParsed = (parsedLeft, parsedRight) => {
4814
+ if (isAborted(parsedLeft) || isAborted(parsedRight)) {
4815
+ return INVALID;
4816
+ }
4817
+ const merged = mergeValues(parsedLeft.value, parsedRight.value);
4818
+ if (!merged.valid) {
4819
+ addIssueToContext(ctx, {
4820
+ code: ZodIssueCode.invalid_intersection_types,
4821
+ });
4822
+ return INVALID;
4823
+ }
4824
+ if (isDirty(parsedLeft) || isDirty(parsedRight)) {
4825
+ status.dirty();
4826
+ }
4827
+ return { status: status.value, value: merged.data };
4828
+ };
4829
+ if (ctx.common.async) {
4830
+ return Promise.all([
4831
+ this._def.left._parseAsync({
4832
+ data: ctx.data,
4833
+ path: ctx.path,
4834
+ parent: ctx,
4835
+ }),
4836
+ this._def.right._parseAsync({
4837
+ data: ctx.data,
4838
+ path: ctx.path,
4839
+ parent: ctx,
4840
+ }),
4841
+ ]).then(([left, right]) => handleParsed(left, right));
4842
+ }
4843
+ else {
4844
+ return handleParsed(this._def.left._parseSync({
4845
+ data: ctx.data,
4846
+ path: ctx.path,
4847
+ parent: ctx,
4848
+ }), this._def.right._parseSync({
4849
+ data: ctx.data,
4850
+ path: ctx.path,
4851
+ parent: ctx,
4852
+ }));
4853
+ }
4854
+ }
4855
+ }
4856
+ ZodIntersection.create = (left, right, params) => {
4857
+ return new ZodIntersection({
4858
+ left: left,
4859
+ right: right,
4860
+ typeName: ZodFirstPartyTypeKind.ZodIntersection,
4861
+ ...processCreateParams(params),
4862
+ });
4863
+ };
4864
+ class ZodTuple extends ZodType {
4865
+ _parse(input) {
4866
+ const { status, ctx } = this._processInputParams(input);
4867
+ if (ctx.parsedType !== ZodParsedType.array) {
4868
+ addIssueToContext(ctx, {
4869
+ code: ZodIssueCode.invalid_type,
4870
+ expected: ZodParsedType.array,
4871
+ received: ctx.parsedType,
4872
+ });
4873
+ return INVALID;
4874
+ }
4875
+ if (ctx.data.length < this._def.items.length) {
4876
+ addIssueToContext(ctx, {
4877
+ code: ZodIssueCode.too_small,
4878
+ minimum: this._def.items.length,
4879
+ inclusive: true,
4880
+ exact: false,
4881
+ type: "array",
4882
+ });
4883
+ return INVALID;
4884
+ }
4885
+ const rest = this._def.rest;
4886
+ if (!rest && ctx.data.length > this._def.items.length) {
4887
+ addIssueToContext(ctx, {
4888
+ code: ZodIssueCode.too_big,
4889
+ maximum: this._def.items.length,
4890
+ inclusive: true,
4891
+ exact: false,
4892
+ type: "array",
4893
+ });
4894
+ status.dirty();
4895
+ }
4896
+ const items = [...ctx.data]
4897
+ .map((item, itemIndex) => {
4898
+ const schema = this._def.items[itemIndex] || this._def.rest;
4899
+ if (!schema)
4900
+ return null;
4901
+ return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
4902
+ })
4903
+ .filter((x) => !!x); // filter nulls
4904
+ if (ctx.common.async) {
4905
+ return Promise.all(items).then((results) => {
4906
+ return ParseStatus.mergeArray(status, results);
4907
+ });
4908
+ }
4909
+ else {
4910
+ return ParseStatus.mergeArray(status, items);
4911
+ }
4912
+ }
4913
+ get items() {
4914
+ return this._def.items;
4915
+ }
4916
+ rest(rest) {
4917
+ return new ZodTuple({
4918
+ ...this._def,
4919
+ rest,
4920
+ });
4921
+ }
4922
+ }
4923
+ ZodTuple.create = (schemas, params) => {
4924
+ if (!Array.isArray(schemas)) {
4925
+ throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
4926
+ }
4927
+ return new ZodTuple({
4928
+ items: schemas,
4929
+ typeName: ZodFirstPartyTypeKind.ZodTuple,
4930
+ rest: null,
4931
+ ...processCreateParams(params),
4932
+ });
4933
+ };
4934
+ class ZodRecord extends ZodType {
4935
+ get keySchema() {
4936
+ return this._def.keyType;
4937
+ }
4938
+ get valueSchema() {
4939
+ return this._def.valueType;
4940
+ }
4941
+ _parse(input) {
4942
+ const { status, ctx } = this._processInputParams(input);
4943
+ if (ctx.parsedType !== ZodParsedType.object) {
4944
+ addIssueToContext(ctx, {
4945
+ code: ZodIssueCode.invalid_type,
4946
+ expected: ZodParsedType.object,
4947
+ received: ctx.parsedType,
4948
+ });
4949
+ return INVALID;
4950
+ }
4951
+ const pairs = [];
4952
+ const keyType = this._def.keyType;
4953
+ const valueType = this._def.valueType;
4954
+ for (const key in ctx.data) {
4955
+ pairs.push({
4956
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
4957
+ value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
4958
+ alwaysSet: key in ctx.data,
4959
+ });
4960
+ }
4961
+ if (ctx.common.async) {
4962
+ return ParseStatus.mergeObjectAsync(status, pairs);
4963
+ }
4964
+ else {
4965
+ return ParseStatus.mergeObjectSync(status, pairs);
4966
+ }
4967
+ }
4968
+ get element() {
4969
+ return this._def.valueType;
4970
+ }
4971
+ static create(first, second, third) {
4972
+ if (second instanceof ZodType) {
4973
+ return new ZodRecord({
4974
+ keyType: first,
4975
+ valueType: second,
4976
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
4977
+ ...processCreateParams(third),
4978
+ });
4979
+ }
4980
+ return new ZodRecord({
4981
+ keyType: ZodString.create(),
4982
+ valueType: first,
4983
+ typeName: ZodFirstPartyTypeKind.ZodRecord,
4984
+ ...processCreateParams(second),
4985
+ });
4986
+ }
4987
+ }
4988
+ class ZodMap extends ZodType {
4989
+ get keySchema() {
4990
+ return this._def.keyType;
4991
+ }
4992
+ get valueSchema() {
4993
+ return this._def.valueType;
4994
+ }
4995
+ _parse(input) {
4996
+ const { status, ctx } = this._processInputParams(input);
4997
+ if (ctx.parsedType !== ZodParsedType.map) {
4998
+ addIssueToContext(ctx, {
4999
+ code: ZodIssueCode.invalid_type,
5000
+ expected: ZodParsedType.map,
5001
+ received: ctx.parsedType,
5002
+ });
5003
+ return INVALID;
5004
+ }
5005
+ const keyType = this._def.keyType;
5006
+ const valueType = this._def.valueType;
5007
+ const pairs = [...ctx.data.entries()].map(([key, value], index) => {
5008
+ return {
5009
+ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
5010
+ value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])),
5011
+ };
5012
+ });
5013
+ if (ctx.common.async) {
5014
+ const finalMap = new Map();
5015
+ return Promise.resolve().then(async () => {
5016
+ for (const pair of pairs) {
5017
+ const key = await pair.key;
5018
+ const value = await pair.value;
5019
+ if (key.status === "aborted" || value.status === "aborted") {
5020
+ return INVALID;
5021
+ }
5022
+ if (key.status === "dirty" || value.status === "dirty") {
5023
+ status.dirty();
5024
+ }
5025
+ finalMap.set(key.value, value.value);
5026
+ }
5027
+ return { status: status.value, value: finalMap };
5028
+ });
5029
+ }
5030
+ else {
5031
+ const finalMap = new Map();
5032
+ for (const pair of pairs) {
5033
+ const key = pair.key;
5034
+ const value = pair.value;
5035
+ if (key.status === "aborted" || value.status === "aborted") {
5036
+ return INVALID;
5037
+ }
5038
+ if (key.status === "dirty" || value.status === "dirty") {
5039
+ status.dirty();
5040
+ }
5041
+ finalMap.set(key.value, value.value);
5042
+ }
5043
+ return { status: status.value, value: finalMap };
5044
+ }
5045
+ }
5046
+ }
5047
+ ZodMap.create = (keyType, valueType, params) => {
5048
+ return new ZodMap({
5049
+ valueType,
5050
+ keyType,
5051
+ typeName: ZodFirstPartyTypeKind.ZodMap,
5052
+ ...processCreateParams(params),
5053
+ });
5054
+ };
5055
+ class ZodSet extends ZodType {
5056
+ _parse(input) {
5057
+ const { status, ctx } = this._processInputParams(input);
5058
+ if (ctx.parsedType !== ZodParsedType.set) {
5059
+ addIssueToContext(ctx, {
5060
+ code: ZodIssueCode.invalid_type,
5061
+ expected: ZodParsedType.set,
5062
+ received: ctx.parsedType,
5063
+ });
5064
+ return INVALID;
5065
+ }
5066
+ const def = this._def;
5067
+ if (def.minSize !== null) {
5068
+ if (ctx.data.size < def.minSize.value) {
5069
+ addIssueToContext(ctx, {
5070
+ code: ZodIssueCode.too_small,
5071
+ minimum: def.minSize.value,
5072
+ type: "set",
5073
+ inclusive: true,
5074
+ exact: false,
5075
+ message: def.minSize.message,
5076
+ });
5077
+ status.dirty();
5078
+ }
5079
+ }
5080
+ if (def.maxSize !== null) {
5081
+ if (ctx.data.size > def.maxSize.value) {
5082
+ addIssueToContext(ctx, {
5083
+ code: ZodIssueCode.too_big,
5084
+ maximum: def.maxSize.value,
5085
+ type: "set",
5086
+ inclusive: true,
5087
+ exact: false,
5088
+ message: def.maxSize.message,
5089
+ });
5090
+ status.dirty();
5091
+ }
5092
+ }
5093
+ const valueType = this._def.valueType;
5094
+ function finalizeSet(elements) {
5095
+ const parsedSet = new Set();
5096
+ for (const element of elements) {
5097
+ if (element.status === "aborted")
5098
+ return INVALID;
5099
+ if (element.status === "dirty")
5100
+ status.dirty();
5101
+ parsedSet.add(element.value);
5102
+ }
5103
+ return { status: status.value, value: parsedSet };
5104
+ }
5105
+ const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
5106
+ if (ctx.common.async) {
5107
+ return Promise.all(elements).then((elements) => finalizeSet(elements));
5108
+ }
5109
+ else {
5110
+ return finalizeSet(elements);
5111
+ }
5112
+ }
5113
+ min(minSize, message) {
5114
+ return new ZodSet({
5115
+ ...this._def,
5116
+ minSize: { value: minSize, message: errorUtil.toString(message) },
5117
+ });
5118
+ }
5119
+ max(maxSize, message) {
5120
+ return new ZodSet({
5121
+ ...this._def,
5122
+ maxSize: { value: maxSize, message: errorUtil.toString(message) },
5123
+ });
5124
+ }
5125
+ size(size, message) {
5126
+ return this.min(size, message).max(size, message);
5127
+ }
5128
+ nonempty(message) {
5129
+ return this.min(1, message);
5130
+ }
5131
+ }
5132
+ ZodSet.create = (valueType, params) => {
5133
+ return new ZodSet({
5134
+ valueType,
5135
+ minSize: null,
5136
+ maxSize: null,
5137
+ typeName: ZodFirstPartyTypeKind.ZodSet,
5138
+ ...processCreateParams(params),
5139
+ });
5140
+ };
5141
+ class ZodFunction extends ZodType {
5142
+ constructor() {
5143
+ super(...arguments);
5144
+ this.validate = this.implement;
5145
+ }
5146
+ _parse(input) {
5147
+ const { ctx } = this._processInputParams(input);
5148
+ if (ctx.parsedType !== ZodParsedType.function) {
5149
+ addIssueToContext(ctx, {
5150
+ code: ZodIssueCode.invalid_type,
5151
+ expected: ZodParsedType.function,
5152
+ received: ctx.parsedType,
5153
+ });
5154
+ return INVALID;
5155
+ }
5156
+ function makeArgsIssue(args, error) {
5157
+ return makeIssue({
5158
+ data: args,
5159
+ path: ctx.path,
5160
+ errorMaps: [
5161
+ ctx.common.contextualErrorMap,
5162
+ ctx.schemaErrorMap,
5163
+ getErrorMap(),
5164
+ errorMap,
5165
+ ].filter((x) => !!x),
5166
+ issueData: {
5167
+ code: ZodIssueCode.invalid_arguments,
5168
+ argumentsError: error,
5169
+ },
5170
+ });
5171
+ }
5172
+ function makeReturnsIssue(returns, error) {
5173
+ return makeIssue({
5174
+ data: returns,
5175
+ path: ctx.path,
5176
+ errorMaps: [
5177
+ ctx.common.contextualErrorMap,
5178
+ ctx.schemaErrorMap,
5179
+ getErrorMap(),
5180
+ errorMap,
5181
+ ].filter((x) => !!x),
5182
+ issueData: {
5183
+ code: ZodIssueCode.invalid_return_type,
5184
+ returnTypeError: error,
5185
+ },
5186
+ });
5187
+ }
5188
+ const params = { errorMap: ctx.common.contextualErrorMap };
5189
+ const fn = ctx.data;
5190
+ if (this._def.returns instanceof ZodPromise) {
5191
+ // Would love a way to avoid disabling this rule, but we need
5192
+ // an alias (using an arrow function was what caused 2651).
5193
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
5194
+ const me = this;
5195
+ return OK(async function (...args) {
5196
+ const error = new ZodError([]);
5197
+ const parsedArgs = await me._def.args
5198
+ .parseAsync(args, params)
5199
+ .catch((e) => {
5200
+ error.addIssue(makeArgsIssue(args, e));
5201
+ throw error;
5202
+ });
5203
+ const result = await Reflect.apply(fn, this, parsedArgs);
5204
+ const parsedReturns = await me._def.returns._def.type
5205
+ .parseAsync(result, params)
5206
+ .catch((e) => {
5207
+ error.addIssue(makeReturnsIssue(result, e));
5208
+ throw error;
5209
+ });
5210
+ return parsedReturns;
5211
+ });
5212
+ }
5213
+ else {
5214
+ // Would love a way to avoid disabling this rule, but we need
5215
+ // an alias (using an arrow function was what caused 2651).
5216
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
5217
+ const me = this;
5218
+ return OK(function (...args) {
5219
+ const parsedArgs = me._def.args.safeParse(args, params);
5220
+ if (!parsedArgs.success) {
5221
+ throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
5222
+ }
5223
+ const result = Reflect.apply(fn, this, parsedArgs.data);
5224
+ const parsedReturns = me._def.returns.safeParse(result, params);
5225
+ if (!parsedReturns.success) {
5226
+ throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
5227
+ }
5228
+ return parsedReturns.data;
5229
+ });
5230
+ }
5231
+ }
5232
+ parameters() {
5233
+ return this._def.args;
5234
+ }
5235
+ returnType() {
5236
+ return this._def.returns;
5237
+ }
5238
+ args(...items) {
5239
+ return new ZodFunction({
5240
+ ...this._def,
5241
+ args: ZodTuple.create(items).rest(ZodUnknown.create()),
5242
+ });
5243
+ }
5244
+ returns(returnType) {
5245
+ return new ZodFunction({
5246
+ ...this._def,
5247
+ returns: returnType,
5248
+ });
5249
+ }
5250
+ implement(func) {
5251
+ const validatedFunc = this.parse(func);
5252
+ return validatedFunc;
5253
+ }
5254
+ strictImplement(func) {
5255
+ const validatedFunc = this.parse(func);
5256
+ return validatedFunc;
5257
+ }
5258
+ static create(args, returns, params) {
5259
+ return new ZodFunction({
5260
+ args: (args
5261
+ ? args
5262
+ : ZodTuple.create([]).rest(ZodUnknown.create())),
5263
+ returns: returns || ZodUnknown.create(),
5264
+ typeName: ZodFirstPartyTypeKind.ZodFunction,
5265
+ ...processCreateParams(params),
5266
+ });
5267
+ }
5268
+ }
5269
+ class ZodLazy extends ZodType {
5270
+ get schema() {
5271
+ return this._def.getter();
5272
+ }
5273
+ _parse(input) {
5274
+ const { ctx } = this._processInputParams(input);
5275
+ const lazySchema = this._def.getter();
5276
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
5277
+ }
5278
+ }
5279
+ ZodLazy.create = (getter, params) => {
5280
+ return new ZodLazy({
5281
+ getter: getter,
5282
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
5283
+ ...processCreateParams(params),
5284
+ });
5285
+ };
5286
+ class ZodLiteral extends ZodType {
5287
+ _parse(input) {
5288
+ if (input.data !== this._def.value) {
5289
+ const ctx = this._getOrReturnCtx(input);
5290
+ addIssueToContext(ctx, {
5291
+ received: ctx.data,
5292
+ code: ZodIssueCode.invalid_literal,
5293
+ expected: this._def.value,
5294
+ });
5295
+ return INVALID;
5296
+ }
5297
+ return { status: "valid", value: input.data };
5298
+ }
5299
+ get value() {
5300
+ return this._def.value;
5301
+ }
5302
+ }
5303
+ ZodLiteral.create = (value, params) => {
5304
+ return new ZodLiteral({
5305
+ value: value,
5306
+ typeName: ZodFirstPartyTypeKind.ZodLiteral,
5307
+ ...processCreateParams(params),
5308
+ });
5309
+ };
5310
+ function createZodEnum(values, params) {
5311
+ return new ZodEnum({
5312
+ values,
5313
+ typeName: ZodFirstPartyTypeKind.ZodEnum,
5314
+ ...processCreateParams(params),
5315
+ });
5316
+ }
5317
+ class ZodEnum extends ZodType {
5318
+ constructor() {
5319
+ super(...arguments);
5320
+ _ZodEnum_cache.set(this, void 0);
5321
+ }
5322
+ _parse(input) {
5323
+ if (typeof input.data !== "string") {
5324
+ const ctx = this._getOrReturnCtx(input);
5325
+ const expectedValues = this._def.values;
5326
+ addIssueToContext(ctx, {
5327
+ expected: util.joinValues(expectedValues),
5328
+ received: ctx.parsedType,
5329
+ code: ZodIssueCode.invalid_type,
5330
+ });
5331
+ return INVALID;
5332
+ }
5333
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
5334
+ __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
5335
+ }
5336
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
5337
+ const ctx = this._getOrReturnCtx(input);
5338
+ const expectedValues = this._def.values;
5339
+ addIssueToContext(ctx, {
5340
+ received: ctx.data,
5341
+ code: ZodIssueCode.invalid_enum_value,
5342
+ options: expectedValues,
5343
+ });
5344
+ return INVALID;
5345
+ }
5346
+ return OK(input.data);
5347
+ }
5348
+ get options() {
5349
+ return this._def.values;
5350
+ }
5351
+ get enum() {
5352
+ const enumValues = {};
5353
+ for (const val of this._def.values) {
5354
+ enumValues[val] = val;
5355
+ }
5356
+ return enumValues;
5357
+ }
5358
+ get Values() {
5359
+ const enumValues = {};
5360
+ for (const val of this._def.values) {
5361
+ enumValues[val] = val;
5362
+ }
5363
+ return enumValues;
5364
+ }
5365
+ get Enum() {
5366
+ const enumValues = {};
5367
+ for (const val of this._def.values) {
5368
+ enumValues[val] = val;
5369
+ }
5370
+ return enumValues;
5371
+ }
5372
+ extract(values, newDef = this._def) {
5373
+ return ZodEnum.create(values, {
5374
+ ...this._def,
5375
+ ...newDef,
5376
+ });
5377
+ }
5378
+ exclude(values, newDef = this._def) {
5379
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
5380
+ ...this._def,
5381
+ ...newDef,
5382
+ });
5383
+ }
5384
+ }
5385
+ _ZodEnum_cache = new WeakMap();
5386
+ ZodEnum.create = createZodEnum;
5387
+ class ZodNativeEnum extends ZodType {
5388
+ constructor() {
5389
+ super(...arguments);
5390
+ _ZodNativeEnum_cache.set(this, void 0);
5391
+ }
5392
+ _parse(input) {
5393
+ const nativeEnumValues = util.getValidEnumValues(this._def.values);
5394
+ const ctx = this._getOrReturnCtx(input);
5395
+ if (ctx.parsedType !== ZodParsedType.string &&
5396
+ ctx.parsedType !== ZodParsedType.number) {
5397
+ const expectedValues = util.objectValues(nativeEnumValues);
5398
+ addIssueToContext(ctx, {
5399
+ expected: util.joinValues(expectedValues),
5400
+ received: ctx.parsedType,
5401
+ code: ZodIssueCode.invalid_type,
5402
+ });
5403
+ return INVALID;
5404
+ }
5405
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
5406
+ __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
5407
+ }
5408
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
5409
+ const expectedValues = util.objectValues(nativeEnumValues);
5410
+ addIssueToContext(ctx, {
5411
+ received: ctx.data,
5412
+ code: ZodIssueCode.invalid_enum_value,
5413
+ options: expectedValues,
5414
+ });
5415
+ return INVALID;
5416
+ }
5417
+ return OK(input.data);
5418
+ }
5419
+ get enum() {
5420
+ return this._def.values;
5421
+ }
5422
+ }
5423
+ _ZodNativeEnum_cache = new WeakMap();
5424
+ ZodNativeEnum.create = (values, params) => {
5425
+ return new ZodNativeEnum({
5426
+ values: values,
5427
+ typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
5428
+ ...processCreateParams(params),
5429
+ });
5430
+ };
5431
+ class ZodPromise extends ZodType {
5432
+ unwrap() {
5433
+ return this._def.type;
5434
+ }
5435
+ _parse(input) {
5436
+ const { ctx } = this._processInputParams(input);
5437
+ if (ctx.parsedType !== ZodParsedType.promise &&
5438
+ ctx.common.async === false) {
5439
+ addIssueToContext(ctx, {
5440
+ code: ZodIssueCode.invalid_type,
5441
+ expected: ZodParsedType.promise,
5442
+ received: ctx.parsedType,
5443
+ });
5444
+ return INVALID;
5445
+ }
5446
+ const promisified = ctx.parsedType === ZodParsedType.promise
5447
+ ? ctx.data
5448
+ : Promise.resolve(ctx.data);
5449
+ return OK(promisified.then((data) => {
5450
+ return this._def.type.parseAsync(data, {
5451
+ path: ctx.path,
5452
+ errorMap: ctx.common.contextualErrorMap,
5453
+ });
5454
+ }));
5455
+ }
5456
+ }
5457
+ ZodPromise.create = (schema, params) => {
5458
+ return new ZodPromise({
5459
+ type: schema,
5460
+ typeName: ZodFirstPartyTypeKind.ZodPromise,
5461
+ ...processCreateParams(params),
5462
+ });
5463
+ };
5464
+ class ZodEffects extends ZodType {
5465
+ innerType() {
5466
+ return this._def.schema;
5467
+ }
5468
+ sourceType() {
5469
+ return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects
5470
+ ? this._def.schema.sourceType()
5471
+ : this._def.schema;
5472
+ }
5473
+ _parse(input) {
5474
+ const { status, ctx } = this._processInputParams(input);
5475
+ const effect = this._def.effect || null;
5476
+ const checkCtx = {
5477
+ addIssue: (arg) => {
5478
+ addIssueToContext(ctx, arg);
5479
+ if (arg.fatal) {
5480
+ status.abort();
5481
+ }
5482
+ else {
5483
+ status.dirty();
5484
+ }
5485
+ },
5486
+ get path() {
5487
+ return ctx.path;
5488
+ },
5489
+ };
5490
+ checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
5491
+ if (effect.type === "preprocess") {
5492
+ const processed = effect.transform(ctx.data, checkCtx);
5493
+ if (ctx.common.async) {
5494
+ return Promise.resolve(processed).then(async (processed) => {
5495
+ if (status.value === "aborted")
5496
+ return INVALID;
5497
+ const result = await this._def.schema._parseAsync({
5498
+ data: processed,
5499
+ path: ctx.path,
5500
+ parent: ctx,
5501
+ });
5502
+ if (result.status === "aborted")
5503
+ return INVALID;
5504
+ if (result.status === "dirty")
5505
+ return DIRTY(result.value);
5506
+ if (status.value === "dirty")
5507
+ return DIRTY(result.value);
5508
+ return result;
5509
+ });
5510
+ }
5511
+ else {
5512
+ if (status.value === "aborted")
5513
+ return INVALID;
5514
+ const result = this._def.schema._parseSync({
5515
+ data: processed,
5516
+ path: ctx.path,
5517
+ parent: ctx,
5518
+ });
5519
+ if (result.status === "aborted")
5520
+ return INVALID;
5521
+ if (result.status === "dirty")
5522
+ return DIRTY(result.value);
5523
+ if (status.value === "dirty")
5524
+ return DIRTY(result.value);
5525
+ return result;
5526
+ }
5527
+ }
5528
+ if (effect.type === "refinement") {
5529
+ const executeRefinement = (acc) => {
5530
+ const result = effect.refinement(acc, checkCtx);
5531
+ if (ctx.common.async) {
5532
+ return Promise.resolve(result);
5533
+ }
5534
+ if (result instanceof Promise) {
5535
+ throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
5536
+ }
5537
+ return acc;
5538
+ };
5539
+ if (ctx.common.async === false) {
5540
+ const inner = this._def.schema._parseSync({
5541
+ data: ctx.data,
5542
+ path: ctx.path,
5543
+ parent: ctx,
5544
+ });
5545
+ if (inner.status === "aborted")
5546
+ return INVALID;
5547
+ if (inner.status === "dirty")
5548
+ status.dirty();
5549
+ // return value is ignored
5550
+ executeRefinement(inner.value);
5551
+ return { status: status.value, value: inner.value };
5552
+ }
5553
+ else {
5554
+ return this._def.schema
5555
+ ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
5556
+ .then((inner) => {
5557
+ if (inner.status === "aborted")
5558
+ return INVALID;
5559
+ if (inner.status === "dirty")
5560
+ status.dirty();
5561
+ return executeRefinement(inner.value).then(() => {
5562
+ return { status: status.value, value: inner.value };
5563
+ });
5564
+ });
5565
+ }
5566
+ }
5567
+ if (effect.type === "transform") {
5568
+ if (ctx.common.async === false) {
5569
+ const base = this._def.schema._parseSync({
5570
+ data: ctx.data,
5571
+ path: ctx.path,
5572
+ parent: ctx,
5573
+ });
5574
+ if (!isValid(base))
5575
+ return base;
5576
+ const result = effect.transform(base.value, checkCtx);
5577
+ if (result instanceof Promise) {
5578
+ throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
5579
+ }
5580
+ return { status: status.value, value: result };
5581
+ }
5582
+ else {
5583
+ return this._def.schema
5584
+ ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
5585
+ .then((base) => {
5586
+ if (!isValid(base))
5587
+ return base;
5588
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
5589
+ });
5590
+ }
5591
+ }
5592
+ util.assertNever(effect);
5593
+ }
5594
+ }
5595
+ ZodEffects.create = (schema, effect, params) => {
5596
+ return new ZodEffects({
5597
+ schema,
5598
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
5599
+ effect,
5600
+ ...processCreateParams(params),
5601
+ });
5602
+ };
5603
+ ZodEffects.createWithPreprocess = (preprocess, schema, params) => {
5604
+ return new ZodEffects({
5605
+ schema,
5606
+ effect: { type: "preprocess", transform: preprocess },
5607
+ typeName: ZodFirstPartyTypeKind.ZodEffects,
5608
+ ...processCreateParams(params),
5609
+ });
5610
+ };
5611
+ class ZodOptional extends ZodType {
5612
+ _parse(input) {
5613
+ const parsedType = this._getType(input);
5614
+ if (parsedType === ZodParsedType.undefined) {
5615
+ return OK(undefined);
1782
5616
  }
1783
- let outputMessage = message;
1784
- if (options.color) {
1785
- outputMessage = chalk[options.color](outputMessage);
5617
+ return this._def.innerType._parse(input);
5618
+ }
5619
+ unwrap() {
5620
+ return this._def.innerType;
5621
+ }
5622
+ }
5623
+ ZodOptional.create = (type, params) => {
5624
+ return new ZodOptional({
5625
+ innerType: type,
5626
+ typeName: ZodFirstPartyTypeKind.ZodOptional,
5627
+ ...processCreateParams(params),
5628
+ });
5629
+ };
5630
+ class ZodNullable extends ZodType {
5631
+ _parse(input) {
5632
+ const parsedType = this._getType(input);
5633
+ if (parsedType === ZodParsedType.null) {
5634
+ return OK(null);
1786
5635
  }
1787
- console.log(outputMessage);
1788
- return this;
5636
+ return this._def.innerType._parse(input);
1789
5637
  }
1790
- verbose(message, options = {}) {
1791
- if (!this.config?.verbose || this.config?.silent) {
1792
- return this;
5638
+ unwrap() {
5639
+ return this._def.innerType;
5640
+ }
5641
+ }
5642
+ ZodNullable.create = (type, params) => {
5643
+ return new ZodNullable({
5644
+ innerType: type,
5645
+ typeName: ZodFirstPartyTypeKind.ZodNullable,
5646
+ ...processCreateParams(params),
5647
+ });
5648
+ };
5649
+ class ZodDefault extends ZodType {
5650
+ _parse(input) {
5651
+ const { ctx } = this._processInputParams(input);
5652
+ let data = ctx.data;
5653
+ if (ctx.parsedType === ZodParsedType.undefined) {
5654
+ data = this._def.defaultValue();
1793
5655
  }
1794
- this.log(message, options);
1795
- return this;
5656
+ return this._def.innerType._parse({
5657
+ data,
5658
+ path: ctx.path,
5659
+ parent: ctx,
5660
+ });
1796
5661
  }
1797
- startTimer() {
1798
- this.timerStart = now();
1799
- return this;
5662
+ removeDefault() {
5663
+ return this._def.innerType;
1800
5664
  }
1801
- stopTimer(message, options = { color: 'yellow' }) {
1802
- if (!this.config?.verbose || !this.timerStart || this.config?.silent) {
1803
- return this;
5665
+ }
5666
+ ZodDefault.create = (type, params) => {
5667
+ return new ZodDefault({
5668
+ innerType: type,
5669
+ typeName: ZodFirstPartyTypeKind.ZodDefault,
5670
+ defaultValue: typeof params.default === "function"
5671
+ ? params.default
5672
+ : () => params.default,
5673
+ ...processCreateParams(params),
5674
+ });
5675
+ };
5676
+ class ZodCatch extends ZodType {
5677
+ _parse(input) {
5678
+ const { ctx } = this._processInputParams(input);
5679
+ // newCtx is used to not collect issues from inner types in ctx
5680
+ const newCtx = {
5681
+ ...ctx,
5682
+ common: {
5683
+ ...ctx.common,
5684
+ issues: [],
5685
+ },
5686
+ };
5687
+ const result = this._def.innerType._parse({
5688
+ data: newCtx.data,
5689
+ path: newCtx.path,
5690
+ parent: {
5691
+ ...newCtx,
5692
+ },
5693
+ });
5694
+ if (isAsync(result)) {
5695
+ return result.then((result) => {
5696
+ return {
5697
+ status: "valid",
5698
+ value: result.status === "valid"
5699
+ ? result.value
5700
+ : this._def.catchValue({
5701
+ get error() {
5702
+ return new ZodError(newCtx.common.issues);
5703
+ },
5704
+ input: newCtx.data,
5705
+ }),
5706
+ };
5707
+ });
1804
5708
  }
1805
- const elapsedTime = prettyMilliseconds(now() - this.timerStart);
1806
- let outputMessage = message ? `${message} (⏲ ${elapsedTime})` : `⏲ ${elapsedTime}`;
1807
- if (options.color) {
1808
- outputMessage = chalk[options.color](outputMessage);
5709
+ else {
5710
+ return {
5711
+ status: "valid",
5712
+ value: result.status === "valid"
5713
+ ? result.value
5714
+ : this._def.catchValue({
5715
+ get error() {
5716
+ return new ZodError(newCtx.common.issues);
5717
+ },
5718
+ input: newCtx.data,
5719
+ }),
5720
+ };
1809
5721
  }
1810
- console.log(outputMessage);
1811
- return this;
1812
5722
  }
1813
- startSpinner(message, options = { color: 'green' }) {
1814
- if (this.config?.silent) {
1815
- return this;
1816
- }
1817
- const spinnerMessage = options.color ? chalk[options.color](message) : message;
1818
- this.spinner = ora(spinnerMessage).start();
1819
- return this;
5723
+ removeCatch() {
5724
+ return this._def.innerType;
1820
5725
  }
1821
- stopSpinner(message = '', options = { mode: 'succeed', color: 'green' }) {
1822
- if (this.config?.silent) {
1823
- return this;
5726
+ }
5727
+ ZodCatch.create = (type, params) => {
5728
+ return new ZodCatch({
5729
+ innerType: type,
5730
+ typeName: ZodFirstPartyTypeKind.ZodCatch,
5731
+ catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
5732
+ ...processCreateParams(params),
5733
+ });
5734
+ };
5735
+ class ZodNaN extends ZodType {
5736
+ _parse(input) {
5737
+ const parsedType = this._getType(input);
5738
+ if (parsedType !== ZodParsedType.nan) {
5739
+ const ctx = this._getOrReturnCtx(input);
5740
+ addIssueToContext(ctx, {
5741
+ code: ZodIssueCode.invalid_type,
5742
+ expected: ZodParsedType.nan,
5743
+ received: ctx.parsedType,
5744
+ });
5745
+ return INVALID;
1824
5746
  }
1825
- const spinnerMessage = options?.color ? chalk[options.color](message) : message;
1826
- this.spinner?.[options.mode || 'succeed'](spinnerMessage);
1827
- this.spinner = null;
1828
- return this;
5747
+ return { status: "valid", value: input.data };
1829
5748
  }
1830
5749
  }
1831
-
1832
- function commandExecutor(handler) {
1833
- return async (argv) => {
1834
- const options = loadConfig(argv);
1835
- const logger = new Logger(options);
1836
- try {
1837
- await handler(argv, logger);
5750
+ ZodNaN.create = (params) => {
5751
+ return new ZodNaN({
5752
+ typeName: ZodFirstPartyTypeKind.ZodNaN,
5753
+ ...processCreateParams(params),
5754
+ });
5755
+ };
5756
+ const BRAND = Symbol("zod_brand");
5757
+ class ZodBranded extends ZodType {
5758
+ _parse(input) {
5759
+ const { ctx } = this._processInputParams(input);
5760
+ const data = ctx.data;
5761
+ return this._def.type._parse({
5762
+ data,
5763
+ path: ctx.path,
5764
+ parent: ctx,
5765
+ });
5766
+ }
5767
+ unwrap() {
5768
+ return this._def.type;
5769
+ }
5770
+ }
5771
+ class ZodPipeline extends ZodType {
5772
+ _parse(input) {
5773
+ const { status, ctx } = this._processInputParams(input);
5774
+ if (ctx.common.async) {
5775
+ const handleAsync = async () => {
5776
+ const inResult = await this._def.in._parseAsync({
5777
+ data: ctx.data,
5778
+ path: ctx.path,
5779
+ parent: ctx,
5780
+ });
5781
+ if (inResult.status === "aborted")
5782
+ return INVALID;
5783
+ if (inResult.status === "dirty") {
5784
+ status.dirty();
5785
+ return DIRTY(inResult.value);
5786
+ }
5787
+ else {
5788
+ return this._def.out._parseAsync({
5789
+ data: inResult.value,
5790
+ path: ctx.path,
5791
+ parent: ctx,
5792
+ });
5793
+ }
5794
+ };
5795
+ return handleAsync();
1838
5796
  }
1839
- catch (error) {
1840
- logger.log('\nFailed to execute command', { color: 'yellow' });
1841
- logger.verbose(`\nError: "${error.message}"`, { color: 'red' });
1842
- logger.log('\nThanks for using coco, make it a great day! 👋🤖', { color: 'blue' });
1843
- process.exit(0);
5797
+ else {
5798
+ const inResult = this._def.in._parseSync({
5799
+ data: ctx.data,
5800
+ path: ctx.path,
5801
+ parent: ctx,
5802
+ });
5803
+ if (inResult.status === "aborted")
5804
+ return INVALID;
5805
+ if (inResult.status === "dirty") {
5806
+ status.dirty();
5807
+ return {
5808
+ status: "dirty",
5809
+ value: inResult.value,
5810
+ };
5811
+ }
5812
+ else {
5813
+ return this._def.out._parseSync({
5814
+ data: inResult.value,
5815
+ path: ctx.path,
5816
+ parent: ctx,
5817
+ });
5818
+ }
1844
5819
  }
1845
- };
5820
+ }
5821
+ static create(a, b) {
5822
+ return new ZodPipeline({
5823
+ in: a,
5824
+ out: b,
5825
+ typeName: ZodFirstPartyTypeKind.ZodPipeline,
5826
+ });
5827
+ }
5828
+ }
5829
+ class ZodReadonly extends ZodType {
5830
+ _parse(input) {
5831
+ const result = this._def.innerType._parse(input);
5832
+ const freeze = (data) => {
5833
+ if (isValid(data)) {
5834
+ data.value = Object.freeze(data.value);
5835
+ }
5836
+ return data;
5837
+ };
5838
+ return isAsync(result)
5839
+ ? result.then((data) => freeze(data))
5840
+ : freeze(result);
5841
+ }
5842
+ unwrap() {
5843
+ return this._def.innerType;
5844
+ }
5845
+ }
5846
+ ZodReadonly.create = (type, params) => {
5847
+ return new ZodReadonly({
5848
+ innerType: type,
5849
+ typeName: ZodFirstPartyTypeKind.ZodReadonly,
5850
+ ...processCreateParams(params),
5851
+ });
5852
+ };
5853
+ function custom(check, params = {},
5854
+ /**
5855
+ * @deprecated
5856
+ *
5857
+ * Pass `fatal` into the params object instead:
5858
+ *
5859
+ * ```ts
5860
+ * z.string().custom((val) => val.length > 5, { fatal: false })
5861
+ * ```
5862
+ *
5863
+ */
5864
+ fatal) {
5865
+ if (check)
5866
+ return ZodAny.create().superRefine((data, ctx) => {
5867
+ var _a, _b;
5868
+ if (!check(data)) {
5869
+ const p = typeof params === "function"
5870
+ ? params(data)
5871
+ : typeof params === "string"
5872
+ ? { message: params }
5873
+ : params;
5874
+ const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
5875
+ const p2 = typeof p === "string" ? { message: p } : p;
5876
+ ctx.addIssue({ code: "custom", ...p2, fatal: _fatal });
5877
+ }
5878
+ });
5879
+ return ZodAny.create();
1846
5880
  }
5881
+ const late = {
5882
+ object: ZodObject.lazycreate,
5883
+ };
5884
+ var ZodFirstPartyTypeKind;
5885
+ (function (ZodFirstPartyTypeKind) {
5886
+ ZodFirstPartyTypeKind["ZodString"] = "ZodString";
5887
+ ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
5888
+ ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
5889
+ ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
5890
+ ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
5891
+ ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
5892
+ ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
5893
+ ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
5894
+ ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
5895
+ ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
5896
+ ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
5897
+ ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
5898
+ ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
5899
+ ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
5900
+ ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
5901
+ ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
5902
+ ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
5903
+ ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
5904
+ ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
5905
+ ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
5906
+ ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
5907
+ ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
5908
+ ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
5909
+ ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
5910
+ ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
5911
+ ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
5912
+ ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
5913
+ ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
5914
+ ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
5915
+ ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
5916
+ ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
5917
+ ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
5918
+ ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
5919
+ ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
5920
+ ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
5921
+ ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
5922
+ })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
5923
+ const instanceOfType = (
5924
+ // const instanceOfType = <T extends new (...args: any[]) => any>(
5925
+ cls, params = {
5926
+ message: `Input not instance of ${cls.name}`,
5927
+ }) => custom((data) => data instanceof cls, params);
5928
+ const stringType = ZodString.create;
5929
+ const numberType = ZodNumber.create;
5930
+ const nanType = ZodNaN.create;
5931
+ const bigIntType = ZodBigInt.create;
5932
+ const booleanType = ZodBoolean.create;
5933
+ const dateType = ZodDate.create;
5934
+ const symbolType = ZodSymbol.create;
5935
+ const undefinedType = ZodUndefined.create;
5936
+ const nullType = ZodNull.create;
5937
+ const anyType = ZodAny.create;
5938
+ const unknownType = ZodUnknown.create;
5939
+ const neverType = ZodNever.create;
5940
+ const voidType = ZodVoid.create;
5941
+ const arrayType = ZodArray.create;
5942
+ const objectType = ZodObject.create;
5943
+ const strictObjectType = ZodObject.strictCreate;
5944
+ const unionType = ZodUnion.create;
5945
+ const discriminatedUnionType = ZodDiscriminatedUnion.create;
5946
+ const intersectionType = ZodIntersection.create;
5947
+ const tupleType = ZodTuple.create;
5948
+ const recordType = ZodRecord.create;
5949
+ const mapType = ZodMap.create;
5950
+ const setType = ZodSet.create;
5951
+ const functionType = ZodFunction.create;
5952
+ const lazyType = ZodLazy.create;
5953
+ const literalType = ZodLiteral.create;
5954
+ const enumType = ZodEnum.create;
5955
+ const nativeEnumType = ZodNativeEnum.create;
5956
+ const promiseType = ZodPromise.create;
5957
+ const effectsType = ZodEffects.create;
5958
+ const optionalType = ZodOptional.create;
5959
+ const nullableType = ZodNullable.create;
5960
+ const preprocessType = ZodEffects.createWithPreprocess;
5961
+ const pipelineType = ZodPipeline.create;
5962
+ const ostring = () => stringType().optional();
5963
+ const onumber = () => numberType().optional();
5964
+ const oboolean = () => booleanType().optional();
5965
+ const coerce = {
5966
+ string: ((arg) => ZodString.create({ ...arg, coerce: true })),
5967
+ number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
5968
+ boolean: ((arg) => ZodBoolean.create({
5969
+ ...arg,
5970
+ coerce: true,
5971
+ })),
5972
+ bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
5973
+ date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
5974
+ };
5975
+ const NEVER = INVALID;
5976
+
5977
+ var z = /*#__PURE__*/Object.freeze({
5978
+ __proto__: null,
5979
+ defaultErrorMap: errorMap,
5980
+ setErrorMap: setErrorMap,
5981
+ getErrorMap: getErrorMap,
5982
+ makeIssue: makeIssue,
5983
+ EMPTY_PATH: EMPTY_PATH,
5984
+ addIssueToContext: addIssueToContext,
5985
+ ParseStatus: ParseStatus,
5986
+ INVALID: INVALID,
5987
+ DIRTY: DIRTY,
5988
+ OK: OK,
5989
+ isAborted: isAborted,
5990
+ isDirty: isDirty,
5991
+ isValid: isValid,
5992
+ isAsync: isAsync,
5993
+ get util () { return util; },
5994
+ get objectUtil () { return objectUtil; },
5995
+ ZodParsedType: ZodParsedType,
5996
+ getParsedType: getParsedType,
5997
+ ZodType: ZodType,
5998
+ datetimeRegex: datetimeRegex,
5999
+ ZodString: ZodString,
6000
+ ZodNumber: ZodNumber,
6001
+ ZodBigInt: ZodBigInt,
6002
+ ZodBoolean: ZodBoolean,
6003
+ ZodDate: ZodDate,
6004
+ ZodSymbol: ZodSymbol,
6005
+ ZodUndefined: ZodUndefined,
6006
+ ZodNull: ZodNull,
6007
+ ZodAny: ZodAny,
6008
+ ZodUnknown: ZodUnknown,
6009
+ ZodNever: ZodNever,
6010
+ ZodVoid: ZodVoid,
6011
+ ZodArray: ZodArray,
6012
+ ZodObject: ZodObject,
6013
+ ZodUnion: ZodUnion,
6014
+ ZodDiscriminatedUnion: ZodDiscriminatedUnion,
6015
+ ZodIntersection: ZodIntersection,
6016
+ ZodTuple: ZodTuple,
6017
+ ZodRecord: ZodRecord,
6018
+ ZodMap: ZodMap,
6019
+ ZodSet: ZodSet,
6020
+ ZodFunction: ZodFunction,
6021
+ ZodLazy: ZodLazy,
6022
+ ZodLiteral: ZodLiteral,
6023
+ ZodEnum: ZodEnum,
6024
+ ZodNativeEnum: ZodNativeEnum,
6025
+ ZodPromise: ZodPromise,
6026
+ ZodEffects: ZodEffects,
6027
+ ZodTransformer: ZodEffects,
6028
+ ZodOptional: ZodOptional,
6029
+ ZodNullable: ZodNullable,
6030
+ ZodDefault: ZodDefault,
6031
+ ZodCatch: ZodCatch,
6032
+ ZodNaN: ZodNaN,
6033
+ BRAND: BRAND,
6034
+ ZodBranded: ZodBranded,
6035
+ ZodPipeline: ZodPipeline,
6036
+ ZodReadonly: ZodReadonly,
6037
+ custom: custom,
6038
+ Schema: ZodType,
6039
+ ZodSchema: ZodType,
6040
+ late: late,
6041
+ get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
6042
+ coerce: coerce,
6043
+ any: anyType,
6044
+ array: arrayType,
6045
+ bigint: bigIntType,
6046
+ boolean: booleanType,
6047
+ date: dateType,
6048
+ discriminatedUnion: discriminatedUnionType,
6049
+ effect: effectsType,
6050
+ 'enum': enumType,
6051
+ 'function': functionType,
6052
+ 'instanceof': instanceOfType,
6053
+ intersection: intersectionType,
6054
+ lazy: lazyType,
6055
+ literal: literalType,
6056
+ map: mapType,
6057
+ nan: nanType,
6058
+ nativeEnum: nativeEnumType,
6059
+ never: neverType,
6060
+ 'null': nullType,
6061
+ nullable: nullableType,
6062
+ number: numberType,
6063
+ object: objectType,
6064
+ oboolean: oboolean,
6065
+ onumber: onumber,
6066
+ optional: optionalType,
6067
+ ostring: ostring,
6068
+ pipeline: pipelineType,
6069
+ preprocess: preprocessType,
6070
+ promise: promiseType,
6071
+ record: recordType,
6072
+ set: setType,
6073
+ strictObject: strictObjectType,
6074
+ string: stringType,
6075
+ symbol: symbolType,
6076
+ transformer: effectsType,
6077
+ tuple: tupleType,
6078
+ 'undefined': undefinedType,
6079
+ union: unionType,
6080
+ unknown: unknownType,
6081
+ 'void': voidType,
6082
+ NEVER: NEVER,
6083
+ ZodIssueCode: ZodIssueCode,
6084
+ quotelessJson: quotelessJson,
6085
+ ZodError: ZodError
6086
+ });
1847
6087
 
6088
+ const ChangelogResponseSchema = z.object({
6089
+ title: z.string(),
6090
+ content: z.string(),
6091
+ });
1848
6092
  const command$4 = 'changelog';
1849
6093
  /**
1850
6094
  * Command line options via yargs
@@ -1853,13 +6097,19 @@ const options$4 = {
1853
6097
  range: {
1854
6098
  type: 'string',
1855
6099
  alias: 'r',
1856
- description: 'Commit range e.g `HEAD~2:HEAD`',
6100
+ description: 'Commit range e.g `HEAD~2:HEAD^1` or `abc1234:def5678` (commit hashes)',
1857
6101
  },
1858
6102
  branch: {
1859
6103
  type: 'string',
1860
6104
  alias: 'b',
1861
6105
  description: 'Target branch to compare against',
1862
6106
  },
6107
+ sinceLastTag: {
6108
+ type: 'boolean',
6109
+ alias: 't',
6110
+ description: 'Generate changelog for all commits since the last tag',
6111
+ default: false,
6112
+ },
1863
6113
  i: {
1864
6114
  type: 'boolean',
1865
6115
  alias: 'interactive',
@@ -1912,6 +6162,7 @@ function getPrompt({ template, variables, fallback }) {
1912
6162
  ? new PromptTemplate({
1913
6163
  template,
1914
6164
  inputVariables: variables,
6165
+ templateFormat: 'mustache',
1915
6166
  })
1916
6167
  : fallback);
1917
6168
  }
@@ -1942,18 +6193,52 @@ function extractTicketIdFromBranchName(branchName) {
1942
6193
  return match ? match[0] : null;
1943
6194
  }
1944
6195
 
6196
+ /**
6197
+ * Formats a commit log into a readable string format.
6198
+ *
6199
+ * @param commitLog - The commit log result containing an array of commit details.
6200
+ * @returns An array of formatted commit log strings.
6201
+ *
6202
+ * Each formatted string includes:
6203
+ * - The date of the commit in square brackets.
6204
+ * - The commit message.
6205
+ * - The commit body.
6206
+ * - The commit hash in parentheses.
6207
+ * - The author's name and email in angle brackets.
6208
+ */
6209
+ const formatCommitLog = (commitLog) => {
6210
+ return commitLog.all.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6211
+ };
6212
+
6213
+ const getChangesSinceLastTag = async ({ git }) => {
6214
+ const tags = await git.tags();
6215
+ if (tags.all.length > 0) {
6216
+ const lastTag = tags.latest;
6217
+ const commitLog = await git.log({ from: lastTag });
6218
+ return formatCommitLog(commitLog);
6219
+ }
6220
+ else {
6221
+ return ['No tags found in the repository.'];
6222
+ }
6223
+ };
6224
+
1945
6225
  /**
1946
6226
  * Retrieves the commit log range between two specified commits.
1947
6227
  *
1948
- * @param from - The starting commit.
1949
- * @param to - The ending commit.
6228
+ * @param from - The starting commit (can be a commit hash, HEAD reference, or branch name).
6229
+ * @param to - The ending commit (can be a commit hash, HEAD reference, or branch name).
1950
6230
  * @param options - Additional options for retrieving the commit log range.
1951
6231
  * @returns A promise that resolves to an array of commit log messages.
1952
6232
  * @throws If there is an error retrieving the commit log range.
1953
6233
  */
1954
6234
  async function getCommitLogRange(from, to, { noMerges, git }) {
1955
6235
  try {
1956
- const logOptions = { from: `${from}^1`, to, '--no-merges': noMerges };
6236
+ // Use the git range syntax directly (from..to) which works with both commit hashes and references
6237
+ const logOptions = {
6238
+ from,
6239
+ to,
6240
+ '--no-merges': noMerges
6241
+ };
1957
6242
  const commitLog = await git.log(logOptions);
1958
6243
  return commitLog.all.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
1959
6244
  }
@@ -2075,8 +6360,17 @@ const getRepo = () => {
2075
6360
  return git;
2076
6361
  };
2077
6362
 
2078
- const template$4 = `Write informative git commit message, in the imperative, based on the diffs & file changes provided in the "Diff Summary" section.
2079
- Commit Messages must have a short description that is less than 50 characters and a longer detailed summary around 300 characters, the shorter and more concise the better.
6363
+ /**
6364
+ * Template for generating git commit messages based on code changes
6365
+ *
6366
+ * Variables:
6367
+ * - summary: Contains the diff summary of staged changes
6368
+ * - format_instructions: Instructions for the output format (JSON with title and body)
6369
+ * - additional_context: Optional user-provided context to guide the commit message generation
6370
+ * - commit_history: Optional history of previous commits for context
6371
+ */
6372
+ const template$4 = `Write informative git commit message, in the imperative, based on the diffs & file changes provided in the "Diff Summary" section.
6373
+ Commit Messages must have a short description that is less than 50 characters and a longer detailed summary around 300 characters, the shorter and more concise the better.
2080
6374
 
2081
6375
  Please follow the guidelines below when writing your commit message:
2082
6376
 
@@ -2086,15 +6380,18 @@ Please follow the guidelines below when writing your commit message:
2086
6380
  - DO NOT include any diffs or file changes in the commit message
2087
6381
  - Wrap variable, class, function, components, and dependency names in back ticks e.g. \`variable\`
2088
6382
 
2089
- {format_instructions}
6383
+ {{format_instructions}}
6384
+
6385
+ {{commit_history}}
2090
6386
 
2091
6387
  """"""
2092
- {summary}
6388
+ {{summary}}
2093
6389
  """"""
2094
6390
 
2095
- {additional}
6391
+ {{additional_context}}
2096
6392
  `;
2097
- const inputVariables$3 = ['summary', 'format_instructions', 'additional'];
6393
+ // Define the variables that will be passed to the prompt template
6394
+ const inputVariables$3 = ['summary', 'format_instructions', 'additional_context', 'commit_history'];
2098
6395
  const COMMIT_PROMPT = new PromptTemplate({
2099
6396
  template: template$4,
2100
6397
  inputVariables: inputVariables$3,
@@ -2260,9 +6557,16 @@ async function generateAndReviewLoop({ label, factory, parser, noResult, agent,
2260
6557
  result = '';
2261
6558
  continue;
2262
6559
  }
6560
+ // Only edit the result in interactive mode if approved
6561
+ result = await editResult(result, options);
6562
+ }
6563
+ else {
6564
+ // In non-interactive mode, we return the result as is to be output to stdout by the caller.
6565
+ const displayResult = reviewParser ? reviewParser(result, options) : result;
6566
+ // In non-interactive mode, ensure we return the properly formatted result
6567
+ result = displayResult;
2263
6568
  }
2264
6569
  // if we're here, we're done.
2265
- result = await editResult(result, options);
2266
6570
  continueLoop = false;
2267
6571
  }
2268
6572
  return result;
@@ -2285,7 +6589,8 @@ async function handleResult({ result, mode, interactiveModeCallback }) {
2285
6589
  break;
2286
6590
  case 'stdout':
2287
6591
  default:
2288
- process.stdout.write(result, 'utf8');
6592
+ // Ensure we write the result to stdout in non-interactive mode
6593
+ process.stdout.write(result + '\n', 'utf8');
2289
6594
  break;
2290
6595
  }
2291
6596
  process.exit(0);
@@ -2299,9 +6604,9 @@ const template$3 = `Write informative git changelog, in the imperative, based on
2299
6604
  - Depending on the size of the changes, consider breaking the changelog into sections
2300
6605
  - Avoid generlizations like "various bug fixes" or "improvements" or "enhancements"
2301
6606
 
2302
- {format_instructions}
6607
+ {{format_instructions}}
2303
6608
 
2304
- """{summary}"""`;
6609
+ """{{summary}}"""`;
2305
6610
  const inputVariables$2 = ['format_instructions', 'summary'];
2306
6611
  const CHANGELOG_PROMPT = new PromptTemplate({
2307
6612
  template: template$3,
@@ -2324,6 +6629,13 @@ const handler$4 = async (argv, logger) => {
2324
6629
  }
2325
6630
  async function factory() {
2326
6631
  const branchName = await getCurrentBranchName({ git });
6632
+ if (config.sinceLastTag) {
6633
+ logger.verbose(`Generating commit log since the last tag`, { color: 'yellow' });
6634
+ return {
6635
+ branch: branchName,
6636
+ commits: await getChangesSinceLastTag({ git, logger }),
6637
+ };
6638
+ }
2327
6639
  if (config.range && config.range.includes(':')) {
2328
6640
  const [from, to] = config.range.split(':');
2329
6641
  if (!from || !to) {
@@ -2342,7 +6654,9 @@ const handler$4 = async (argv, logger) => {
2342
6654
  commits: await getCommitLogAgainstBranch({ git, logger, targetBranch: argv.branch }),
2343
6655
  };
2344
6656
  }
2345
- logger.verbose(`No range or branch provided. Defaulting to current branch`, { color: 'yellow' });
6657
+ logger.verbose(`No range, branch, or tag option provided. Defaulting to current branch`, {
6658
+ color: 'yellow',
6659
+ });
2346
6660
  return {
2347
6661
  branch: branchName,
2348
6662
  commits: await getCommitLogCurrentBranch({ git, logger }),
@@ -2372,7 +6686,7 @@ const handler$4 = async (argv, logger) => {
2372
6686
  factory,
2373
6687
  parser,
2374
6688
  agent: async (context, options) => {
2375
- const parser = new JsonOutputParser();
6689
+ const parser = new StructuredOutputParser(ChangelogResponseSchema);
2376
6690
  const prompt = getPrompt({
2377
6691
  template: options.prompt,
2378
6692
  variables: CHANGELOG_PROMPT.inputVariables,
@@ -2414,12 +6728,16 @@ const handler$4 = async (argv, logger) => {
2414
6728
 
2415
6729
  var changelog = {
2416
6730
  command: command$4,
2417
- desc: 'Generate a changelog from current or target branch or provided commit range.',
6731
+ desc: 'Generate a changelog from current or target branch, provided commit range, or since the last tag.',
2418
6732
  builder: builder$4,
2419
6733
  handler: commandExecutor(handler$4),
2420
6734
  options: options$4,
2421
6735
  };
2422
6736
 
6737
+ const CommitMessageResponseSchema = z.object({
6738
+ title: z.string(),
6739
+ body: z.string(),
6740
+ });
2423
6741
  const command$3 = 'commit';
2424
6742
  /**
2425
6743
  * Command line options via yargs
@@ -2452,6 +6770,12 @@ const options$3 = {
2452
6770
  type: 'string',
2453
6771
  alias: 'a',
2454
6772
  },
6773
+ withPreviousCommits: {
6774
+ description: 'Include previous commits as context (specify number of commits, 0 for none)',
6775
+ type: 'number',
6776
+ default: 0,
6777
+ alias: 'p',
6778
+ },
2455
6779
  };
2456
6780
  const builder$3 = (yargs) => {
2457
6781
  return yargs.options(options$3).usage(getCommandUsageHeader(command$3));
@@ -6189,6 +10513,48 @@ async function getChanges({ git, options }) {
6189
10513
  };
6190
10514
  }
6191
10515
 
10516
+ /**
10517
+ * Format a single commit log entry into a readable string
10518
+ * @param commit - The commit log entry
10519
+ * @returns Formatted commit log string
10520
+ */
10521
+ function formatSingleCommit(commit) {
10522
+ const { hash, date, message, body, author_name } = commit;
10523
+ const shortHash = hash.substring(0, 7);
10524
+ return `Commit: ${shortHash}
10525
+ Author: ${author_name}
10526
+ Date: ${date}
10527
+ Message: ${message}
10528
+ ${body ? `\nDetails: ${body}` : ''}`;
10529
+ }
10530
+
10531
+ /**
10532
+ * Get the specified number of previous commits
10533
+ * @param options - Options for getting previous commits
10534
+ * @returns Formatted commit logs
10535
+ */
10536
+ async function getPreviousCommits(options) {
10537
+ const { git, count = 1 } = options;
10538
+ if (count <= 0) {
10539
+ return '';
10540
+ }
10541
+ try {
10542
+ const logs = await git.log({ maxCount: count });
10543
+ if (!logs || logs.total === 0) {
10544
+ return '';
10545
+ }
10546
+ // Format the commit logs
10547
+ const formattedLogs = logs.all.map((commit) => {
10548
+ return formatSingleCommit(commit);
10549
+ }).join('\n\n');
10550
+ return formattedLogs;
10551
+ }
10552
+ catch (error) {
10553
+ console.error(`Error getting previous commits: ${error.message}`);
10554
+ return '';
10555
+ }
10556
+ }
10557
+
6192
10558
  /**
6193
10559
  * Retrieves a TikToken for the specified model.
6194
10560
  *
@@ -6295,21 +10661,37 @@ const handler$3 = async (argv, logger) => {
6295
10661
  factory,
6296
10662
  parser,
6297
10663
  agent: async (context, options) => {
6298
- const parser = new JsonOutputParser();
10664
+ const parser = new StructuredOutputParser(CommitMessageResponseSchema);
6299
10665
  const prompt = getPrompt({
6300
10666
  template: options.prompt,
6301
10667
  variables: COMMIT_PROMPT.inputVariables,
6302
10668
  fallback: COMMIT_PROMPT,
6303
10669
  });
6304
10670
  const formatInstructions = "Respond with a valid JSON object, containing two fields: 'title' and 'body', both strings.";
6305
- const additionalContext = argv.additional ? `${argv.additional}` : '';
10671
+ // Get additional context if provided
10672
+ let additional_context = '';
10673
+ if (argv.additional) {
10674
+ additional_context = `## Additional Context\n${argv.additional}`;
10675
+ }
10676
+ // Get commit history if requested
10677
+ let commit_history = '';
10678
+ if (argv.withPreviousCommits > 0) {
10679
+ const commitHistoryData = await getPreviousCommits({
10680
+ git,
10681
+ count: argv.withPreviousCommits
10682
+ });
10683
+ if (commitHistoryData) {
10684
+ commit_history = `## Commit History\n${commitHistoryData}`;
10685
+ }
10686
+ }
6306
10687
  const commitMsg = await executeChain({
6307
10688
  llm,
6308
10689
  prompt,
6309
10690
  variables: {
6310
10691
  summary: context,
6311
10692
  format_instructions: formatInstructions,
6312
- additional: additionalContext,
10693
+ additional_context: additional_context,
10694
+ commit_history: commit_history,
6313
10695
  },
6314
10696
  parser,
6315
10697
  });
@@ -6799,6 +11181,10 @@ var init = {
6799
11181
  options: options$2,
6800
11182
  };
6801
11183
 
11184
+ const RecapLlmResponseSchema = z.object({
11185
+ title: z.string().optional(),
11186
+ summary: z.string().optional(),
11187
+ });
6802
11188
  const command$1 = 'recap';
6803
11189
  /**
6804
11190
  * Command line options via yargs
@@ -6833,40 +11219,11 @@ const builder$1 = (yargs) => {
6833
11219
  return yargs.options(options$1).usage(getCommandUsageHeader(command$1));
6834
11220
  };
6835
11221
 
6836
- /**
6837
- * Formats a commit log into a readable string format.
6838
- *
6839
- * @param commitLog - The commit log result containing an array of commit details.
6840
- * @returns An array of formatted commit log strings.
6841
- *
6842
- * Each formatted string includes:
6843
- * - The date of the commit in square brackets.
6844
- * - The commit message.
6845
- * - The commit body.
6846
- * - The commit hash in parentheses.
6847
- * - The author's name and email in angle brackets.
6848
- */
6849
- const formatCommitLog = (commitLog) => {
6850
- return commitLog.all.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6851
- };
6852
-
6853
11222
  const getChangesByTimestamp = async ({ since, git }) => {
6854
11223
  const commitLog = await git.log({ '--since': since });
6855
11224
  return formatCommitLog(commitLog);
6856
11225
  };
6857
11226
 
6858
- const getChangesSinceLastTag = async ({ git }) => {
6859
- const tags = await git.tags();
6860
- if (tags.all.length > 0) {
6861
- const lastTag = tags.latest;
6862
- const commitLog = await git.log({ from: lastTag });
6863
- return formatCommitLog(commitLog);
6864
- }
6865
- else {
6866
- return ['No tags found in the repository.'];
6867
- }
6868
- };
6869
-
6870
11227
  async function noResult$1({ logger }) {
6871
11228
  logger.log('No repo changes detected. 👀', { color: 'blue' });
6872
11229
  }
@@ -6876,12 +11233,12 @@ The summarization should descibe in a general sense what has changed in the repo
6876
11233
 
6877
11234
  Breaking down the changes into categories (e.g. bug fixes, new features, etc.) with markdown headings is encouraged.
6878
11235
 
6879
- {timeframe}
11236
+ {{timeframe}}
6880
11237
 
6881
- {format_instructions}
11238
+ {{format_instructions}}
6882
11239
 
6883
- """{changes}"""`;
6884
- const inputVariables$1 = ['format_instructions', 'changes', 'timeframe'];
11240
+ """{{changes}}"""`;
11241
+ const inputVariables$1 = ['timeframe', 'format_instructions', 'changes'];
6885
11242
  const RECAP_PROMPT = new PromptTemplate({
6886
11243
  template: template$1,
6887
11244
  inputVariables: inputVariables$1,
@@ -6898,10 +11255,13 @@ const handler$1 = async (argv, logger) => {
6898
11255
  }
6899
11256
  const tokenizer = await getTokenCounter(provider === 'openai' ? model : 'gpt-4o');
6900
11257
  const llm = getLlm(provider, model, config);
6901
- const INTERACTIVE = isInteractive(config);
11258
+ const INTERACTIVE = argv.interactive || isInteractive(config);
6902
11259
  if (INTERACTIVE) {
6903
11260
  logger.log(LOGO);
6904
11261
  }
11262
+ else {
11263
+ logger.setConfig({ silent: true });
11264
+ }
6905
11265
  const { 'last-month': lastMonth, 'last-tag': lastTag, yesterday, 'last-week': lastWeek } = argv;
6906
11266
  const timeframe = lastMonth
6907
11267
  ? 'last-month'
@@ -6960,7 +11320,7 @@ const handler$1 = async (argv, logger) => {
6960
11320
  async function parser(changes) {
6961
11321
  return changes.join('\n');
6962
11322
  }
6963
- await generateAndReviewLoop({
11323
+ const recapResult = await generateAndReviewLoop({
6964
11324
  label: 'recap',
6965
11325
  options: {
6966
11326
  ...config,
@@ -6985,30 +11345,57 @@ const handler$1 = async (argv, logger) => {
6985
11345
  factory,
6986
11346
  parser,
6987
11347
  agent: async (context, options) => {
6988
- const parser = new JsonOutputParser();
6989
- const formatInstructions = "Respond with a valid JSON object, containing one field: 'summary', a string.";
11348
+ const formatInstructions = "Respond with a valid JSON object, containing two fields: 'title' and 'summary', both strings.";
6990
11349
  const prompt = getPrompt({
6991
11350
  template: options.prompt,
6992
11351
  variables: RECAP_PROMPT.inputVariables,
6993
11352
  fallback: RECAP_PROMPT,
6994
11353
  });
6995
- const response = await executeChain({
6996
- llm,
6997
- prompt,
6998
- variables: {
6999
- changes: context,
7000
- format_instructions: formatInstructions,
7001
- timeframe,
7002
- },
7003
- parser,
7004
- });
7005
- return `${response.summary || 'no response'}`;
11354
+ try {
11355
+ const parser = new StructuredOutputParser(RecapLlmResponseSchema);
11356
+ const response = await executeChain({
11357
+ llm,
11358
+ prompt,
11359
+ variables: {
11360
+ changes: context,
11361
+ format_instructions: formatInstructions,
11362
+ timeframe,
11363
+ },
11364
+ parser,
11365
+ });
11366
+ return response ? `${response.title}\n\n${response.summary}` : 'no response';
11367
+ }
11368
+ catch (error) {
11369
+ const errorMessage = error instanceof Error ? error.message : String(error);
11370
+ // Log the error but don't exit
11371
+ logger.log(`Error parsing LLM response: ${errorMessage}`, { color: 'red' });
11372
+ // Always return a fallback message instead of exiting
11373
+ const fallbackMessage = `
11374
+ ## Failed to parse the response [timeframe: ${timeframe}]
11375
+ - There are changes in the codebase that couldn't be properly summarized due to a technical issue.
11376
+ - LLM encountered issues when parsing the changes.
11377
+
11378
+ ### Error encountered
11379
+
11380
+ ${errorMessage}
11381
+ `;
11382
+ return fallbackMessage;
11383
+ }
7006
11384
  },
7007
11385
  noResult: async () => {
7008
11386
  await noResult$1({ git, logger });
7009
11387
  process.exit(0);
7010
11388
  },
7011
11389
  });
11390
+ // Handle the result based on the mode (interactive or stdout)
11391
+ const MODE = (INTERACTIVE && 'interactive') || (config.recap && 'interactive') || config?.mode || 'stdout'; // Default to stdout
11392
+ handleResult({
11393
+ result: recapResult,
11394
+ interactiveModeCallback: async () => {
11395
+ logSuccess();
11396
+ },
11397
+ mode: MODE,
11398
+ });
7012
11399
  };
7013
11400
 
7014
11401
  var recap = {
@@ -7019,6 +11406,26 @@ var recap = {
7019
11406
  options: options$1,
7020
11407
  };
7021
11408
 
11409
+ const ReviewFeedbackItemSchema = z.object({
11410
+ title: z.string(),
11411
+ summary: z.string(),
11412
+ severity: z.union([
11413
+ z.literal(1),
11414
+ z.literal(2),
11415
+ z.literal(3),
11416
+ z.literal(4),
11417
+ z.literal(5),
11418
+ z.literal(6),
11419
+ z.literal(7),
11420
+ z.literal(8),
11421
+ z.literal(9),
11422
+ z.literal(10),
11423
+ ]),
11424
+ category: z.string(),
11425
+ filePath: z.string(),
11426
+ });
11427
+ // Array schema for review feedback items
11428
+ const ReviewFeedbackItemArraySchema = z.array(ReviewFeedbackItemSchema);
7022
11429
  const command = 'review';
7023
11430
  /**
7024
11431
  * Command line options via yargs
@@ -28217,11 +32624,11 @@ const template = `As an experienced software engineer, you are tasked with perfo
28217
32624
  - Breaking down the changes into categories and ranking by severity is helpful.
28218
32625
  - Output the content in a clear and concise manner that will render well in a terminal or CLI.
28219
32626
 
28220
- {format_instructions}
32627
+ {{format_instructions}}
28221
32628
 
28222
32629
  Following the formatting instructions, perform a code review on the following changes
28223
32630
 
28224
- """{changes}"""`;
32631
+ """{{changes}}"""`;
28225
32632
  const inputVariables = ['format_instructions', 'changes'];
28226
32633
  const REVIEW_PROMPT = new PromptTemplate({
28227
32634
  template,
@@ -28317,7 +32724,7 @@ const handler = async (argv, logger) => {
28317
32724
  factory,
28318
32725
  parser,
28319
32726
  agent: async (context, options) => {
28320
- const parser = new JsonOutputParser();
32727
+ const parser = new StructuredOutputParser(ReviewFeedbackItemArraySchema);
28321
32728
  const formatInstructions = "Respond with a valid JSON object, containing four fields:'title' a string, 'summary' a short summary of the problem (include line number if big file), 'severity' a numeric enum up to ten, 'category' an enum string, and 'filePath' a relative filepath to file as string.";
28322
32729
  const prompt = getPrompt({
28323
32730
  template: options.prompt,