git-coco 0.16.2 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -19,20 +19,20 @@ var ollama = require('@langchain/ollama');
19
19
  var openai = require('@langchain/openai');
20
20
  var output_parsers = require('@langchain/core/output_parsers');
21
21
  var simpleGit = require('simple-git');
22
- var pQueue = require('p-queue');
23
- var documents = require('@langchain/core/documents');
22
+ var base = require('@langchain/core/language_models/base');
23
+ var runnables = require('@langchain/core/runnables');
24
24
  var outputs = require('@langchain/core/outputs');
25
25
  var manager = require('@langchain/core/callbacks/manager');
26
- var runnables = require('@langchain/core/runnables');
27
- var base = require('@langchain/core/language_models/base');
26
+ require('@langchain/core/utils/json_patch');
27
+ var pQueue = require('p-queue');
28
+ var documents = require('@langchain/core/documents');
29
+ var diff = require('diff');
28
30
  require('@langchain/core/messages');
29
31
  require('@langchain/core/memory');
30
32
  require('@langchain/core/chat_history');
31
33
  require('@langchain/core/utils/tiktoken');
32
34
  require('@langchain/core/utils/async_caller');
33
35
  require('@langchain/core/utils/env');
34
- require('@langchain/core/utils/json_patch');
35
- var diff = require('diff');
36
36
  var minimatch = require('minimatch');
37
37
  var tiktoken = require('tiktoken');
38
38
  var child_process = require('child_process');
@@ -68,7 +68,7 @@ var readline__namespace = /*#__PURE__*/_interopNamespaceDefault(readline$1);
68
68
  /**
69
69
  * Current build version from package.json
70
70
  */
71
- const BUILD_VERSION = "0.16.2";
71
+ const BUILD_VERSION = "0.17.0";
72
72
 
73
73
  const isInteractive = (config) => {
74
74
  return config?.mode === 'interactive' || !!config?.interactive;
@@ -195,51 +195,175 @@ const SUMMARIZE_PROMPT = new prompts$1.PromptTemplate({
195
195
  template: template$5,
196
196
  });
197
197
 
198
+ /**
199
+ * Base class for all LangChain-related errors
200
+ */
201
+ class LangChainError extends Error {
202
+ constructor(message, context) {
203
+ super(message);
204
+ this.context = context;
205
+ this.name = this.constructor.name;
206
+ }
207
+ }
208
+ /**
209
+ * Configuration-related errors (invalid service configs, missing settings, etc.)
210
+ */
211
+ class LangChainConfigurationError extends LangChainError {
212
+ constructor(message, context) {
213
+ super(message, context);
214
+ }
215
+ }
216
+ /**
217
+ * Input validation errors (missing required parameters, invalid types, etc.)
218
+ */
219
+ class LangChainValidationError extends LangChainError {
220
+ constructor(message, context) {
221
+ super(message, context);
222
+ }
223
+ }
224
+ /**
225
+ * Runtime execution errors (LLM failures, parsing errors, etc.)
226
+ */
227
+ class LangChainExecutionError extends LangChainError {
228
+ constructor(message, context) {
229
+ super(message, context);
230
+ }
231
+ }
232
+ /**
233
+ * Authentication-related errors (missing API keys, invalid credentials, etc.)
234
+ */
235
+ class LangChainAuthenticationError extends LangChainError {
236
+ constructor(message, context) {
237
+ super(message, context);
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Validates that a required parameter is not null or undefined
243
+ */
244
+ function validateRequired(value, paramName, functionName) {
245
+ if (value === null || value === undefined) {
246
+ throw new LangChainValidationError(`${functionName ? `${functionName}: ` : ''}Required parameter '${paramName}' is missing`, { paramName, functionName, value });
247
+ }
248
+ }
249
+ /**
250
+ * Validates that a string parameter is not empty
251
+ */
252
+ function validateNonEmptyString(value, paramName, functionName) {
253
+ validateRequired(value, paramName, functionName);
254
+ if (typeof value !== 'string' || value.trim() === '') {
255
+ throw new LangChainValidationError(`${functionName ? `${functionName}: ` : ''}Parameter '${paramName}' must be a non-empty string`, { paramName, functionName, value, type: typeof value });
256
+ }
257
+ }
258
+ /**
259
+ * Validates that an array parameter is not empty
260
+ */
261
+ function validateNonEmptyArray(value, paramName, functionName) {
262
+ validateRequired(value, paramName, functionName);
263
+ if (!Array.isArray(value) || value.length === 0) {
264
+ throw new LangChainValidationError(`${functionName ? `${functionName}: ` : ''}Parameter '${paramName}' must be a non-empty array`, { paramName, functionName, value, isArray: Array.isArray(value), length: Array.isArray(value) ? value.length : undefined });
265
+ }
266
+ }
267
+ /**
268
+ * Validates that a provider is supported
269
+ */
270
+ function validateProvider(provider, functionName) {
271
+ const validProviders = ['openai', 'anthropic', 'ollama'];
272
+ if (!validProviders.includes(provider)) {
273
+ throw new LangChainConfigurationError(`${functionName ? `${functionName}: ` : ''}Invalid provider '${provider}'. Supported providers: ${validProviders.join(', ')}`, { provider, validProviders, functionName });
274
+ }
275
+ }
276
+ /**
277
+ * Validates that a model is valid for the given provider
278
+ */
279
+ function validateModel(model, provider, functionName) {
280
+ validateRequired(model, 'model', functionName);
281
+ if (typeof model !== 'string' || model.trim() === '') {
282
+ throw new LangChainValidationError(`${functionName ? `${functionName}: ` : ''}Model must be a non-empty string`, { model, provider, functionName });
283
+ }
284
+ // Additional provider-specific validation could be added here
285
+ // For now, we trust the TypeScript types
286
+ }
287
+ /**
288
+ * Validates that a service configuration is complete and valid
289
+ */
290
+ function validateServiceConfig(service, functionName) {
291
+ validateRequired(service, 'service', functionName);
292
+ if (typeof service !== 'object') {
293
+ throw new LangChainConfigurationError(`${functionName ? `${functionName}: ` : ''}Service configuration must be an object`, { service, functionName });
294
+ }
295
+ const serviceObj = service;
296
+ validateProvider(serviceObj.provider, functionName);
297
+ validateModel(serviceObj.model, serviceObj.provider, functionName);
298
+ // Validate authentication
299
+ if (!serviceObj.authentication || typeof serviceObj.authentication !== 'object') {
300
+ throw new LangChainConfigurationError(`${functionName ? `${functionName}: ` : ''}Service configuration must include authentication`, { service, functionName });
301
+ }
302
+ }
303
+
198
304
  /**
199
305
  * Retrieves the provider and model from the given configuration object.
200
306
  * @param config The configuration object.
201
307
  * @returns An object containing the provider and model.
202
- * @throws Error if the configuration is invalid or missing required properties.
308
+ * @throws LangChainConfigurationError if the configuration is invalid or missing required properties.
203
309
  */
204
310
  function getModelAndProviderFromConfig(config) {
311
+ validateRequired(config, 'config', 'getModelAndProviderFromConfig');
205
312
  if (!config.service) {
206
- throw new Error('Invalid service: undefined');
313
+ throw new LangChainConfigurationError('getModelAndProviderFromConfig: Service configuration is missing', { config });
207
314
  }
315
+ validateServiceConfig(config.service, 'getModelAndProviderFromConfig');
208
316
  const { provider, model } = config.service;
209
- if (!model || !provider) {
210
- throw new Error(`Invalid service: ${config.service}`);
211
- }
212
317
  return { provider, model };
213
318
  }
214
319
  /**
215
320
  * Retrieve appropriate API key based on selected model
216
- * @param service
217
- * @param options
218
- * @returns API Key
321
+ * @param config The configuration object
322
+ * @returns API Key or empty string if no authentication required
323
+ * @throws LangChainAuthenticationError if authentication is required but missing
219
324
  */
220
325
  function getApiKeyForModel(config) {
221
- const { provider } = getModelAndProviderFromConfig(config);
222
- switch (provider) {
223
- case 'openai':
224
- return getDefaultServiceApiKey(config);
225
- default:
226
- return getDefaultServiceApiKey(config);
227
- }
326
+ validateRequired(config, 'config', 'getApiKeyForModel');
327
+ // This function now simply delegates to getDefaultServiceApiKey
328
+ // The switch statement was unnecessary since all providers use the same logic
329
+ return getDefaultServiceApiKey(config);
228
330
  }
229
331
  /**
230
332
  * Retrieves the default service API key from the given configuration.
231
333
  * @param config The configuration object.
232
- * @returns The default service API key.
334
+ * @returns The default service API key or empty string for services that don't require authentication.
335
+ * @throws LangChainAuthenticationError if authentication is required but invalid.
233
336
  */
234
337
  function getDefaultServiceApiKey(config) {
338
+ validateRequired(config, 'config', 'getDefaultServiceApiKey');
339
+ validateServiceConfig(config.service, 'getDefaultServiceApiKey');
235
340
  const service = config.service;
341
+ const { provider } = service;
342
+ // Check if authentication is required for this provider
343
+ const requiresAuth = provider === 'openai' || provider === 'anthropic';
236
344
  if (service.authentication.type === 'APIKey') {
237
- return service.authentication.credentials?.apiKey;
345
+ const apiKey = service.authentication.credentials?.apiKey;
346
+ if (requiresAuth && (!apiKey || apiKey.trim() === '')) {
347
+ throw new LangChainAuthenticationError(`getDefaultServiceApiKey: API key is required for ${provider} provider but not provided`, { provider, authenticationType: service.authentication.type });
348
+ }
349
+ return apiKey || '';
350
+ }
351
+ if (service.authentication.type === 'OAuth') {
352
+ const token = service.authentication.credentials?.token;
353
+ if (requiresAuth && (!token || token.trim() === '')) {
354
+ throw new LangChainAuthenticationError(`getDefaultServiceApiKey: OAuth token is required for ${provider} provider but not provided`, { provider, authenticationType: service.authentication.type });
355
+ }
356
+ return token || '';
238
357
  }
239
- else if (service.authentication.type === 'OAuth') {
240
- return service.authentication.credentials?.token;
358
+ if (service.authentication.type === 'None') {
359
+ if (requiresAuth) {
360
+ throw new LangChainAuthenticationError(`getDefaultServiceApiKey: ${provider} provider requires authentication but 'None' was configured`, { provider, authenticationType: service.authentication.type });
361
+ }
362
+ return '';
241
363
  }
242
- return '';
364
+ // This should never be reached due to TypeScript type checking, but included for safety
365
+ const authType = service.authentication.type;
366
+ throw new LangChainConfigurationError(`getDefaultServiceApiKey: Unknown authentication type '${authType}'`, { provider, authentication: service.authentication });
243
367
  }
244
368
  const DEFAULT_OPENAI_LLM_SERVICE = {
245
369
  provider: 'openai',
@@ -253,6 +377,17 @@ const DEFAULT_OPENAI_LLM_SERVICE = {
253
377
  },
254
378
  },
255
379
  };
380
+ const DEFAULT_ANTHROPIC_LLM_SERVICE = {
381
+ provider: 'anthropic',
382
+ model: 'claude-3-5-sonnet-20240620',
383
+ temperature: 0.32,
384
+ authentication: {
385
+ type: 'APIKey',
386
+ credentials: {
387
+ apiKey: '',
388
+ },
389
+ },
390
+ };
256
391
  const DEFAULT_OLLAMA_LLM_SERVICE = {
257
392
  provider: 'ollama',
258
393
  model: 'llama3',
@@ -260,24 +395,33 @@ const DEFAULT_OLLAMA_LLM_SERVICE = {
260
395
  maxConcurrent: 1,
261
396
  tokenLimit: 2024,
262
397
  temperature: 0.4,
398
+ maxParsingAttempts: 3,
263
399
  authentication: {
264
400
  type: 'None',
265
401
  credentials: undefined,
266
402
  },
267
403
  };
268
404
  /**
269
- * Retrieves the default service configuration based on the provided alias and optional model.
270
- * @param provider - The alias of the service.
271
- * @param model - The optional model to be used.
272
- * @returns The default service configuration.
273
- * @throws Error if the alias is invalid or undefined.
405
+ * Retrieves the default service configuration based on the provided provider and optional model.
406
+ * @param provider - The LLM provider (openai, anthropic, ollama).
407
+ * @param model - The optional model to be used. If not provided, uses the default model for the provider.
408
+ * @returns The default service configuration for the specified provider.
409
+ * @throws LangChainConfigurationError if the provider is invalid or unsupported.
274
410
  */
275
411
  function getDefaultServiceConfigFromAlias(provider, model) {
412
+ validateRequired(provider, 'provider', 'getDefaultServiceConfigFromAlias');
413
+ // Validate model if provided
414
+ if (model !== undefined) {
415
+ validateRequired(model, 'model', 'getDefaultServiceConfigFromAlias');
416
+ if (typeof model !== 'string' || model.trim() === '') {
417
+ throw new LangChainConfigurationError('getDefaultServiceConfigFromAlias: Model must be a non-empty string when provided', { provider, model });
418
+ }
419
+ }
276
420
  switch (provider) {
277
421
  case 'anthropic':
278
422
  return {
279
- ...DEFAULT_OPENAI_LLM_SERVICE,
280
- model: model || DEFAULT_OPENAI_LLM_SERVICE.model,
423
+ ...DEFAULT_ANTHROPIC_LLM_SERVICE,
424
+ model: model || DEFAULT_ANTHROPIC_LLM_SERVICE.model,
281
425
  };
282
426
  case 'ollama':
283
427
  return {
@@ -285,11 +429,12 @@ function getDefaultServiceConfigFromAlias(provider, model) {
285
429
  model: model || DEFAULT_OLLAMA_LLM_SERVICE.model,
286
430
  };
287
431
  case 'openai':
288
- default:
289
432
  return {
290
433
  ...DEFAULT_OPENAI_LLM_SERVICE,
291
434
  model: model || DEFAULT_OPENAI_LLM_SERVICE.model,
292
435
  };
436
+ default:
437
+ throw new LangChainConfigurationError(`getDefaultServiceConfigFromAlias: Unsupported provider '${provider}'. Supported providers: openai, anthropic, ollama`, { provider, supportedProviders: ['openai', 'anthropic', 'ollama'] });
293
438
  }
294
439
  }
295
440
 
@@ -915,6 +1060,11 @@ const schema$1 = {
915
1060
  }
916
1061
  },
917
1062
  "additionalProperties": false
1063
+ },
1064
+ "maxParsingAttempts": {
1065
+ "type": "number",
1066
+ "description": "The maximum number of attempts for schema parsing with retry logic.",
1067
+ "default": 3
918
1068
  }
919
1069
  },
920
1070
  "required": [
@@ -1005,6 +1155,9 @@ const schema$1 = {
1005
1155
  "OllamaModel": {
1006
1156
  "type": "string",
1007
1157
  "enum": [
1158
+ "deepseek-r1:1.5b",
1159
+ "deepseek-r1:8b",
1160
+ "deepseek-r1:32b",
1008
1161
  "codegemma:2b",
1009
1162
  "codegemma:7b-code",
1010
1163
  "codegemma",
@@ -1036,9 +1189,11 @@ const schema$1 = {
1036
1189
  "llama3.2:latest",
1037
1190
  "llama3.2:1b",
1038
1191
  "llama3.2:3b",
1039
- "llama3.2:1b-instruct-fp16",
1040
- "llama3.2:1b-instruct-q3_K_M",
1041
1192
  "llama3",
1193
+ "llava-llama3:latest",
1194
+ "dolphin-llama3:latest",
1195
+ "dolphin-llama3:8b",
1196
+ "dolphin-llama3:70b",
1042
1197
  "mistral:7b",
1043
1198
  "mistral:latest",
1044
1199
  "mistral:text",
@@ -1054,18 +1209,28 @@ const schema$1 = {
1054
1209
  "qwen2:1.5b",
1055
1210
  "qwen2:72b-text",
1056
1211
  "qwen2:72b",
1057
- "qwen2"
1212
+ "qwen2",
1213
+ "qwen2.5-coder:latest",
1214
+ "qwen2.5-coder:0.5b",
1215
+ "qwen2.5-coder:1.5b",
1216
+ "qwen2.5-coder:3b",
1217
+ "qwen2.5-coder:7b",
1218
+ "qwen2.5-coder:14b",
1219
+ "qwen2.5-coder:32b"
1058
1220
  ]
1059
1221
  },
1060
1222
  "AnthropicModel": {
1061
1223
  "type": "string",
1062
1224
  "enum": [
1225
+ "claude-sonnet-4-0",
1226
+ "claude-3-7-sonnet-latest",
1227
+ "claude-3-5-haiku-latest",
1228
+ "claude-3-5-sonnet-latest",
1229
+ "claude-3-5-sonnet-20241022",
1063
1230
  "claude-3-5-sonnet-20240620",
1064
1231
  "claude-3-opus-20240229",
1065
1232
  "claude-3-sonnet-20240229",
1066
- "claude-3-haiku-20240307",
1067
- "claude-2.1",
1068
- "claude-2.0"
1233
+ "claude-3-haiku-20240307"
1069
1234
  ]
1070
1235
  },
1071
1236
  "Callbacks": {
@@ -1510,6 +1675,11 @@ const schema$1 = {
1510
1675
  }
1511
1676
  },
1512
1677
  "additionalProperties": false
1678
+ },
1679
+ "maxParsingAttempts": {
1680
+ "type": "number",
1681
+ "description": "The maximum number of attempts for schema parsing with retry logic.",
1682
+ "default": 3
1513
1683
  }
1514
1684
  },
1515
1685
  "required": [
@@ -1656,6 +1826,11 @@ const schema$1 = {
1656
1826
  }
1657
1827
  },
1658
1828
  "additionalProperties": false
1829
+ },
1830
+ "maxParsingAttempts": {
1831
+ "type": "number",
1832
+ "description": "The maximum number of attempts for schema parsing with retry logic.",
1833
+ "default": 3
1659
1834
  }
1660
1835
  },
1661
1836
  "required": [
@@ -1875,7 +2050,7 @@ function commandExecutor(handler) {
1875
2050
 
1876
2051
  var util;
1877
2052
  (function (util) {
1878
- util.assertEqual = (val) => val;
2053
+ util.assertEqual = (_) => { };
1879
2054
  function assertIs(_arg) { }
1880
2055
  util.assertIs = assertIs;
1881
2056
  function assertNever(_x) {
@@ -1922,11 +2097,9 @@ var util;
1922
2097
  };
1923
2098
  util.isInteger = typeof Number.isInteger === "function"
1924
2099
  ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
1925
- : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
2100
+ : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
1926
2101
  function joinValues(array, separator = " | ") {
1927
- return array
1928
- .map((val) => (typeof val === "string" ? `'${val}'` : val))
1929
- .join(separator);
2102
+ return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator);
1930
2103
  }
1931
2104
  util.joinValues = joinValues;
1932
2105
  util.jsonStringifyReplacer = (_, value) => {
@@ -1975,7 +2148,7 @@ const getParsedType = (data) => {
1975
2148
  case "string":
1976
2149
  return ZodParsedType.string;
1977
2150
  case "number":
1978
- return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
2151
+ return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
1979
2152
  case "boolean":
1980
2153
  return ZodParsedType.boolean;
1981
2154
  case "function":
@@ -1991,10 +2164,7 @@ const getParsedType = (data) => {
1991
2164
  if (data === null) {
1992
2165
  return ZodParsedType.null;
1993
2166
  }
1994
- if (data.then &&
1995
- typeof data.then === "function" &&
1996
- data.catch &&
1997
- typeof data.catch === "function") {
2167
+ if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
1998
2168
  return ZodParsedType.promise;
1999
2169
  }
2000
2170
  if (typeof Map !== "undefined" && data instanceof Map) {
@@ -2030,10 +2200,6 @@ const ZodIssueCode = util.arrayToEnum([
2030
2200
  "not_multiple_of",
2031
2201
  "not_finite",
2032
2202
  ]);
2033
- const quotelessJson = (obj) => {
2034
- const json = JSON.stringify(obj, null, 2);
2035
- return json.replace(/"([^"]+)":/g, "$1:");
2036
- };
2037
2203
  class ZodError extends Error {
2038
2204
  get errors() {
2039
2205
  return this.issues;
@@ -2126,8 +2292,9 @@ class ZodError extends Error {
2126
2292
  const formErrors = [];
2127
2293
  for (const sub of this.issues) {
2128
2294
  if (sub.path.length > 0) {
2129
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
2130
- fieldErrors[sub.path[0]].push(mapper(sub));
2295
+ const firstEl = sub.path[0];
2296
+ fieldErrors[firstEl] = fieldErrors[firstEl] || [];
2297
+ fieldErrors[firstEl].push(mapper(sub));
2131
2298
  }
2132
2299
  else {
2133
2300
  formErrors.push(mapper(sub));
@@ -2210,17 +2377,11 @@ const errorMap = (issue, _ctx) => {
2210
2377
  else if (issue.type === "string")
2211
2378
  message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;
2212
2379
  else if (issue.type === "number")
2213
- message = `Number must be ${issue.exact
2214
- ? `exactly equal to `
2215
- : issue.inclusive
2216
- ? `greater than or equal to `
2217
- : `greater than `}${issue.minimum}`;
2380
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
2381
+ else if (issue.type === "bigint")
2382
+ message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;
2218
2383
  else if (issue.type === "date")
2219
- message = `Date must be ${issue.exact
2220
- ? `exactly equal to `
2221
- : issue.inclusive
2222
- ? `greater than or equal to `
2223
- : `greater than `}${new Date(Number(issue.minimum))}`;
2384
+ message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;
2224
2385
  else
2225
2386
  message = "Invalid input";
2226
2387
  break;
@@ -2230,23 +2391,11 @@ const errorMap = (issue, _ctx) => {
2230
2391
  else if (issue.type === "string")
2231
2392
  message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;
2232
2393
  else if (issue.type === "number")
2233
- message = `Number must be ${issue.exact
2234
- ? `exactly`
2235
- : issue.inclusive
2236
- ? `less than or equal to`
2237
- : `less than`} ${issue.maximum}`;
2394
+ message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
2238
2395
  else if (issue.type === "bigint")
2239
- message = `BigInt must be ${issue.exact
2240
- ? `exactly`
2241
- : issue.inclusive
2242
- ? `less than or equal to`
2243
- : `less than`} ${issue.maximum}`;
2396
+ message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;
2244
2397
  else if (issue.type === "date")
2245
- message = `Date must be ${issue.exact
2246
- ? `exactly`
2247
- : issue.inclusive
2248
- ? `smaller than or equal to`
2249
- : `smaller than`} ${new Date(Number(issue.maximum))}`;
2398
+ message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;
2250
2399
  else
2251
2400
  message = "Invalid input";
2252
2401
  break;
@@ -2268,11 +2417,9 @@ const errorMap = (issue, _ctx) => {
2268
2417
  }
2269
2418
  return { message };
2270
2419
  };
2420
+ var defaultErrorMap = errorMap;
2271
2421
 
2272
- let overrideErrorMap = errorMap;
2273
- function setErrorMap(map) {
2274
- overrideErrorMap = map;
2275
- }
2422
+ let overrideErrorMap = defaultErrorMap;
2276
2423
  function getErrorMap() {
2277
2424
  return overrideErrorMap;
2278
2425
  }
@@ -2305,7 +2452,6 @@ const makeIssue = (params) => {
2305
2452
  message: errorMessage,
2306
2453
  };
2307
2454
  };
2308
- const EMPTY_PATH = [];
2309
2455
  function addIssueToContext(ctx, issueData) {
2310
2456
  const overrideMap = getErrorMap();
2311
2457
  const issue = makeIssue({
@@ -2316,7 +2462,7 @@ function addIssueToContext(ctx, issueData) {
2316
2462
  ctx.common.contextualErrorMap, // contextual error map is first priority
2317
2463
  ctx.schemaErrorMap, // then schema-bound map if available
2318
2464
  overrideMap, // then global override map
2319
- overrideMap === errorMap ? undefined : errorMap, // then global default map
2465
+ overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map
2320
2466
  ].filter((x) => !!x),
2321
2467
  });
2322
2468
  ctx.common.issues.push(issue);
@@ -2368,8 +2514,7 @@ class ParseStatus {
2368
2514
  status.dirty();
2369
2515
  if (value.status === "dirty")
2370
2516
  status.dirty();
2371
- if (key.value !== "__proto__" &&
2372
- (typeof value.value !== "undefined" || pair.alwaysSet)) {
2517
+ if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
2373
2518
  finalObject[key.value] = value.value;
2374
2519
  }
2375
2520
  }
@@ -2386,46 +2531,13 @@ const isDirty = (x) => x.status === "dirty";
2386
2531
  const isValid = (x) => x.status === "valid";
2387
2532
  const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;
2388
2533
 
2389
- /******************************************************************************
2390
- Copyright (c) Microsoft Corporation.
2391
-
2392
- Permission to use, copy, modify, and/or distribute this software for any
2393
- purpose with or without fee is hereby granted.
2394
-
2395
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
2396
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
2397
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
2398
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
2399
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
2400
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
2401
- PERFORMANCE OF THIS SOFTWARE.
2402
- ***************************************************************************** */
2403
-
2404
- function __classPrivateFieldGet(receiver, state, kind, f) {
2405
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
2406
- 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");
2407
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
2408
- }
2409
-
2410
- function __classPrivateFieldSet(receiver, state, value, kind, f) {
2411
- if (kind === "m") throw new TypeError("Private method is not writable");
2412
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
2413
- 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");
2414
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
2415
- }
2416
-
2417
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
2418
- var e = new Error(message);
2419
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
2420
- };
2421
-
2422
2534
  var errorUtil;
2423
2535
  (function (errorUtil) {
2424
2536
  errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
2425
- errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
2537
+ // biome-ignore lint:
2538
+ errorUtil.toString = (message) => typeof message === "string" ? message : message?.message;
2426
2539
  })(errorUtil || (errorUtil = {}));
2427
2540
 
2428
- var _ZodEnum_cache, _ZodNativeEnum_cache;
2429
2541
  class ParseInputLazyPath {
2430
2542
  constructor(parent, value, path, key) {
2431
2543
  this._cachedPath = [];
@@ -2436,7 +2548,7 @@ class ParseInputLazyPath {
2436
2548
  }
2437
2549
  get path() {
2438
2550
  if (!this._cachedPath.length) {
2439
- if (this._key instanceof Array) {
2551
+ if (Array.isArray(this._key)) {
2440
2552
  this._cachedPath.push(...this._path, ...this._key);
2441
2553
  }
2442
2554
  else {
@@ -2476,17 +2588,16 @@ function processCreateParams(params) {
2476
2588
  if (errorMap)
2477
2589
  return { errorMap: errorMap, description };
2478
2590
  const customMap = (iss, ctx) => {
2479
- var _a, _b;
2480
2591
  const { message } = params;
2481
2592
  if (iss.code === "invalid_enum_value") {
2482
- return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
2593
+ return { message: message ?? ctx.defaultError };
2483
2594
  }
2484
2595
  if (typeof ctx.data === "undefined") {
2485
- return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
2596
+ return { message: message ?? required_error ?? ctx.defaultError };
2486
2597
  }
2487
2598
  if (iss.code !== "invalid_type")
2488
2599
  return { message: ctx.defaultError };
2489
- return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
2600
+ return { message: message ?? invalid_type_error ?? ctx.defaultError };
2490
2601
  };
2491
2602
  return { errorMap: customMap, description };
2492
2603
  }
@@ -2538,14 +2649,13 @@ class ZodType {
2538
2649
  throw result.error;
2539
2650
  }
2540
2651
  safeParse(data, params) {
2541
- var _a;
2542
2652
  const ctx = {
2543
2653
  common: {
2544
2654
  issues: [],
2545
- async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,
2546
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
2655
+ async: params?.async ?? false,
2656
+ contextualErrorMap: params?.errorMap,
2547
2657
  },
2548
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
2658
+ path: params?.path || [],
2549
2659
  schemaErrorMap: this._def.errorMap,
2550
2660
  parent: null,
2551
2661
  data,
@@ -2555,7 +2665,6 @@ class ZodType {
2555
2665
  return handleResult$1(ctx, result);
2556
2666
  }
2557
2667
  "~validate"(data) {
2558
- var _a, _b;
2559
2668
  const ctx = {
2560
2669
  common: {
2561
2670
  issues: [],
@@ -2579,7 +2688,7 @@ class ZodType {
2579
2688
  };
2580
2689
  }
2581
2690
  catch (err) {
2582
- if ((_b = (_a = err === null || err === void 0 ? void 0 : err.message) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === null || _b === void 0 ? void 0 : _b.includes("encountered")) {
2691
+ if (err?.message?.toLowerCase()?.includes("encountered")) {
2583
2692
  this["~standard"].async = true;
2584
2693
  }
2585
2694
  ctx.common = {
@@ -2606,19 +2715,17 @@ class ZodType {
2606
2715
  const ctx = {
2607
2716
  common: {
2608
2717
  issues: [],
2609
- contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,
2718
+ contextualErrorMap: params?.errorMap,
2610
2719
  async: true,
2611
2720
  },
2612
- path: (params === null || params === void 0 ? void 0 : params.path) || [],
2721
+ path: params?.path || [],
2613
2722
  schemaErrorMap: this._def.errorMap,
2614
2723
  parent: null,
2615
2724
  data,
2616
2725
  parsedType: getParsedType(data),
2617
2726
  };
2618
2727
  const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
2619
- const result = await (isAsync(maybeAsyncResult)
2620
- ? maybeAsyncResult
2621
- : Promise.resolve(maybeAsyncResult));
2728
+ const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
2622
2729
  return handleResult$1(ctx, result);
2623
2730
  }
2624
2731
  refine(check, message) {
@@ -2662,9 +2769,7 @@ class ZodType {
2662
2769
  refinement(check, refinementData) {
2663
2770
  return this._refinement((val, ctx) => {
2664
2771
  if (!check(val)) {
2665
- ctx.addIssue(typeof refinementData === "function"
2666
- ? refinementData(val, ctx)
2667
- : refinementData);
2772
+ ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
2668
2773
  return false;
2669
2774
  }
2670
2775
  else {
@@ -2836,15 +2941,15 @@ const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z
2836
2941
  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])))`;
2837
2942
  const dateRegex = new RegExp(`^${dateRegexSource}$`);
2838
2943
  function timeRegexSource(args) {
2839
- // let regex = `\\d{2}:\\d{2}:\\d{2}`;
2840
- let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
2944
+ let secondsRegexSource = `[0-5]\\d`;
2841
2945
  if (args.precision) {
2842
- regex = `${regex}\\.\\d{${args.precision}}`;
2946
+ secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
2843
2947
  }
2844
2948
  else if (args.precision == null) {
2845
- regex = `${regex}(\\.\\d+)?`;
2949
+ secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
2846
2950
  }
2847
- return regex;
2951
+ const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero
2952
+ return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
2848
2953
  }
2849
2954
  function timeRegex(args) {
2850
2955
  return new RegExp(`^${timeRegexSource(args)}$`);
@@ -2873,6 +2978,8 @@ function isValidJWT(jwt, alg) {
2873
2978
  return false;
2874
2979
  try {
2875
2980
  const [header] = jwt.split(".");
2981
+ if (!header)
2982
+ return false;
2876
2983
  // Convert base64url to base64
2877
2984
  const base64 = header
2878
2985
  .replace(/-/g, "+")
@@ -2881,13 +2988,15 @@ function isValidJWT(jwt, alg) {
2881
2988
  const decoded = JSON.parse(atob(base64));
2882
2989
  if (typeof decoded !== "object" || decoded === null)
2883
2990
  return false;
2884
- if (!decoded.typ || !decoded.alg)
2991
+ if ("typ" in decoded && decoded?.typ !== "JWT")
2992
+ return false;
2993
+ if (!decoded.alg)
2885
2994
  return false;
2886
2995
  if (alg && decoded.alg !== alg)
2887
2996
  return false;
2888
2997
  return true;
2889
2998
  }
2890
- catch (_a) {
2999
+ catch {
2891
3000
  return false;
2892
3001
  }
2893
3002
  }
@@ -3058,7 +3167,7 @@ class ZodString extends ZodType {
3058
3167
  try {
3059
3168
  new URL(input.data);
3060
3169
  }
3061
- catch (_a) {
3170
+ catch {
3062
3171
  ctx = this._getOrReturnCtx(input, ctx);
3063
3172
  addIssueToContext(ctx, {
3064
3173
  validation: "url",
@@ -3288,7 +3397,6 @@ class ZodString extends ZodType {
3288
3397
  return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
3289
3398
  }
3290
3399
  datetime(options) {
3291
- var _a, _b;
3292
3400
  if (typeof options === "string") {
3293
3401
  return this._addCheck({
3294
3402
  kind: "datetime",
@@ -3300,10 +3408,10 @@ class ZodString extends ZodType {
3300
3408
  }
3301
3409
  return this._addCheck({
3302
3410
  kind: "datetime",
3303
- precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
3304
- offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
3305
- local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
3306
- ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
3411
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
3412
+ offset: options?.offset ?? false,
3413
+ local: options?.local ?? false,
3414
+ ...errorUtil.errToObj(options?.message),
3307
3415
  });
3308
3416
  }
3309
3417
  date(message) {
@@ -3319,8 +3427,8 @@ class ZodString extends ZodType {
3319
3427
  }
3320
3428
  return this._addCheck({
3321
3429
  kind: "time",
3322
- precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
3323
- ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
3430
+ precision: typeof options?.precision === "undefined" ? null : options?.precision,
3431
+ ...errorUtil.errToObj(options?.message),
3324
3432
  });
3325
3433
  }
3326
3434
  duration(message) {
@@ -3337,8 +3445,8 @@ class ZodString extends ZodType {
3337
3445
  return this._addCheck({
3338
3446
  kind: "includes",
3339
3447
  value: value,
3340
- position: options === null || options === void 0 ? void 0 : options.position,
3341
- ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
3448
+ position: options?.position,
3449
+ ...errorUtil.errToObj(options?.message),
3342
3450
  });
3343
3451
  }
3344
3452
  startsWith(value, message) {
@@ -3471,11 +3579,10 @@ class ZodString extends ZodType {
3471
3579
  }
3472
3580
  }
3473
3581
  ZodString.create = (params) => {
3474
- var _a;
3475
3582
  return new ZodString({
3476
3583
  checks: [],
3477
3584
  typeName: ZodFirstPartyTypeKind.ZodString,
3478
- coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
3585
+ coerce: params?.coerce ?? false,
3479
3586
  ...processCreateParams(params),
3480
3587
  });
3481
3588
  };
@@ -3484,9 +3591,9 @@ function floatSafeRemainder(val, step) {
3484
3591
  const valDecCount = (val.toString().split(".")[1] || "").length;
3485
3592
  const stepDecCount = (step.toString().split(".")[1] || "").length;
3486
3593
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
3487
- const valInt = parseInt(val.toFixed(decCount).replace(".", ""));
3488
- const stepInt = parseInt(step.toFixed(decCount).replace(".", ""));
3489
- return (valInt % stepInt) / Math.pow(10, decCount);
3594
+ const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
3595
+ const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
3596
+ return (valInt % stepInt) / 10 ** decCount;
3490
3597
  }
3491
3598
  class ZodNumber extends ZodType {
3492
3599
  constructor() {
@@ -3525,9 +3632,7 @@ class ZodNumber extends ZodType {
3525
3632
  }
3526
3633
  }
3527
3634
  else if (check.kind === "min") {
3528
- const tooSmall = check.inclusive
3529
- ? input.data < check.value
3530
- : input.data <= check.value;
3635
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
3531
3636
  if (tooSmall) {
3532
3637
  ctx = this._getOrReturnCtx(input, ctx);
3533
3638
  addIssueToContext(ctx, {
@@ -3542,9 +3647,7 @@ class ZodNumber extends ZodType {
3542
3647
  }
3543
3648
  }
3544
3649
  else if (check.kind === "max") {
3545
- const tooBig = check.inclusive
3546
- ? input.data > check.value
3547
- : input.data >= check.value;
3650
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
3548
3651
  if (tooBig) {
3549
3652
  ctx = this._getOrReturnCtx(input, ctx);
3550
3653
  addIssueToContext(ctx, {
@@ -3702,15 +3805,13 @@ class ZodNumber extends ZodType {
3702
3805
  return max;
3703
3806
  }
3704
3807
  get isInt() {
3705
- return !!this._def.checks.find((ch) => ch.kind === "int" ||
3706
- (ch.kind === "multipleOf" && util.isInteger(ch.value)));
3808
+ return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value)));
3707
3809
  }
3708
3810
  get isFinite() {
3709
- let max = null, min = null;
3811
+ let max = null;
3812
+ let min = null;
3710
3813
  for (const ch of this._def.checks) {
3711
- if (ch.kind === "finite" ||
3712
- ch.kind === "int" ||
3713
- ch.kind === "multipleOf") {
3814
+ if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
3714
3815
  return true;
3715
3816
  }
3716
3817
  else if (ch.kind === "min") {
@@ -3729,7 +3830,7 @@ ZodNumber.create = (params) => {
3729
3830
  return new ZodNumber({
3730
3831
  checks: [],
3731
3832
  typeName: ZodFirstPartyTypeKind.ZodNumber,
3732
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
3833
+ coerce: params?.coerce || false,
3733
3834
  ...processCreateParams(params),
3734
3835
  });
3735
3836
  };
@@ -3744,7 +3845,7 @@ class ZodBigInt extends ZodType {
3744
3845
  try {
3745
3846
  input.data = BigInt(input.data);
3746
3847
  }
3747
- catch (_a) {
3848
+ catch {
3748
3849
  return this._getInvalidInput(input);
3749
3850
  }
3750
3851
  }
@@ -3756,9 +3857,7 @@ class ZodBigInt extends ZodType {
3756
3857
  const status = new ParseStatus();
3757
3858
  for (const check of this._def.checks) {
3758
3859
  if (check.kind === "min") {
3759
- const tooSmall = check.inclusive
3760
- ? input.data < check.value
3761
- : input.data <= check.value;
3860
+ const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
3762
3861
  if (tooSmall) {
3763
3862
  ctx = this._getOrReturnCtx(input, ctx);
3764
3863
  addIssueToContext(ctx, {
@@ -3772,9 +3871,7 @@ class ZodBigInt extends ZodType {
3772
3871
  }
3773
3872
  }
3774
3873
  else if (check.kind === "max") {
3775
- const tooBig = check.inclusive
3776
- ? input.data > check.value
3777
- : input.data >= check.value;
3874
+ const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
3778
3875
  if (tooBig) {
3779
3876
  ctx = this._getOrReturnCtx(input, ctx);
3780
3877
  addIssueToContext(ctx, {
@@ -3906,11 +4003,10 @@ class ZodBigInt extends ZodType {
3906
4003
  }
3907
4004
  }
3908
4005
  ZodBigInt.create = (params) => {
3909
- var _a;
3910
4006
  return new ZodBigInt({
3911
4007
  checks: [],
3912
4008
  typeName: ZodFirstPartyTypeKind.ZodBigInt,
3913
- coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,
4009
+ coerce: params?.coerce ?? false,
3914
4010
  ...processCreateParams(params),
3915
4011
  });
3916
4012
  };
@@ -3935,7 +4031,7 @@ class ZodBoolean extends ZodType {
3935
4031
  ZodBoolean.create = (params) => {
3936
4032
  return new ZodBoolean({
3937
4033
  typeName: ZodFirstPartyTypeKind.ZodBoolean,
3938
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
4034
+ coerce: params?.coerce || false,
3939
4035
  ...processCreateParams(params),
3940
4036
  });
3941
4037
  };
@@ -3954,7 +4050,7 @@ class ZodDate extends ZodType {
3954
4050
  });
3955
4051
  return INVALID;
3956
4052
  }
3957
- if (isNaN(input.data.getTime())) {
4053
+ if (Number.isNaN(input.data.getTime())) {
3958
4054
  const ctx = this._getOrReturnCtx(input);
3959
4055
  addIssueToContext(ctx, {
3960
4056
  code: ZodIssueCode.invalid_date,
@@ -4045,7 +4141,7 @@ class ZodDate extends ZodType {
4045
4141
  ZodDate.create = (params) => {
4046
4142
  return new ZodDate({
4047
4143
  checks: [],
4048
- coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,
4144
+ coerce: params?.coerce || false,
4049
4145
  typeName: ZodFirstPartyTypeKind.ZodDate,
4050
4146
  ...processCreateParams(params),
4051
4147
  });
@@ -4367,7 +4463,8 @@ class ZodObject extends ZodType {
4367
4463
  return this._cached;
4368
4464
  const shape = this._def.shape();
4369
4465
  const keys = util.objectKeys(shape);
4370
- return (this._cached = { shape, keys });
4466
+ this._cached = { shape, keys };
4467
+ return this._cached;
4371
4468
  }
4372
4469
  _parse(input) {
4373
4470
  const parsedType = this._getType(input);
@@ -4383,8 +4480,7 @@ class ZodObject extends ZodType {
4383
4480
  const { status, ctx } = this._processInputParams(input);
4384
4481
  const { shape, keys: shapeKeys } = this._getCached();
4385
4482
  const extraKeys = [];
4386
- if (!(this._def.catchall instanceof ZodNever &&
4387
- this._def.unknownKeys === "strip")) {
4483
+ if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
4388
4484
  for (const key in ctx.data) {
4389
4485
  if (!shapeKeys.includes(key)) {
4390
4486
  extraKeys.push(key);
@@ -4472,11 +4568,10 @@ class ZodObject extends ZodType {
4472
4568
  ...(message !== undefined
4473
4569
  ? {
4474
4570
  errorMap: (issue, ctx) => {
4475
- var _a, _b, _c, _d;
4476
- 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;
4571
+ const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
4477
4572
  if (issue.code === "unrecognized_keys")
4478
4573
  return {
4479
- message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,
4574
+ message: errorUtil.errToObj(message).message ?? defaultError,
4480
4575
  };
4481
4576
  return {
4482
4577
  message: defaultError,
@@ -4608,11 +4703,11 @@ class ZodObject extends ZodType {
4608
4703
  }
4609
4704
  pick(mask) {
4610
4705
  const shape = {};
4611
- util.objectKeys(mask).forEach((key) => {
4706
+ for (const key of util.objectKeys(mask)) {
4612
4707
  if (mask[key] && this.shape[key]) {
4613
4708
  shape[key] = this.shape[key];
4614
4709
  }
4615
- });
4710
+ }
4616
4711
  return new ZodObject({
4617
4712
  ...this._def,
4618
4713
  shape: () => shape,
@@ -4620,11 +4715,11 @@ class ZodObject extends ZodType {
4620
4715
  }
4621
4716
  omit(mask) {
4622
4717
  const shape = {};
4623
- util.objectKeys(this.shape).forEach((key) => {
4718
+ for (const key of util.objectKeys(this.shape)) {
4624
4719
  if (!mask[key]) {
4625
4720
  shape[key] = this.shape[key];
4626
4721
  }
4627
- });
4722
+ }
4628
4723
  return new ZodObject({
4629
4724
  ...this._def,
4630
4725
  shape: () => shape,
@@ -4638,7 +4733,7 @@ class ZodObject extends ZodType {
4638
4733
  }
4639
4734
  partial(mask) {
4640
4735
  const newShape = {};
4641
- util.objectKeys(this.shape).forEach((key) => {
4736
+ for (const key of util.objectKeys(this.shape)) {
4642
4737
  const fieldSchema = this.shape[key];
4643
4738
  if (mask && !mask[key]) {
4644
4739
  newShape[key] = fieldSchema;
@@ -4646,7 +4741,7 @@ class ZodObject extends ZodType {
4646
4741
  else {
4647
4742
  newShape[key] = fieldSchema.optional();
4648
4743
  }
4649
- });
4744
+ }
4650
4745
  return new ZodObject({
4651
4746
  ...this._def,
4652
4747
  shape: () => newShape,
@@ -4654,7 +4749,7 @@ class ZodObject extends ZodType {
4654
4749
  }
4655
4750
  required(mask) {
4656
4751
  const newShape = {};
4657
- util.objectKeys(this.shape).forEach((key) => {
4752
+ for (const key of util.objectKeys(this.shape)) {
4658
4753
  if (mask && !mask[key]) {
4659
4754
  newShape[key] = this.shape[key];
4660
4755
  }
@@ -4666,7 +4761,7 @@ class ZodObject extends ZodType {
4666
4761
  }
4667
4762
  newShape[key] = newField;
4668
4763
  }
4669
- });
4764
+ }
4670
4765
  return new ZodObject({
4671
4766
  ...this._def,
4672
4767
  shape: () => newShape,
@@ -4799,137 +4894,6 @@ ZodUnion.create = (types, params) => {
4799
4894
  ...processCreateParams(params),
4800
4895
  });
4801
4896
  };
4802
- /////////////////////////////////////////////////////
4803
- /////////////////////////////////////////////////////
4804
- ////////// //////////
4805
- ////////// ZodDiscriminatedUnion //////////
4806
- ////////// //////////
4807
- /////////////////////////////////////////////////////
4808
- /////////////////////////////////////////////////////
4809
- const getDiscriminator = (type) => {
4810
- if (type instanceof ZodLazy) {
4811
- return getDiscriminator(type.schema);
4812
- }
4813
- else if (type instanceof ZodEffects) {
4814
- return getDiscriminator(type.innerType());
4815
- }
4816
- else if (type instanceof ZodLiteral) {
4817
- return [type.value];
4818
- }
4819
- else if (type instanceof ZodEnum) {
4820
- return type.options;
4821
- }
4822
- else if (type instanceof ZodNativeEnum) {
4823
- // eslint-disable-next-line ban/ban
4824
- return util.objectValues(type.enum);
4825
- }
4826
- else if (type instanceof ZodDefault) {
4827
- return getDiscriminator(type._def.innerType);
4828
- }
4829
- else if (type instanceof ZodUndefined) {
4830
- return [undefined];
4831
- }
4832
- else if (type instanceof ZodNull) {
4833
- return [null];
4834
- }
4835
- else if (type instanceof ZodOptional) {
4836
- return [undefined, ...getDiscriminator(type.unwrap())];
4837
- }
4838
- else if (type instanceof ZodNullable) {
4839
- return [null, ...getDiscriminator(type.unwrap())];
4840
- }
4841
- else if (type instanceof ZodBranded) {
4842
- return getDiscriminator(type.unwrap());
4843
- }
4844
- else if (type instanceof ZodReadonly) {
4845
- return getDiscriminator(type.unwrap());
4846
- }
4847
- else if (type instanceof ZodCatch) {
4848
- return getDiscriminator(type._def.innerType);
4849
- }
4850
- else {
4851
- return [];
4852
- }
4853
- };
4854
- class ZodDiscriminatedUnion extends ZodType {
4855
- _parse(input) {
4856
- const { ctx } = this._processInputParams(input);
4857
- if (ctx.parsedType !== ZodParsedType.object) {
4858
- addIssueToContext(ctx, {
4859
- code: ZodIssueCode.invalid_type,
4860
- expected: ZodParsedType.object,
4861
- received: ctx.parsedType,
4862
- });
4863
- return INVALID;
4864
- }
4865
- const discriminator = this.discriminator;
4866
- const discriminatorValue = ctx.data[discriminator];
4867
- const option = this.optionsMap.get(discriminatorValue);
4868
- if (!option) {
4869
- addIssueToContext(ctx, {
4870
- code: ZodIssueCode.invalid_union_discriminator,
4871
- options: Array.from(this.optionsMap.keys()),
4872
- path: [discriminator],
4873
- });
4874
- return INVALID;
4875
- }
4876
- if (ctx.common.async) {
4877
- return option._parseAsync({
4878
- data: ctx.data,
4879
- path: ctx.path,
4880
- parent: ctx,
4881
- });
4882
- }
4883
- else {
4884
- return option._parseSync({
4885
- data: ctx.data,
4886
- path: ctx.path,
4887
- parent: ctx,
4888
- });
4889
- }
4890
- }
4891
- get discriminator() {
4892
- return this._def.discriminator;
4893
- }
4894
- get options() {
4895
- return this._def.options;
4896
- }
4897
- get optionsMap() {
4898
- return this._def.optionsMap;
4899
- }
4900
- /**
4901
- * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
4902
- * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
4903
- * have a different value for each object in the union.
4904
- * @param discriminator the name of the discriminator property
4905
- * @param types an array of object schemas
4906
- * @param params
4907
- */
4908
- static create(discriminator, options, params) {
4909
- // Get all the valid discriminator values
4910
- const optionsMap = new Map();
4911
- // try {
4912
- for (const type of options) {
4913
- const discriminatorValues = getDiscriminator(type.shape[discriminator]);
4914
- if (!discriminatorValues.length) {
4915
- throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
4916
- }
4917
- for (const value of discriminatorValues) {
4918
- if (optionsMap.has(value)) {
4919
- throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
4920
- }
4921
- optionsMap.set(value, type);
4922
- }
4923
- }
4924
- return new ZodDiscriminatedUnion({
4925
- typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
4926
- discriminator,
4927
- options,
4928
- optionsMap,
4929
- ...processCreateParams(params),
4930
- });
4931
- }
4932
- }
4933
4897
  function mergeValues(a, b) {
4934
4898
  const aType = getParsedType(a);
4935
4899
  const bType = getParsedType(b);
@@ -4938,9 +4902,7 @@ function mergeValues(a, b) {
4938
4902
  }
4939
4903
  else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
4940
4904
  const bKeys = util.objectKeys(b);
4941
- const sharedKeys = util
4942
- .objectKeys(a)
4943
- .filter((key) => bKeys.indexOf(key) !== -1);
4905
+ const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);
4944
4906
  const newObj = { ...a, ...b };
4945
4907
  for (const key of sharedKeys) {
4946
4908
  const sharedValue = mergeValues(a[key], b[key]);
@@ -4967,9 +4929,7 @@ function mergeValues(a, b) {
4967
4929
  }
4968
4930
  return { valid: true, data: newArray };
4969
4931
  }
4970
- else if (aType === ZodParsedType.date &&
4971
- bType === ZodParsedType.date &&
4972
- +a === +b) {
4932
+ else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {
4973
4933
  return { valid: true, data: a };
4974
4934
  }
4975
4935
  else {
@@ -5030,6 +4990,7 @@ ZodIntersection.create = (left, right, params) => {
5030
4990
  ...processCreateParams(params),
5031
4991
  });
5032
4992
  };
4993
+ // type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];
5033
4994
  class ZodTuple extends ZodType {
5034
4995
  _parse(input) {
5035
4996
  const { status, ctx } = this._processInputParams(input);
@@ -5100,60 +5061,6 @@ ZodTuple.create = (schemas, params) => {
5100
5061
  ...processCreateParams(params),
5101
5062
  });
5102
5063
  };
5103
- class ZodRecord extends ZodType {
5104
- get keySchema() {
5105
- return this._def.keyType;
5106
- }
5107
- get valueSchema() {
5108
- return this._def.valueType;
5109
- }
5110
- _parse(input) {
5111
- const { status, ctx } = this._processInputParams(input);
5112
- if (ctx.parsedType !== ZodParsedType.object) {
5113
- addIssueToContext(ctx, {
5114
- code: ZodIssueCode.invalid_type,
5115
- expected: ZodParsedType.object,
5116
- received: ctx.parsedType,
5117
- });
5118
- return INVALID;
5119
- }
5120
- const pairs = [];
5121
- const keyType = this._def.keyType;
5122
- const valueType = this._def.valueType;
5123
- for (const key in ctx.data) {
5124
- pairs.push({
5125
- key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
5126
- value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
5127
- alwaysSet: key in ctx.data,
5128
- });
5129
- }
5130
- if (ctx.common.async) {
5131
- return ParseStatus.mergeObjectAsync(status, pairs);
5132
- }
5133
- else {
5134
- return ParseStatus.mergeObjectSync(status, pairs);
5135
- }
5136
- }
5137
- get element() {
5138
- return this._def.valueType;
5139
- }
5140
- static create(first, second, third) {
5141
- if (second instanceof ZodType) {
5142
- return new ZodRecord({
5143
- keyType: first,
5144
- valueType: second,
5145
- typeName: ZodFirstPartyTypeKind.ZodRecord,
5146
- ...processCreateParams(third),
5147
- });
5148
- }
5149
- return new ZodRecord({
5150
- keyType: ZodString.create(),
5151
- valueType: first,
5152
- typeName: ZodFirstPartyTypeKind.ZodRecord,
5153
- ...processCreateParams(second),
5154
- });
5155
- }
5156
- }
5157
5064
  class ZodMap extends ZodType {
5158
5065
  get keySchema() {
5159
5066
  return this._def.keyType;
@@ -5307,159 +5214,31 @@ ZodSet.create = (valueType, params) => {
5307
5214
  ...processCreateParams(params),
5308
5215
  });
5309
5216
  };
5310
- class ZodFunction extends ZodType {
5311
- constructor() {
5312
- super(...arguments);
5313
- this.validate = this.implement;
5217
+ class ZodLazy extends ZodType {
5218
+ get schema() {
5219
+ return this._def.getter();
5314
5220
  }
5315
5221
  _parse(input) {
5316
5222
  const { ctx } = this._processInputParams(input);
5317
- if (ctx.parsedType !== ZodParsedType.function) {
5223
+ const lazySchema = this._def.getter();
5224
+ return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
5225
+ }
5226
+ }
5227
+ ZodLazy.create = (getter, params) => {
5228
+ return new ZodLazy({
5229
+ getter: getter,
5230
+ typeName: ZodFirstPartyTypeKind.ZodLazy,
5231
+ ...processCreateParams(params),
5232
+ });
5233
+ };
5234
+ class ZodLiteral extends ZodType {
5235
+ _parse(input) {
5236
+ if (input.data !== this._def.value) {
5237
+ const ctx = this._getOrReturnCtx(input);
5318
5238
  addIssueToContext(ctx, {
5319
- code: ZodIssueCode.invalid_type,
5320
- expected: ZodParsedType.function,
5321
- received: ctx.parsedType,
5322
- });
5323
- return INVALID;
5324
- }
5325
- function makeArgsIssue(args, error) {
5326
- return makeIssue({
5327
- data: args,
5328
- path: ctx.path,
5329
- errorMaps: [
5330
- ctx.common.contextualErrorMap,
5331
- ctx.schemaErrorMap,
5332
- getErrorMap(),
5333
- errorMap,
5334
- ].filter((x) => !!x),
5335
- issueData: {
5336
- code: ZodIssueCode.invalid_arguments,
5337
- argumentsError: error,
5338
- },
5339
- });
5340
- }
5341
- function makeReturnsIssue(returns, error) {
5342
- return makeIssue({
5343
- data: returns,
5344
- path: ctx.path,
5345
- errorMaps: [
5346
- ctx.common.contextualErrorMap,
5347
- ctx.schemaErrorMap,
5348
- getErrorMap(),
5349
- errorMap,
5350
- ].filter((x) => !!x),
5351
- issueData: {
5352
- code: ZodIssueCode.invalid_return_type,
5353
- returnTypeError: error,
5354
- },
5355
- });
5356
- }
5357
- const params = { errorMap: ctx.common.contextualErrorMap };
5358
- const fn = ctx.data;
5359
- if (this._def.returns instanceof ZodPromise) {
5360
- // Would love a way to avoid disabling this rule, but we need
5361
- // an alias (using an arrow function was what caused 2651).
5362
- // eslint-disable-next-line @typescript-eslint/no-this-alias
5363
- const me = this;
5364
- return OK(async function (...args) {
5365
- const error = new ZodError([]);
5366
- const parsedArgs = await me._def.args
5367
- .parseAsync(args, params)
5368
- .catch((e) => {
5369
- error.addIssue(makeArgsIssue(args, e));
5370
- throw error;
5371
- });
5372
- const result = await Reflect.apply(fn, this, parsedArgs);
5373
- const parsedReturns = await me._def.returns._def.type
5374
- .parseAsync(result, params)
5375
- .catch((e) => {
5376
- error.addIssue(makeReturnsIssue(result, e));
5377
- throw error;
5378
- });
5379
- return parsedReturns;
5380
- });
5381
- }
5382
- else {
5383
- // Would love a way to avoid disabling this rule, but we need
5384
- // an alias (using an arrow function was what caused 2651).
5385
- // eslint-disable-next-line @typescript-eslint/no-this-alias
5386
- const me = this;
5387
- return OK(function (...args) {
5388
- const parsedArgs = me._def.args.safeParse(args, params);
5389
- if (!parsedArgs.success) {
5390
- throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
5391
- }
5392
- const result = Reflect.apply(fn, this, parsedArgs.data);
5393
- const parsedReturns = me._def.returns.safeParse(result, params);
5394
- if (!parsedReturns.success) {
5395
- throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
5396
- }
5397
- return parsedReturns.data;
5398
- });
5399
- }
5400
- }
5401
- parameters() {
5402
- return this._def.args;
5403
- }
5404
- returnType() {
5405
- return this._def.returns;
5406
- }
5407
- args(...items) {
5408
- return new ZodFunction({
5409
- ...this._def,
5410
- args: ZodTuple.create(items).rest(ZodUnknown.create()),
5411
- });
5412
- }
5413
- returns(returnType) {
5414
- return new ZodFunction({
5415
- ...this._def,
5416
- returns: returnType,
5417
- });
5418
- }
5419
- implement(func) {
5420
- const validatedFunc = this.parse(func);
5421
- return validatedFunc;
5422
- }
5423
- strictImplement(func) {
5424
- const validatedFunc = this.parse(func);
5425
- return validatedFunc;
5426
- }
5427
- static create(args, returns, params) {
5428
- return new ZodFunction({
5429
- args: (args
5430
- ? args
5431
- : ZodTuple.create([]).rest(ZodUnknown.create())),
5432
- returns: returns || ZodUnknown.create(),
5433
- typeName: ZodFirstPartyTypeKind.ZodFunction,
5434
- ...processCreateParams(params),
5435
- });
5436
- }
5437
- }
5438
- class ZodLazy extends ZodType {
5439
- get schema() {
5440
- return this._def.getter();
5441
- }
5442
- _parse(input) {
5443
- const { ctx } = this._processInputParams(input);
5444
- const lazySchema = this._def.getter();
5445
- return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
5446
- }
5447
- }
5448
- ZodLazy.create = (getter, params) => {
5449
- return new ZodLazy({
5450
- getter: getter,
5451
- typeName: ZodFirstPartyTypeKind.ZodLazy,
5452
- ...processCreateParams(params),
5453
- });
5454
- };
5455
- class ZodLiteral extends ZodType {
5456
- _parse(input) {
5457
- if (input.data !== this._def.value) {
5458
- const ctx = this._getOrReturnCtx(input);
5459
- addIssueToContext(ctx, {
5460
- received: ctx.data,
5461
- code: ZodIssueCode.invalid_literal,
5462
- expected: this._def.value,
5239
+ received: ctx.data,
5240
+ code: ZodIssueCode.invalid_literal,
5241
+ expected: this._def.value,
5463
5242
  });
5464
5243
  return INVALID;
5465
5244
  }
@@ -5484,10 +5263,6 @@ function createZodEnum(values, params) {
5484
5263
  });
5485
5264
  }
5486
5265
  class ZodEnum extends ZodType {
5487
- constructor() {
5488
- super(...arguments);
5489
- _ZodEnum_cache.set(this, void 0);
5490
- }
5491
5266
  _parse(input) {
5492
5267
  if (typeof input.data !== "string") {
5493
5268
  const ctx = this._getOrReturnCtx(input);
@@ -5499,10 +5274,10 @@ class ZodEnum extends ZodType {
5499
5274
  });
5500
5275
  return INVALID;
5501
5276
  }
5502
- if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
5503
- __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
5277
+ if (!this._cache) {
5278
+ this._cache = new Set(this._def.values);
5504
5279
  }
5505
- if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
5280
+ if (!this._cache.has(input.data)) {
5506
5281
  const ctx = this._getOrReturnCtx(input);
5507
5282
  const expectedValues = this._def.values;
5508
5283
  addIssueToContext(ctx, {
@@ -5551,18 +5326,12 @@ class ZodEnum extends ZodType {
5551
5326
  });
5552
5327
  }
5553
5328
  }
5554
- _ZodEnum_cache = new WeakMap();
5555
5329
  ZodEnum.create = createZodEnum;
5556
5330
  class ZodNativeEnum extends ZodType {
5557
- constructor() {
5558
- super(...arguments);
5559
- _ZodNativeEnum_cache.set(this, void 0);
5560
- }
5561
5331
  _parse(input) {
5562
5332
  const nativeEnumValues = util.getValidEnumValues(this._def.values);
5563
5333
  const ctx = this._getOrReturnCtx(input);
5564
- if (ctx.parsedType !== ZodParsedType.string &&
5565
- ctx.parsedType !== ZodParsedType.number) {
5334
+ if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
5566
5335
  const expectedValues = util.objectValues(nativeEnumValues);
5567
5336
  addIssueToContext(ctx, {
5568
5337
  expected: util.joinValues(expectedValues),
@@ -5571,10 +5340,10 @@ class ZodNativeEnum extends ZodType {
5571
5340
  });
5572
5341
  return INVALID;
5573
5342
  }
5574
- if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
5575
- __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util.getValidEnumValues(this._def.values)), "f");
5343
+ if (!this._cache) {
5344
+ this._cache = new Set(util.getValidEnumValues(this._def.values));
5576
5345
  }
5577
- if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
5346
+ if (!this._cache.has(input.data)) {
5578
5347
  const expectedValues = util.objectValues(nativeEnumValues);
5579
5348
  addIssueToContext(ctx, {
5580
5349
  received: ctx.data,
@@ -5589,7 +5358,6 @@ class ZodNativeEnum extends ZodType {
5589
5358
  return this._def.values;
5590
5359
  }
5591
5360
  }
5592
- _ZodNativeEnum_cache = new WeakMap();
5593
5361
  ZodNativeEnum.create = (values, params) => {
5594
5362
  return new ZodNativeEnum({
5595
5363
  values: values,
@@ -5603,8 +5371,7 @@ class ZodPromise extends ZodType {
5603
5371
  }
5604
5372
  _parse(input) {
5605
5373
  const { ctx } = this._processInputParams(input);
5606
- if (ctx.parsedType !== ZodParsedType.promise &&
5607
- ctx.common.async === false) {
5374
+ if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
5608
5375
  addIssueToContext(ctx, {
5609
5376
  code: ZodIssueCode.invalid_type,
5610
5377
  expected: ZodParsedType.promise,
@@ -5612,9 +5379,7 @@ class ZodPromise extends ZodType {
5612
5379
  });
5613
5380
  return INVALID;
5614
5381
  }
5615
- const promisified = ctx.parsedType === ZodParsedType.promise
5616
- ? ctx.data
5617
- : Promise.resolve(ctx.data);
5382
+ const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
5618
5383
  return OK(promisified.then((data) => {
5619
5384
  return this._def.type.parseAsync(data, {
5620
5385
  path: ctx.path,
@@ -5720,9 +5485,7 @@ class ZodEffects extends ZodType {
5720
5485
  return { status: status.value, value: inner.value };
5721
5486
  }
5722
5487
  else {
5723
- return this._def.schema
5724
- ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
5725
- .then((inner) => {
5488
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
5726
5489
  if (inner.status === "aborted")
5727
5490
  return INVALID;
5728
5491
  if (inner.status === "dirty")
@@ -5741,7 +5504,7 @@ class ZodEffects extends ZodType {
5741
5504
  parent: ctx,
5742
5505
  });
5743
5506
  if (!isValid(base))
5744
- return base;
5507
+ return INVALID;
5745
5508
  const result = effect.transform(base.value, checkCtx);
5746
5509
  if (result instanceof Promise) {
5747
5510
  throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
@@ -5749,12 +5512,13 @@ class ZodEffects extends ZodType {
5749
5512
  return { status: status.value, value: result };
5750
5513
  }
5751
5514
  else {
5752
- return this._def.schema
5753
- ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })
5754
- .then((base) => {
5515
+ return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
5755
5516
  if (!isValid(base))
5756
- return base;
5757
- return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));
5517
+ return INVALID;
5518
+ return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
5519
+ status: status.value,
5520
+ value: result,
5521
+ }));
5758
5522
  });
5759
5523
  }
5760
5524
  }
@@ -5836,9 +5600,7 @@ ZodDefault.create = (type, params) => {
5836
5600
  return new ZodDefault({
5837
5601
  innerType: type,
5838
5602
  typeName: ZodFirstPartyTypeKind.ZodDefault,
5839
- defaultValue: typeof params.default === "function"
5840
- ? params.default
5841
- : () => params.default,
5603
+ defaultValue: typeof params.default === "function" ? params.default : () => params.default,
5842
5604
  ...processCreateParams(params),
5843
5605
  });
5844
5606
  };
@@ -5922,7 +5684,6 @@ ZodNaN.create = (params) => {
5922
5684
  ...processCreateParams(params),
5923
5685
  });
5924
5686
  };
5925
- const BRAND = Symbol("zod_brand");
5926
5687
  class ZodBranded extends ZodType {
5927
5688
  _parse(input) {
5928
5689
  const { ctx } = this._processInputParams(input);
@@ -6004,9 +5765,7 @@ class ZodReadonly extends ZodType {
6004
5765
  }
6005
5766
  return data;
6006
5767
  };
6007
- return isAsync(result)
6008
- ? result.then((data) => freeze(data))
6009
- : freeze(result);
5768
+ return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
6010
5769
  }
6011
5770
  unwrap() {
6012
5771
  return this._def.innerType;
@@ -6019,60 +5778,9 @@ ZodReadonly.create = (type, params) => {
6019
5778
  ...processCreateParams(params),
6020
5779
  });
6021
5780
  };
6022
- ////////////////////////////////////////
6023
- ////////////////////////////////////////
6024
- ////////// //////////
6025
- ////////// z.custom //////////
6026
- ////////// //////////
6027
- ////////////////////////////////////////
6028
- ////////////////////////////////////////
6029
- function cleanParams(params, data) {
6030
- const p = typeof params === "function"
6031
- ? params(data)
6032
- : typeof params === "string"
6033
- ? { message: params }
6034
- : params;
6035
- const p2 = typeof p === "string" ? { message: p } : p;
6036
- return p2;
6037
- }
6038
- function custom(check, _params = {},
6039
- /**
6040
- * @deprecated
6041
- *
6042
- * Pass `fatal` into the params object instead:
6043
- *
6044
- * ```ts
6045
- * z.string().custom((val) => val.length > 5, { fatal: false })
6046
- * ```
6047
- *
6048
- */
6049
- fatal) {
6050
- if (check)
6051
- return ZodAny.create().superRefine((data, ctx) => {
6052
- var _a, _b;
6053
- const r = check(data);
6054
- if (r instanceof Promise) {
6055
- return r.then((r) => {
6056
- var _a, _b;
6057
- if (!r) {
6058
- const params = cleanParams(_params, data);
6059
- const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
6060
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
6061
- }
6062
- });
6063
- }
6064
- if (!r) {
6065
- const params = cleanParams(_params, data);
6066
- const _fatal = (_b = (_a = params.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;
6067
- ctx.addIssue({ code: "custom", ...params, fatal: _fatal });
6068
- }
6069
- return;
6070
- });
6071
- return ZodAny.create();
6072
- }
6073
- const late = {
5781
+ ({
6074
5782
  object: ZodObject.lazycreate,
6075
- };
5783
+ });
6076
5784
  var ZodFirstPartyTypeKind;
6077
5785
  (function (ZodFirstPartyTypeKind) {
6078
5786
  ZodFirstPartyTypeKind["ZodString"] = "ZodString";
@@ -6112,174 +5820,23 @@ var ZodFirstPartyTypeKind;
6112
5820
  ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
6113
5821
  ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
6114
5822
  })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
6115
- const instanceOfType = (
6116
- // const instanceOfType = <T extends new (...args: any[]) => any>(
6117
- cls, params = {
6118
- message: `Input not instance of ${cls.name}`,
6119
- }) => custom((data) => data instanceof cls, params);
6120
5823
  const stringType = ZodString.create;
6121
- const numberType = ZodNumber.create;
6122
- const nanType = ZodNaN.create;
6123
- const bigIntType = ZodBigInt.create;
6124
- const booleanType = ZodBoolean.create;
6125
- const dateType = ZodDate.create;
6126
- const symbolType = ZodSymbol.create;
6127
- const undefinedType = ZodUndefined.create;
6128
- const nullType = ZodNull.create;
6129
- const anyType = ZodAny.create;
6130
- const unknownType = ZodUnknown.create;
6131
- const neverType = ZodNever.create;
6132
- const voidType = ZodVoid.create;
5824
+ ZodNever.create;
6133
5825
  const arrayType = ZodArray.create;
6134
5826
  const objectType = ZodObject.create;
6135
- const strictObjectType = ZodObject.strictCreate;
5827
+ ZodObject.strictCreate;
6136
5828
  const unionType = ZodUnion.create;
6137
- const discriminatedUnionType = ZodDiscriminatedUnion.create;
6138
- const intersectionType = ZodIntersection.create;
6139
- const tupleType = ZodTuple.create;
6140
- const recordType = ZodRecord.create;
6141
- const mapType = ZodMap.create;
6142
- const setType = ZodSet.create;
6143
- const functionType = ZodFunction.create;
6144
- const lazyType = ZodLazy.create;
5829
+ ZodIntersection.create;
5830
+ ZodTuple.create;
6145
5831
  const literalType = ZodLiteral.create;
6146
- const enumType = ZodEnum.create;
6147
- const nativeEnumType = ZodNativeEnum.create;
6148
- const promiseType = ZodPromise.create;
6149
- const effectsType = ZodEffects.create;
6150
- const optionalType = ZodOptional.create;
6151
- const nullableType = ZodNullable.create;
6152
- const preprocessType = ZodEffects.createWithPreprocess;
6153
- const pipelineType = ZodPipeline.create;
6154
- const ostring = () => stringType().optional();
6155
- const onumber = () => numberType().optional();
6156
- const oboolean = () => booleanType().optional();
6157
- const coerce = {
6158
- string: ((arg) => ZodString.create({ ...arg, coerce: true })),
6159
- number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),
6160
- boolean: ((arg) => ZodBoolean.create({
6161
- ...arg,
6162
- coerce: true,
6163
- })),
6164
- bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),
6165
- date: ((arg) => ZodDate.create({ ...arg, coerce: true })),
6166
- };
6167
- const NEVER = INVALID;
6168
-
6169
- var z = /*#__PURE__*/Object.freeze({
6170
- __proto__: null,
6171
- defaultErrorMap: errorMap,
6172
- setErrorMap: setErrorMap,
6173
- getErrorMap: getErrorMap,
6174
- makeIssue: makeIssue,
6175
- EMPTY_PATH: EMPTY_PATH,
6176
- addIssueToContext: addIssueToContext,
6177
- ParseStatus: ParseStatus,
6178
- INVALID: INVALID,
6179
- DIRTY: DIRTY,
6180
- OK: OK,
6181
- isAborted: isAborted,
6182
- isDirty: isDirty,
6183
- isValid: isValid,
6184
- isAsync: isAsync,
6185
- get util () { return util; },
6186
- get objectUtil () { return objectUtil; },
6187
- ZodParsedType: ZodParsedType,
6188
- getParsedType: getParsedType,
6189
- ZodType: ZodType,
6190
- datetimeRegex: datetimeRegex,
6191
- ZodString: ZodString,
6192
- ZodNumber: ZodNumber,
6193
- ZodBigInt: ZodBigInt,
6194
- ZodBoolean: ZodBoolean,
6195
- ZodDate: ZodDate,
6196
- ZodSymbol: ZodSymbol,
6197
- ZodUndefined: ZodUndefined,
6198
- ZodNull: ZodNull,
6199
- ZodAny: ZodAny,
6200
- ZodUnknown: ZodUnknown,
6201
- ZodNever: ZodNever,
6202
- ZodVoid: ZodVoid,
6203
- ZodArray: ZodArray,
6204
- ZodObject: ZodObject,
6205
- ZodUnion: ZodUnion,
6206
- ZodDiscriminatedUnion: ZodDiscriminatedUnion,
6207
- ZodIntersection: ZodIntersection,
6208
- ZodTuple: ZodTuple,
6209
- ZodRecord: ZodRecord,
6210
- ZodMap: ZodMap,
6211
- ZodSet: ZodSet,
6212
- ZodFunction: ZodFunction,
6213
- ZodLazy: ZodLazy,
6214
- ZodLiteral: ZodLiteral,
6215
- ZodEnum: ZodEnum,
6216
- ZodNativeEnum: ZodNativeEnum,
6217
- ZodPromise: ZodPromise,
6218
- ZodEffects: ZodEffects,
6219
- ZodTransformer: ZodEffects,
6220
- ZodOptional: ZodOptional,
6221
- ZodNullable: ZodNullable,
6222
- ZodDefault: ZodDefault,
6223
- ZodCatch: ZodCatch,
6224
- ZodNaN: ZodNaN,
6225
- BRAND: BRAND,
6226
- ZodBranded: ZodBranded,
6227
- ZodPipeline: ZodPipeline,
6228
- ZodReadonly: ZodReadonly,
6229
- custom: custom,
6230
- Schema: ZodType,
6231
- ZodSchema: ZodType,
6232
- late: late,
6233
- get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },
6234
- coerce: coerce,
6235
- any: anyType,
6236
- array: arrayType,
6237
- bigint: bigIntType,
6238
- boolean: booleanType,
6239
- date: dateType,
6240
- discriminatedUnion: discriminatedUnionType,
6241
- effect: effectsType,
6242
- 'enum': enumType,
6243
- 'function': functionType,
6244
- 'instanceof': instanceOfType,
6245
- intersection: intersectionType,
6246
- lazy: lazyType,
6247
- literal: literalType,
6248
- map: mapType,
6249
- nan: nanType,
6250
- nativeEnum: nativeEnumType,
6251
- never: neverType,
6252
- 'null': nullType,
6253
- nullable: nullableType,
6254
- number: numberType,
6255
- object: objectType,
6256
- oboolean: oboolean,
6257
- onumber: onumber,
6258
- optional: optionalType,
6259
- ostring: ostring,
6260
- pipeline: pipelineType,
6261
- preprocess: preprocessType,
6262
- promise: promiseType,
6263
- record: recordType,
6264
- set: setType,
6265
- strictObject: strictObjectType,
6266
- string: stringType,
6267
- symbol: symbolType,
6268
- transformer: effectsType,
6269
- tuple: tupleType,
6270
- 'undefined': undefinedType,
6271
- union: unionType,
6272
- unknown: unknownType,
6273
- 'void': voidType,
6274
- NEVER: NEVER,
6275
- ZodIssueCode: ZodIssueCode,
6276
- quotelessJson: quotelessJson,
6277
- ZodError: ZodError
6278
- });
6279
-
6280
- const ChangelogResponseSchema = z.object({
6281
- title: z.string(),
6282
- content: z.string(),
5832
+ ZodEnum.create;
5833
+ ZodPromise.create;
5834
+ ZodOptional.create;
5835
+ ZodNullable.create;
5836
+
5837
+ const ChangelogResponseSchema = objectType({
5838
+ title: stringType(),
5839
+ content: stringType(),
6283
5840
  });
6284
5841
  const command$4 = 'changelog';
6285
5842
  /**
@@ -6313,70 +5870,234 @@ const builder$4 = (yargs) => {
6313
5870
  };
6314
5871
 
6315
5872
  /**
6316
- * Get LLM Model Based on Configuration
5873
+ * Default retry predicate - retries on non-validation errors
5874
+ */
5875
+ function defaultShouldRetry(error) {
5876
+ // Don't retry validation errors or configuration errors
5877
+ if (error.name.includes('Validation') || error.name.includes('Configuration')) {
5878
+ return false;
5879
+ }
5880
+ // Don't retry authentication errors
5881
+ if (error.name.includes('Authentication')) {
5882
+ return false;
5883
+ }
5884
+ // Retry execution errors and timeouts
5885
+ return true;
5886
+ }
5887
+ /**
5888
+ * Executes an operation with retry logic
5889
+ */
5890
+ async function withRetry(operation, options = {}) {
5891
+ const { maxAttempts = 3, backoffMs = 1000, backoffMultiplier = 2, maxBackoffMs = 10000, onRetry, shouldRetry = defaultShouldRetry } = options;
5892
+ let lastError = new Error('No attempts made');
5893
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
5894
+ try {
5895
+ return await operation();
5896
+ }
5897
+ catch (error) {
5898
+ lastError = error instanceof Error ? error : new Error(String(error));
5899
+ // If this is the last attempt or we shouldn't retry, throw the error
5900
+ if (attempt === maxAttempts || !shouldRetry(lastError)) {
5901
+ throw lastError;
5902
+ }
5903
+ // Calculate delay with exponential backoff
5904
+ const delay = Math.min(backoffMs * Math.pow(backoffMultiplier, attempt - 1), maxBackoffMs);
5905
+ // Call retry callback if provided
5906
+ if (onRetry) {
5907
+ onRetry(attempt, lastError, delay);
5908
+ }
5909
+ // Wait before retrying
5910
+ await new Promise(resolve => setTimeout(resolve, delay));
5911
+ }
5912
+ }
5913
+ // This should never be reached, but TypeScript requires it
5914
+ throw new Error(`Operation failed after ${maxAttempts} attempts. Last error: ${lastError.message}`);
5915
+ }
5916
+
5917
+ /**
5918
+ * Wraps errors with additional context and converts them to LangChain errors
5919
+ */
5920
+ function handleLangChainError(error, context, additionalContext) {
5921
+ // If it's already a LangChain error, re-throw with additional context
5922
+ if (error instanceof LangChainError) {
5923
+ throw new LangChainExecutionError(`${context}: ${error.message}`, {
5924
+ ...error.context,
5925
+ ...additionalContext,
5926
+ originalError: error.name,
5927
+ context
5928
+ });
5929
+ }
5930
+ // If it's a regular Error, wrap it
5931
+ if (error instanceof Error) {
5932
+ throw new LangChainExecutionError(`${context}: ${error.message}`, {
5933
+ originalError: error.name,
5934
+ originalMessage: error.message,
5935
+ stack: error.stack,
5936
+ context,
5937
+ ...additionalContext
5938
+ });
5939
+ }
5940
+ // For unknown error types
5941
+ throw new LangChainExecutionError(`${context}: Unknown error occurred`, {
5942
+ originalError: typeof error,
5943
+ originalValue: String(error),
5944
+ context,
5945
+ ...additionalContext
5946
+ });
5947
+ }
5948
+
5949
+ /**
5950
+ * Creates and configures an LLM instance based on the provider and configuration.
6317
5951
  *
6318
- * @param fields
6319
- * @param configuration
6320
- * @returns LLM Model
5952
+ * @param provider - The LLM provider (openai, anthropic, ollama)
5953
+ * @param model - The specific model to use
5954
+ * @param config - The configuration object containing service settings
5955
+ * @returns Configured LLM instance
5956
+ * @throws LangChainConfigurationError if the provider/model combination is invalid
5957
+ * @throws LangChainExecutionError if LLM instantiation fails
6321
5958
  */
6322
5959
  function getLlm(provider, model, config) {
6323
- if (!model) {
6324
- throw new Error(`Invalid LLM Service: ${provider}/${model}`);
5960
+ // Validate input parameters
5961
+ validateProvider(provider, 'getLlm');
5962
+ validateModel(model, provider, 'getLlm');
5963
+ validateRequired(config, 'config', 'getLlm');
5964
+ // Get the API key once and validate it
5965
+ let apiKey;
5966
+ try {
5967
+ apiKey = getApiKeyForModel(config);
6325
5968
  }
6326
- switch (provider) {
6327
- case 'anthropic':
6328
- return new anthropic.ChatAnthropic({
6329
- anthropicApiKey: getApiKeyForModel(config),
6330
- maxConcurrency: config.service.maxConcurrent,
6331
- model,
6332
- });
6333
- case 'ollama':
6334
- return new ollama.ChatOllama({
6335
- baseUrl: DEFAULT_OLLAMA_LLM_SERVICE.endpoint,
5969
+ catch (error) {
5970
+ handleLangChainError(error, 'getLlm: Failed to retrieve API key', { provider, model });
5971
+ }
5972
+ try {
5973
+ switch (provider) {
5974
+ case 'anthropic':
5975
+ return new anthropic.ChatAnthropic({
5976
+ anthropicApiKey: apiKey,
5977
+ maxConcurrency: config.service.maxConcurrent,
5978
+ model,
5979
+ });
5980
+ case 'ollama':
5981
+ // Use endpoint from service config if available, otherwise fall back to default
5982
+ const endpoint = 'endpoint' in config.service
5983
+ ? config.service.endpoint
5984
+ : DEFAULT_OLLAMA_LLM_SERVICE.endpoint;
5985
+ return new ollama.ChatOllama({
5986
+ baseUrl: endpoint,
5987
+ maxConcurrency: config.service.maxConcurrent,
5988
+ model,
5989
+ });
5990
+ case 'openai':
5991
+ return new openai.ChatOpenAI({
5992
+ openAIApiKey: apiKey,
5993
+ model,
5994
+ temperature: config.service.temperature || 0.2,
5995
+ });
5996
+ default:
5997
+ throw new LangChainConfigurationError(`getLlm: Unsupported provider '${provider}'`, { provider, model, supportedProviders: ['openai', 'anthropic', 'ollama'] });
5998
+ }
5999
+ }
6000
+ catch (error) {
6001
+ // If it's already a LangChain error, re-throw it
6002
+ if (error instanceof LangChainConfigurationError || error instanceof LangChainExecutionError) {
6003
+ throw error;
6004
+ }
6005
+ // Wrap other errors
6006
+ handleLangChainError(error, `getLlm: Failed to instantiate ${provider} LLM`, {
6007
+ provider,
6008
+ model,
6009
+ hasApiKey: !!apiKey,
6010
+ serviceConfig: {
6336
6011
  maxConcurrency: config.service.maxConcurrent,
6337
- model,
6338
- });
6339
- case 'openai':
6340
- default:
6341
- const openAiModel = new openai.ChatOpenAI({
6342
- openAIApiKey: getApiKeyForModel(config),
6343
- model,
6344
- temperature: config.service.temperature || 0.2,
6345
- });
6346
- return openAiModel;
6012
+ temperature: config.service.temperature
6013
+ }
6014
+ });
6347
6015
  }
6348
6016
  }
6349
6017
 
6018
+ /**
6019
+ * Creates a PromptTemplate from a template string or returns a fallback template.
6020
+ *
6021
+ * @param params - The prompt creation parameters
6022
+ * @returns A configured PromptTemplate instance
6023
+ * @throws LangChainValidationError if neither template nor fallback is provided or if parameters are invalid
6024
+ * @throws LangChainExecutionError if PromptTemplate instantiation fails
6025
+ */
6350
6026
  function getPrompt({ template, variables, fallback }) {
6351
- if (!template && !fallback)
6352
- throw new Error('Must provide either a template or a fallback');
6353
- return (template
6354
- ? new prompts$1.PromptTemplate({
6355
- template,
6356
- inputVariables: variables,
6357
- templateFormat: 'mustache',
6358
- })
6359
- : fallback);
6027
+ // Validate that we have either a template or fallback
6028
+ if (!template && !fallback) {
6029
+ throw new LangChainValidationError('getPrompt: Must provide either a template string or a fallback PromptTemplate', { hasTemplate: !!template, hasFallback: !!fallback, variables });
6030
+ }
6031
+ // Validate variables array
6032
+ validateRequired(variables, 'variables', 'getPrompt');
6033
+ validateNonEmptyArray(variables, 'variables', 'getPrompt');
6034
+ // If using template, validate it and create PromptTemplate
6035
+ if (template) {
6036
+ validateNonEmptyString(template, 'template', 'getPrompt');
6037
+ try {
6038
+ return new prompts$1.PromptTemplate({
6039
+ template,
6040
+ inputVariables: variables,
6041
+ templateFormat: 'mustache',
6042
+ });
6043
+ }
6044
+ catch (error) {
6045
+ handleLangChainError(error, 'getPrompt: Failed to create PromptTemplate', {
6046
+ template: template.substring(0, 100) + (template.length > 100 ? '...' : ''),
6047
+ variables,
6048
+ templateFormat: 'mustache'
6049
+ });
6050
+ }
6051
+ }
6052
+ // Validate fallback if using it
6053
+ if (fallback) {
6054
+ validateRequired(fallback, 'fallback', 'getPrompt');
6055
+ if (!(fallback instanceof prompts$1.PromptTemplate)) {
6056
+ throw new LangChainValidationError('getPrompt: Fallback must be a PromptTemplate instance', { fallbackType: typeof fallback, fallbackConstructor: fallback.constructor?.name });
6057
+ }
6058
+ return fallback;
6059
+ }
6060
+ // This should never be reached, but TypeScript requires it
6061
+ throw new LangChainExecutionError('getPrompt: Unexpected execution path - neither template nor fallback available', { template, fallback, variables });
6360
6062
  }
6361
6063
 
6064
+ /**
6065
+ * Executes a LangChain pipeline with the provided LLM, prompt, variables, and parser.
6066
+ * @param params - The execution parameters
6067
+ * @returns The parsed result from the LLM chain
6068
+ * @throws LangChainExecutionError if the chain execution fails or returns empty results
6069
+ */
6362
6070
  const executeChain = async ({ llm, prompt, variables, parser }) => {
6363
- if (!llm || !prompt || !variables) {
6364
- throw new Error('The input parameters "llm", "prompt", and "variables" are all required.');
6071
+ // Validate all required parameters
6072
+ validateRequired(llm, 'llm', 'executeChain');
6073
+ validateRequired(prompt, 'prompt', 'executeChain');
6074
+ validateRequired(variables, 'variables', 'executeChain');
6075
+ validateRequired(parser, 'parser', 'executeChain');
6076
+ // Validate that variables is an object
6077
+ if (typeof variables !== 'object' || Array.isArray(variables)) {
6078
+ throw new LangChainExecutionError('executeChain: Variables must be a non-array object', { variables, type: typeof variables, isArray: Array.isArray(variables) });
6365
6079
  }
6366
- const chain = prompt.pipe(llm).pipe(parser);
6367
- let res;
6368
6080
  try {
6369
- res = await chain.invoke(variables);
6081
+ const chain = prompt.pipe(llm).pipe(parser);
6082
+ const result = await chain.invoke(variables);
6083
+ console.debug('LLMChain call result:', result);
6084
+ if (result === null || result === undefined) {
6085
+ throw new LangChainExecutionError('executeChain: Chain execution returned null or undefined result', { variables, promptInputVariables: prompt.inputVariables });
6086
+ }
6087
+ return result;
6370
6088
  }
6371
6089
  catch (error) {
6372
- if (error instanceof Error) {
6373
- throw new Error(`LLMChain call error: ${error.message}`);
6090
+ // Re-throw LangChain errors as-is
6091
+ if (error instanceof LangChainExecutionError) {
6092
+ throw error;
6374
6093
  }
6094
+ // Wrap other errors with context
6095
+ handleLangChainError(error, 'executeChain: Chain execution failed', {
6096
+ promptInputVariables: prompt.inputVariables,
6097
+ variableKeys: Object.keys(variables),
6098
+ parserType: parser.constructor.name
6099
+ });
6375
6100
  }
6376
- if (!res) {
6377
- throw new Error('Empty response from LLMChain call');
6378
- }
6379
- return res;
6380
6101
  };
6381
6102
 
6382
6103
  function extractTicketIdFromBranchName(branchName) {
@@ -6415,19 +6136,20 @@ const getChangesSinceLastTag = async ({ git }) => {
6415
6136
  };
6416
6137
 
6417
6138
  /**
6418
- * Retrieves the commit log range between two specified commits.
6139
+ * Retrieves the commit log range between two specified commits (inclusive of both commits).
6419
6140
  *
6420
- * @param from - The starting commit (can be a commit hash, HEAD reference, or branch name).
6421
- * @param to - The ending commit (can be a commit hash, HEAD reference, or branch name).
6141
+ * @param from - The starting commit (can be a commit hash, HEAD reference, or branch name). This commit will be included in the results.
6142
+ * @param to - The ending commit (can be a commit hash, HEAD reference, or branch name). This commit will be included in the results.
6422
6143
  * @param options - Additional options for retrieving the commit log range.
6423
- * @returns A promise that resolves to an array of commit log messages.
6144
+ * @returns A promise that resolves to an array of commit log messages, including both the 'from' and 'to' commits.
6424
6145
  * @throws If there is an error retrieving the commit log range.
6425
6146
  */
6426
6147
  async function getCommitLogRange(from, to, { noMerges, git }) {
6427
6148
  try {
6428
- // Use the git range syntax directly (from..to) which works with both commit hashes and references
6149
+ // Use from^..to to include the 'from' commit in the range
6150
+ // This works because from^..to means "commits reachable from 'to' but not from the parent of 'from'"
6429
6151
  const logOptions = {
6430
- from,
6152
+ from: `${from}^`,
6431
6153
  to,
6432
6154
  '--no-merges': noMerges
6433
6155
  };
@@ -6435,7 +6157,29 @@ async function getCommitLogRange(from, to, { noMerges, git }) {
6435
6157
  return commitLog.all.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6436
6158
  }
6437
6159
  catch (error) {
6438
- // If there's an error, handle it appropriately
6160
+ // If from^ fails (e.g., 'from' is the first commit), fall back to using from..to and manually adding the 'from' commit
6161
+ if (error instanceof Error && error.message.includes('unknown revision')) {
6162
+ try {
6163
+ // Get the 'from' commit separately
6164
+ const fromCommitLog = await git.log({ from: from, maxCount: 1 });
6165
+ const fromCommit = fromCommitLog.latest;
6166
+ // Get the range from..to (excluding 'from')
6167
+ const rangeLogOptions = {
6168
+ from,
6169
+ to,
6170
+ '--no-merges': noMerges
6171
+ };
6172
+ const rangeCommitLog = await git.log(rangeLogOptions);
6173
+ // Combine the 'from' commit with the range commits
6174
+ const allCommits = fromCommit
6175
+ ? [fromCommit, ...rangeCommitLog.all]
6176
+ : rangeCommitLog.all;
6177
+ return allCommits.map(({ message, date, body, author_name, hash, author_email }) => `[${date}] ${message}\n${body}\n(${hash}) - ${author_name}<${author_email}>`);
6178
+ }
6179
+ catch (fallbackError) {
6180
+ throw fallbackError;
6181
+ }
6182
+ }
6439
6183
  throw error;
6440
6184
  }
6441
6185
  }
@@ -6496,38 +6240,38 @@ async function getCommitLogAgainstBranch({ git, logger, targetBranch, }) {
6496
6240
  */
6497
6241
  async function getCommitLogCurrentBranch({ git, logger, comparisonBranch = 'main', comparisonRemote = 'origin', }) {
6498
6242
  try {
6499
- // Get the current branch name
6500
- const branch = await getCurrentBranchName({ git });
6501
- // Check if the current branch has any commits
6502
- const hasCommits = (await git.raw(['rev-list', '--count', branch])) !== '0';
6243
+ const branchName = await getCurrentBranchName({ git });
6244
+ const hasCommits = (await git.raw(['rev-list', '--count', branchName])) !== '0';
6503
6245
  if (!hasCommits) {
6504
6246
  logger?.log('No commits on the current branch.');
6505
6247
  return [];
6506
6248
  }
6507
- // Get the list of commits that are unique to the current branch
6508
6249
  let uniqueCommits;
6509
- if (comparisonBranch === branch) {
6250
+ if (comparisonBranch === branchName) {
6510
6251
  // If the comparison branch is the same as the current branch, we compare against the remote.
6511
- uniqueCommits = (await git.raw(['rev-list', `${comparisonRemote}/${comparisonBranch}..${branch}`]))
6252
+ uniqueCommits = (await git.raw(['rev-list', `${comparisonRemote}/${comparisonBranch}..${branchName}`]))
6512
6253
  .split('\n')
6513
6254
  .filter(Boolean)
6514
6255
  .reverse();
6515
6256
  }
6516
6257
  else {
6517
6258
  // Your existing code for different branches
6518
- uniqueCommits = (await git.raw(['rev-list', `${comparisonBranch}..${branch}`]))
6259
+ uniqueCommits = (await git.raw(['rev-list', `${comparisonBranch}..${branchName}`]))
6519
6260
  .split('\n')
6520
6261
  .filter(Boolean)
6521
6262
  .reverse();
6522
6263
  }
6523
- logger?.verbose(`Found ${uniqueCommits.length} unique commits on "${branch}"`, { color: 'blue' });
6264
+ logger?.verbose(`Found ${uniqueCommits.length} unique commits on "${branchName}"`, {
6265
+ color: 'blue',
6266
+ });
6524
6267
  const firstCommit = uniqueCommits[0];
6525
6268
  const lastCommit = uniqueCommits[uniqueCommits.length - 1];
6526
6269
  if (!firstCommit || !lastCommit) {
6527
- logger?.log('Unable to determine first and last commit on the current branch', { color: 'yellow' });
6270
+ logger?.log('Unable to determine first and last commit on the current branch', {
6271
+ color: 'yellow',
6272
+ });
6528
6273
  return [];
6529
6274
  }
6530
- // Retrieve commit log with messages
6531
6275
  return await getCommitLogRange(firstCommit, lastCommit, { git, noMerges: true });
6532
6276
  }
6533
6277
  catch (error) {
@@ -6656,17 +6400,35 @@ const CONVENTIONAL_COMMIT_PROMPT = new prompts$1.PromptTemplate({
6656
6400
  *
6657
6401
  * @param text template string
6658
6402
  * @param inputVariables template variables
6659
- * @returns boolean or error message
6403
+ * @throws Error if validation fails
6660
6404
  */
6661
6405
  function validatePromptTemplate(text, inputVariables) {
6662
- if (!text) {
6663
- return 'Prompt template cannot be empty';
6406
+ if (!text || text.trim() === '') {
6407
+ throw new Error('Prompt template cannot be empty');
6664
6408
  }
6665
- if (!inputVariables.some((entry) => text.includes(entry))) {
6666
- return ('Prompt template must include at least one of the following input variables: ' +
6667
- inputVariables.map((value) => `{${value}}`).join(', '));
6409
+ if (!inputVariables || inputVariables.length === 0) {
6410
+ return; // No variables to validate
6411
+ }
6412
+ // Extract variables from template using regex to find {variable} patterns
6413
+ // This regex matches {variable_name} with no whitespace inside braces
6414
+ // Excludes JSON-like patterns with quotes, colons, or whitespace
6415
+ const templateVariableRegex = /\{([^}\s:"']+)\}/g;
6416
+ const foundVariables = new Set();
6417
+ let match;
6418
+ while ((match = templateVariableRegex.exec(text)) !== null) {
6419
+ foundVariables.add(match[1]);
6420
+ }
6421
+ // Check if all required variables are present in template
6422
+ const missingVariables = inputVariables.filter(variable => !foundVariables.has(variable));
6423
+ if (missingVariables.length > 0) {
6424
+ throw new Error(`Prompt template is missing required variables: ${missingVariables.map(v => `{${v}}`).join(', ')}. ` +
6425
+ `Found variables: ${Array.from(foundVariables).map(v => `{${v}}`).join(', ') || 'none'}`);
6426
+ }
6427
+ // Warn about unused variables in template (optional check)
6428
+ const unusedVariables = Array.from(foundVariables).filter(variable => !inputVariables.includes(variable));
6429
+ if (unusedVariables.length > 0) {
6430
+ console.warn(`Prompt template contains undefined variables: ${unusedVariables.map(v => `{${v}}`).join(', ')}`);
6668
6431
  }
6669
- return true;
6670
6432
  }
6671
6433
 
6672
6434
  async function editPrompt(options) {
@@ -6675,7 +6437,15 @@ async function editPrompt(options) {
6675
6437
  default: options.prompt?.length ? options.prompt : COMMIT_PROMPT.template,
6676
6438
  waitForUseInput: false,
6677
6439
  postfix: 'Press ENTER to continue',
6678
- validate: (text) => validatePromptTemplate(text, COMMIT_PROMPT.inputVariables),
6440
+ validate: (text) => {
6441
+ try {
6442
+ validatePromptTemplate(text, COMMIT_PROMPT.inputVariables);
6443
+ return true;
6444
+ }
6445
+ catch (error) {
6446
+ return error instanceof Error ? error.message : 'Invalid prompt template';
6447
+ }
6448
+ },
6679
6449
  });
6680
6450
  }
6681
6451
 
@@ -6894,7 +6664,9 @@ const handler$4 = async (argv, logger) => {
6894
6664
  const llm = getLlm(provider, model, config);
6895
6665
  const INTERACTIVE = isInteractive(config);
6896
6666
  if (INTERACTIVE) {
6897
- logger.log(LOGO);
6667
+ if (!config.hideCocoBanner) {
6668
+ logger.log(LOGO);
6669
+ }
6898
6670
  }
6899
6671
  async function factory() {
6900
6672
  const branchName = await getCurrentBranchName({ git });
@@ -6926,9 +6698,10 @@ const handler$4 = async (argv, logger) => {
6926
6698
  logger.verbose(`No range, branch, or tag option provided. Defaulting to current branch`, {
6927
6699
  color: 'yellow',
6928
6700
  });
6701
+ const commits = await getCommitLogCurrentBranch({ git, logger });
6929
6702
  return {
6930
6703
  branch: branchName,
6931
- commits: await getCommitLogCurrentBranch({ git, logger }),
6704
+ commits,
6932
6705
  };
6933
6706
  }
6934
6707
  async function parser({ branch, commits }) {
@@ -7005,16 +6778,16 @@ var changelog = {
7005
6778
 
7006
6779
  const conventionalTypeRegex = /^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\(.+\))?:/;
7007
6780
  // Regular commit message schema with basic validation
7008
- const CommitMessageResponseSchema = z.object({
7009
- title: z.string(),
7010
- body: z.string(),
6781
+ const CommitMessageResponseSchema = objectType({
6782
+ title: stringType(),
6783
+ body: stringType(),
7011
6784
  });
7012
6785
  // Conventional commit message schema with strict formatting rules
7013
- const ConventionalCommitMessageResponseSchema = z.object({
7014
- title: z.string()
6786
+ const ConventionalCommitMessageResponseSchema = objectType({
6787
+ title: stringType()
7015
6788
  .max(50, "Title must be 50 characters or less")
7016
6789
  .refine((title) => conventionalTypeRegex.test(title), "Title must follow Conventional Commits format (e.g., 'feat: add new feature' or 'fix(scope): fix bug')"),
7017
- body: z.string()
6790
+ body: stringType()
7018
6791
  // .max(280, "Body must be 280 characters or less"),
7019
6792
  });
7020
6793
  const command$3 = 'commit';
@@ -7071,152 +6844,33 @@ const builder$3 = (yargs) => {
7071
6844
  return yargs.options(options$3).usage(getCommandUsageHeader(command$3));
7072
6845
  };
7073
6846
 
7074
- /**
7075
- * Extract the path from a file path string.
7076
- * @param {string} filePath - The full file path.
7077
- * @returns {string} The path portion of the file path.
7078
- */
7079
- function getPathFromFilePath(filePath) {
7080
- return filePath.split('/').slice(0, -1).join('/');
7081
- }
7082
-
7083
- async function summarize(documents$1, { chain, textSplitter, options }) {
7084
- const { returnIntermediateSteps = false } = options || {};
7085
- const docs = await textSplitter.splitDocuments(documents$1.map((doc) => new documents.Document(doc)));
7086
- const res = await chain.invoke({
7087
- input_documents: docs,
7088
- returnIntermediateSteps,
7089
- });
7090
- if (res.error)
7091
- throw new Error(res.error);
7092
- return res.text && res.text.trim();
7093
- }
6847
+ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
7094
6848
 
7095
6849
  /**
7096
- * Create groups from a given node info.
7097
- * @param {DiffNode} node - The node info to start grouping.
7098
- * @returns {DirectoryDiff[]} The groups created.
6850
+ * Base interface that all chains must implement.
7099
6851
  */
7100
- function createDirectoryDiffs(node) {
7101
- const groupByPath = {};
7102
- function traverse(node) {
7103
- node.diffs.forEach((diff) => {
7104
- const path = getPathFromFilePath(diff.file);
7105
- if (!groupByPath[path]) {
7106
- groupByPath[path] = { diffs: [], path, tokenCount: 0 };
7107
- }
7108
- groupByPath[path].diffs.push(diff);
7109
- groupByPath[path].tokenCount += diff.tokenCount;
7110
- });
7111
- node.children.forEach(traverse);
6852
+ class BaseChain extends base.BaseLangChain {
6853
+ get lc_namespace() {
6854
+ return ["langchain", "chains", this._chainType()];
7112
6855
  }
7113
- traverse(node);
7114
- return Object.values(groupByPath);
7115
- }
7116
- /**
7117
- * Summarize a directory diff asynchronously.
7118
- */
7119
- async function summarizeDirectoryDiff(directory, { chain, textSplitter, tokenizer }) {
7120
- try {
7121
- const directorySummary = await summarize(directory.diffs.map((diff) => ({
7122
- pageContent: diff.diff,
7123
- metadata: {
7124
- file: diff.file,
7125
- summary: diff.summary,
7126
- },
7127
- })), {
7128
- chain,
7129
- textSplitter,
7130
- options: {
7131
- returnIntermediateSteps: true,
7132
- },
7133
- });
7134
- const newTokenTotal = tokenizer(directorySummary);
7135
- return {
7136
- diffs: directory.diffs,
7137
- path: directory.path,
7138
- summary: directorySummary,
7139
- tokenCount: newTokenTotal,
7140
- };
7141
- }
7142
- catch (error) {
7143
- console.error(error);
7144
- return directory;
7145
- }
7146
- }
7147
- const defaultOutputCallback = (group) => {
7148
- let output = `
7149
- -------\n* changes in "/${group.path}"\n\n`;
7150
- if (group.summary) {
7151
- output += `${group.diffs.map((diff) => ` • ${diff.summary}`).join('\n')}\n\nSummary:\n\n${group.summary}\n\n`;
7152
- }
7153
- else {
7154
- output += `${group.diffs.map((diff) => ` • ${diff.summary}\n\n${diff.diff}`).join('\n\n')}\n\n`;
7155
- }
7156
- return output;
7157
- };
7158
- async function summarizeDiffs(rootDiffNode, { tokenizer, logger, maxTokens = 2048, textSplitter, chain, handleOutput = defaultOutputCallback, }) {
7159
- const queue = new pQueue({ concurrency: 8 });
7160
- logger.startTimer().startSpinner(`Organizing Diffs...`, { color: 'blue' });
7161
- const directoryDiffs = createDirectoryDiffs(rootDiffNode);
7162
- // Sort by token count descending
7163
- directoryDiffs.sort((a, b) => b.tokenCount - a.tokenCount);
7164
- let totalTokenCount = directoryDiffs.reduce((sum, group) => sum + group.tokenCount, 0);
7165
- logger.stopSpinner('Diffs Organized').stopTimer();
7166
- logger.startSpinner(`Consolidating Diffs`, { color: 'blue' });
7167
- const processingTasks = directoryDiffs.map((group, i) => {
7168
- return queue.add(async () => {
7169
- // If the diff token count is already less than the average req, we can skip summarizing.
7170
- const isLessThanAvgTokenReq = group.tokenCount <= maxTokens / directoryDiffs.length;
7171
- if (totalTokenCount <= maxTokens || isLessThanAvgTokenReq) {
7172
- return group;
7173
- }
7174
- group = await summarizeDirectoryDiff(group, {
7175
- chain,
7176
- textSplitter,
7177
- tokenizer,
7178
- });
7179
- // We need to subtract the old token count and add the new one
7180
- totalTokenCount = totalTokenCount - directoryDiffs[i].tokenCount + group.tokenCount;
7181
- directoryDiffs[i] = group;
7182
- logger
7183
- .verbose(`\n • Summarized diffs in "/${group.path}" `, { color: 'blue' })
7184
- .verbose(`\nTotal token count: ${totalTokenCount}`, {
7185
- color: totalTokenCount > maxTokens ? 'yellow' : 'green',
7186
- });
7187
- return group;
7188
- }, { priority: group.tokenCount });
7189
- });
7190
- await Promise.all(processingTasks);
7191
- logger.stopSpinner(`Summarized Diffs`);
7192
- return directoryDiffs.map(handleOutput).join('');
7193
- }
7194
-
7195
- /**
7196
- * Base interface that all chains must implement.
7197
- */
7198
- class BaseChain extends base.BaseLangChain {
7199
- get lc_namespace() {
7200
- return ["langchain", "chains", this._chainType()];
7201
- }
7202
- constructor(fields,
7203
- /** @deprecated */
7204
- verbose,
7205
- /** @deprecated */
7206
- callbacks) {
7207
- if (arguments.length === 1 &&
7208
- typeof fields === "object" &&
7209
- !("saveContext" in fields)) {
7210
- // fields is not a BaseMemory
7211
- const { memory, callbackManager, ...rest } = fields;
7212
- super({ ...rest, callbacks: callbackManager ?? rest.callbacks });
7213
- this.memory = memory;
7214
- }
7215
- else {
7216
- // fields is a BaseMemory
7217
- super({ verbose, callbacks });
7218
- this.memory = fields;
7219
- }
6856
+ constructor(fields,
6857
+ /** @deprecated */
6858
+ verbose,
6859
+ /** @deprecated */
6860
+ callbacks) {
6861
+ if (arguments.length === 1 &&
6862
+ typeof fields === "object" &&
6863
+ !("saveContext" in fields)) {
6864
+ // fields is not a BaseMemory
6865
+ const { memory, callbackManager, ...rest } = fields;
6866
+ super({ ...rest, callbacks: callbackManager ?? rest.callbacks });
6867
+ this.memory = memory;
6868
+ }
6869
+ else {
6870
+ // fields is a BaseMemory
6871
+ super({ verbose, callbacks });
6872
+ this.memory = fields;
6873
+ }
7220
6874
  }
7221
6875
  /** @ignore */
7222
6876
  _selectMemoryInputs(values) {
@@ -7638,15 +7292,550 @@ class LLMChain extends BaseChain {
7638
7292
  prompt: this.prompt.serialize(),
7639
7293
  };
7640
7294
  }
7641
- _getNumTokens(text) {
7642
- return _getLanguageModel(this.llm).getNumTokens(text);
7295
+ _getNumTokens(text) {
7296
+ return _getLanguageModel(this.llm).getNumTokens(text);
7297
+ }
7298
+ }
7299
+
7300
+ var llm_chain = /*#__PURE__*/Object.freeze({
7301
+ __proto__: null,
7302
+ LLMChain: LLMChain
7303
+ });
7304
+
7305
+ const NAIVE_FIX_TEMPLATE = `Instructions:
7306
+ --------------
7307
+ {instructions}
7308
+ --------------
7309
+ Completion:
7310
+ --------------
7311
+ {completion}
7312
+ --------------
7313
+
7314
+ Above, the Completion did not satisfy the constraints given in the Instructions.
7315
+ Error:
7316
+ --------------
7317
+ {error}
7318
+ --------------
7319
+
7320
+ Please try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions:`;
7321
+ const NAIVE_FIX_PROMPT =
7322
+ /* #__PURE__ */ prompts$1.PromptTemplate.fromTemplate(NAIVE_FIX_TEMPLATE);
7323
+
7324
+ function isLLMChain(x) {
7325
+ return (x.prompt !== undefined && x.llm !== undefined);
7326
+ }
7327
+ /**
7328
+ * Class that extends the BaseOutputParser to handle situations where the
7329
+ * initial parsing attempt fails. It contains a retryChain for retrying
7330
+ * the parsing process in case of a failure.
7331
+ */
7332
+ class OutputFixingParser extends output_parsers.BaseOutputParser {
7333
+ static lc_name() {
7334
+ return "OutputFixingParser";
7335
+ }
7336
+ /**
7337
+ * Static method to create a new instance of OutputFixingParser using a
7338
+ * given language model, parser, and optional fields.
7339
+ * @param llm The language model to be used.
7340
+ * @param parser The parser to be used.
7341
+ * @param fields Optional fields which may contain a prompt.
7342
+ * @returns A new instance of OutputFixingParser.
7343
+ */
7344
+ static fromLLM(llm, parser, fields) {
7345
+ const prompt = fields?.prompt ?? NAIVE_FIX_PROMPT;
7346
+ const chain = new LLMChain({ llm, prompt });
7347
+ return new OutputFixingParser({ parser, retryChain: chain });
7348
+ }
7349
+ constructor({ parser, retryChain, }) {
7350
+ super(...arguments);
7351
+ Object.defineProperty(this, "lc_namespace", {
7352
+ enumerable: true,
7353
+ configurable: true,
7354
+ writable: true,
7355
+ value: ["langchain", "output_parsers", "fix"]
7356
+ });
7357
+ Object.defineProperty(this, "lc_serializable", {
7358
+ enumerable: true,
7359
+ configurable: true,
7360
+ writable: true,
7361
+ value: true
7362
+ });
7363
+ Object.defineProperty(this, "parser", {
7364
+ enumerable: true,
7365
+ configurable: true,
7366
+ writable: true,
7367
+ value: void 0
7368
+ });
7369
+ Object.defineProperty(this, "retryChain", {
7370
+ enumerable: true,
7371
+ configurable: true,
7372
+ writable: true,
7373
+ value: void 0
7374
+ });
7375
+ this.parser = parser;
7376
+ this.retryChain = retryChain;
7377
+ }
7378
+ /**
7379
+ * Method to parse the completion using the parser. If the initial parsing
7380
+ * fails, it uses the retryChain to attempt to fix the output and retry
7381
+ * the parsing process.
7382
+ * @param completion The completion to be parsed.
7383
+ * @param callbacks Optional callbacks to be used during parsing.
7384
+ * @returns The parsed output.
7385
+ */
7386
+ async parse(completion, callbacks) {
7387
+ try {
7388
+ return await this.parser.parse(completion, callbacks);
7389
+ }
7390
+ catch (e) {
7391
+ // eslint-disable-next-line no-instanceof/no-instanceof
7392
+ if (e instanceof output_parsers.OutputParserException) {
7393
+ const retryInput = {
7394
+ instructions: this.parser.getFormatInstructions(),
7395
+ completion,
7396
+ error: e,
7397
+ };
7398
+ if (isLLMChain(this.retryChain)) {
7399
+ const result = await this.retryChain.call(retryInput, callbacks);
7400
+ const newCompletion = result[this.retryChain.outputKey];
7401
+ return this.parser.parse(newCompletion, callbacks);
7402
+ }
7403
+ else {
7404
+ const result = await this.retryChain.invoke(retryInput, {
7405
+ callbacks,
7406
+ });
7407
+ return result;
7408
+ }
7409
+ }
7410
+ throw e;
7411
+ }
7412
+ }
7413
+ /**
7414
+ * Method to get the format instructions for the parser.
7415
+ * @returns The format instructions for the parser.
7416
+ */
7417
+ getFormatInstructions() {
7418
+ return this.parser.getFormatInstructions();
7419
+ }
7420
+ }
7421
+
7422
+ /**
7423
+ * Creates a parser with built-in retry logic for schema-based generation
7424
+ * @param schema - Zod schema for the expected output structure
7425
+ * @param llm - LLM instance for retry attempts
7426
+ * @param options - Configuration options for retry behavior
7427
+ * @returns OutputFixingParser configured with retry logic
7428
+ * @throws LangChainExecutionError if parser creation fails
7429
+ */
7430
+ function createSchemaParser(schema, llm, options = {}) {
7431
+ // Validate required parameters
7432
+ validateRequired(schema, 'schema', 'createSchemaParser');
7433
+ validateRequired(llm, 'llm', 'createSchemaParser');
7434
+ validateRequired(options, 'options', 'createSchemaParser');
7435
+ // Validate schema is actually a Zod schema
7436
+ if (typeof schema.parse !== 'function') {
7437
+ throw new LangChainExecutionError('createSchemaParser: Schema must be a valid Zod schema with a parse method', { schemaType: typeof schema, hasParseMethod: typeof schema.parse });
7438
+ }
7439
+ // Validate options structure
7440
+ if (typeof options !== 'object' || Array.isArray(options)) {
7441
+ throw new LangChainExecutionError('createSchemaParser: Options must be a non-array object', { options, type: typeof options, isArray: Array.isArray(options) });
7442
+ }
7443
+ const { retryTemplate } = options;
7444
+ // Validate retryTemplate if provided
7445
+ if (retryTemplate !== undefined && typeof retryTemplate !== 'string') {
7446
+ throw new LangChainExecutionError('createSchemaParser: retryTemplate must be a string when provided', { retryTemplate, type: typeof retryTemplate });
7447
+ }
7448
+ try {
7449
+ const baseParser = new output_parsers.StructuredOutputParser(schema);
7450
+ const defaultRetryTemplate = `The following text failed to parse as valid JSON. Please convert it into a valid JSON object that matches the required schema.
7451
+
7452
+ ## Text to fix:
7453
+ {completion}
7454
+
7455
+ ## Instructions:
7456
+ {instructions}
7457
+
7458
+ You must return ONLY valid JSON that matches the schema exactly. Do not include any additional text, explanations, or markdown formatting:`;
7459
+ const retryPromptTemplate = new prompts$1.PromptTemplate({
7460
+ template: retryTemplate || defaultRetryTemplate,
7461
+ inputVariables: ['completion', 'instructions'],
7462
+ });
7463
+ const retryChain = retryPromptTemplate.pipe(llm).pipe(baseParser);
7464
+ return new OutputFixingParser({
7465
+ parser: baseParser,
7466
+ retryChain: retryChain,
7467
+ });
7468
+ }
7469
+ catch (error) {
7470
+ handleLangChainError(error, 'createSchemaParser: Failed to create schema parser', {
7471
+ schemaName: schema.constructor.name,
7472
+ llmType: llm.constructor.name,
7473
+ hasRetryTemplate: !!retryTemplate
7474
+ });
7475
+ }
7476
+ }
7477
+
7478
+ /**
7479
+ * High-level function that combines chain execution with schema-based parsing
7480
+ * Includes automatic retry logic and graceful degradation
7481
+ * @param schema - Zod schema for the expected output structure
7482
+ * @param llm - LLM instance
7483
+ * @param prompt - Prompt template
7484
+ * @param variables - Variables for the prompt
7485
+ * @param options - Configuration options
7486
+ * @returns Parsed result matching the schema type
7487
+ */
7488
+ async function executeChainWithSchema(schema, llm, prompt, variables, options = {}) {
7489
+ const { retryOptions = { maxAttempts: 3 }, fallbackParser, onFallback, ...parserOptions } = options;
7490
+ const parser = createSchemaParser(schema, llm, parserOptions);
7491
+ // Define the operation to retry
7492
+ const operation = async () => {
7493
+ const result = await executeChain({
7494
+ llm,
7495
+ prompt,
7496
+ variables,
7497
+ parser,
7498
+ });
7499
+ return result;
7500
+ };
7501
+ try {
7502
+ // Use the general retry utility
7503
+ return await withRetry(operation, retryOptions);
7504
+ }
7505
+ catch (error) {
7506
+ // If all retries failed and we have a fallback parser, use it
7507
+ if (fallbackParser) {
7508
+ if (onFallback) {
7509
+ onFallback();
7510
+ }
7511
+ // Generate without structured parsing as fallback
7512
+ const fallbackResult = await executeChain({
7513
+ llm,
7514
+ prompt,
7515
+ variables,
7516
+ parser: new output_parsers.StringOutputParser(),
7517
+ });
7518
+ const fallbackText = typeof fallbackResult === 'string' ? fallbackResult : String(fallbackResult);
7519
+ return fallbackParser(fallbackText);
7520
+ }
7521
+ // No fallback available, re-throw the error
7522
+ throw error;
7523
+ }
7524
+ }
7525
+
7526
+ /**
7527
+ * Extract the path from a file path string.
7528
+ * @param {string} filePath - The full file path.
7529
+ * @returns {string} The path portion of the file path.
7530
+ */
7531
+ function getPathFromFilePath(filePath) {
7532
+ return filePath.split('/').slice(0, -1).join('/');
7533
+ }
7534
+
7535
+ async function summarize(documents$1, { chain, textSplitter, options }) {
7536
+ const { returnIntermediateSteps = false } = options || {};
7537
+ const docs = await textSplitter.splitDocuments(documents$1.map((doc) => new documents.Document(doc)));
7538
+ const res = await chain.invoke({
7539
+ input_documents: docs,
7540
+ returnIntermediateSteps,
7541
+ });
7542
+ if (res.error)
7543
+ throw new Error(res.error);
7544
+ return res.text && res.text.trim();
7545
+ }
7546
+
7547
+ /**
7548
+ * Create groups from a given node info.
7549
+ * @param {DiffNode} node - The node info to start grouping.
7550
+ * @returns {DirectoryDiff[]} The groups created.
7551
+ */
7552
+ function createDirectoryDiffs(node) {
7553
+ const groupByPath = {};
7554
+ function traverse(node) {
7555
+ node.diffs.forEach((diff) => {
7556
+ const path = getPathFromFilePath(diff.file);
7557
+ if (!groupByPath[path]) {
7558
+ groupByPath[path] = { diffs: [], path, tokenCount: 0 };
7559
+ }
7560
+ groupByPath[path].diffs.push(diff);
7561
+ groupByPath[path].tokenCount += diff.tokenCount;
7562
+ });
7563
+ node.children.forEach(traverse);
7564
+ }
7565
+ traverse(node);
7566
+ return Object.values(groupByPath);
7567
+ }
7568
+ /**
7569
+ * Summarize a directory diff asynchronously.
7570
+ */
7571
+ async function summarizeDirectoryDiff(directory, { chain, textSplitter, tokenizer }) {
7572
+ try {
7573
+ const directorySummary = await summarize(directory.diffs.map((diff) => ({
7574
+ pageContent: diff.diff,
7575
+ metadata: {
7576
+ file: diff.file,
7577
+ summary: diff.summary,
7578
+ },
7579
+ })), {
7580
+ chain,
7581
+ textSplitter,
7582
+ options: {
7583
+ returnIntermediateSteps: true,
7584
+ },
7585
+ });
7586
+ const newTokenTotal = tokenizer(directorySummary);
7587
+ return {
7588
+ diffs: directory.diffs,
7589
+ path: directory.path,
7590
+ summary: directorySummary,
7591
+ tokenCount: newTokenTotal,
7592
+ };
7593
+ }
7594
+ catch (error) {
7595
+ console.error(error);
7596
+ return directory;
7597
+ }
7598
+ }
7599
+ const defaultOutputCallback = (group) => {
7600
+ let output = `
7601
+ -------\n* changes in "/${group.path}"\n\n`;
7602
+ if (group.summary) {
7603
+ output += `${group.diffs.map((diff) => ` • ${diff.summary}`).join('\n')}\n\nSummary:\n\n${group.summary}\n\n`;
7604
+ }
7605
+ else {
7606
+ output += `${group.diffs.map((diff) => ` • ${diff.summary}\n\n${diff.diff}`).join('\n\n')}\n\n`;
7607
+ }
7608
+ return output;
7609
+ };
7610
+ async function summarizeDiffs(rootDiffNode, { tokenizer, logger, maxTokens = 2048, textSplitter, chain, handleOutput = defaultOutputCallback, }) {
7611
+ const queue = new pQueue({ concurrency: 8 });
7612
+ logger.startTimer().startSpinner(`Organizing Diffs...`, { color: 'blue' });
7613
+ const directoryDiffs = createDirectoryDiffs(rootDiffNode);
7614
+ // Sort by token count descending
7615
+ directoryDiffs.sort((a, b) => b.tokenCount - a.tokenCount);
7616
+ let totalTokenCount = directoryDiffs.reduce((sum, group) => sum + group.tokenCount, 0);
7617
+ logger.stopSpinner('Diffs Organized').stopTimer();
7618
+ logger.startSpinner(`Consolidating Diffs`, { color: 'blue' });
7619
+ const processingTasks = directoryDiffs.map((group, i) => {
7620
+ return queue.add(async () => {
7621
+ // If the diff token count is already less than the average req, we can skip summarizing.
7622
+ const isLessThanAvgTokenReq = group.tokenCount <= maxTokens / directoryDiffs.length;
7623
+ if (totalTokenCount <= maxTokens || isLessThanAvgTokenReq) {
7624
+ return group;
7625
+ }
7626
+ group = await summarizeDirectoryDiff(group, {
7627
+ chain,
7628
+ textSplitter,
7629
+ tokenizer,
7630
+ });
7631
+ // We need to subtract the old token count and add the new one
7632
+ totalTokenCount = totalTokenCount - directoryDiffs[i].tokenCount + group.tokenCount;
7633
+ directoryDiffs[i] = group;
7634
+ logger
7635
+ .verbose(`\n • Summarized diffs in "/${group.path}" `, { color: 'blue' })
7636
+ .verbose(`\nTotal token count: ${totalTokenCount}`, {
7637
+ color: totalTokenCount > maxTokens ? 'yellow' : 'green',
7638
+ });
7639
+ return group;
7640
+ }, { priority: group.tokenCount });
7641
+ });
7642
+ await Promise.all(processingTasks);
7643
+ logger.stopSpinner(`Summarized Diffs`);
7644
+ return directoryDiffs.map(handleOutput).join('');
7645
+ }
7646
+
7647
+ /**
7648
+ * Asynchronously collect diffs for a given node and its children.
7649
+ */
7650
+ async function collectDiffs(node, getFileDiff, tokenizer, logger) {
7651
+ // Collect diffs for the files of the current node
7652
+ const diffPromises = node.files.map(async (nodeFile) => {
7653
+ const diff = await getFileDiff(nodeFile);
7654
+ const tokenCount = tokenizer(diff);
7655
+ logger.verbose(`Collected diff for ${nodeFile.filePath} (${tokenCount} tokens)`, {
7656
+ color: 'magenta',
7657
+ });
7658
+ return {
7659
+ file: nodeFile.filePath,
7660
+ summary: nodeFile.summary,
7661
+ diff,
7662
+ tokenCount,
7663
+ };
7664
+ });
7665
+ // Collect diffs for the children of the current node
7666
+ const childrenPromises = Array.from(node.children.values()).map(async (child) => collectDiffs(child, getFileDiff, tokenizer, logger));
7667
+ const [diffs, children] = await Promise.all([
7668
+ Promise.all(diffPromises),
7669
+ Promise.all(childrenPromises),
7670
+ ]);
7671
+ return {
7672
+ path: node.getPath(),
7673
+ diffs,
7674
+ children,
7675
+ };
7676
+ }
7677
+
7678
+ class DiffTreeNode {
7679
+ constructor(path) {
7680
+ this.path = [];
7681
+ this.files = [];
7682
+ this.children = new Map();
7683
+ if (path)
7684
+ this.path = path;
7685
+ }
7686
+ addFile(file) {
7687
+ this.files.push(file);
7688
+ }
7689
+ addChild(part, node) {
7690
+ this.children.set(part, node);
7691
+ }
7692
+ getChild(part) {
7693
+ return this.children.get(part);
7694
+ }
7695
+ getPath() {
7696
+ return this.path.join('/');
7697
+ }
7698
+ print(indentation = 0) {
7699
+ const indent = ' '.repeat(indentation);
7700
+ let output = `${indent}- Path: ${this.getPath()}\n`;
7701
+ if (this.files.length > 0) {
7702
+ output += `${indent} Files:\n`;
7703
+ for (const file of this.files) {
7704
+ output += `${indent} - ${file.summary}\n`;
7705
+ }
7706
+ }
7707
+ if (this.children.size > 0) {
7708
+ output += `${indent} Children:\n`;
7709
+ for (const [, child] of this.children) {
7710
+ output += child.print(indentation + 4);
7711
+ }
7712
+ }
7713
+ return output;
7714
+ }
7715
+ }
7716
+ const createDiffTree = (changes) => {
7717
+ const root = new DiffTreeNode();
7718
+ for (const change of changes) {
7719
+ let currentParent = root;
7720
+ const parts = change.filePath.split('/');
7721
+ parts.pop();
7722
+ for (const part of parts) {
7723
+ let childNode = currentParent.getChild(part);
7724
+ if (!childNode) {
7725
+ childNode = new DiffTreeNode([...currentParent.path, part]);
7726
+ currentParent.addChild(part, childNode);
7727
+ }
7728
+ currentParent = childNode;
7729
+ }
7730
+ // Create a NodeFile object and add it to the parent
7731
+ currentParent.addFile({
7732
+ filePath: change.filePath,
7733
+ oldFilePath: change.oldFilePath,
7734
+ summary: change.summary,
7735
+ status: change.status,
7736
+ });
7737
+ }
7738
+ return root;
7739
+ };
7740
+
7741
+ /**
7742
+ * Parses the default file diff for a given nodeFile.
7743
+ *
7744
+ * @param nodeFile - The file change object.
7745
+ * @param commit - The commit to diff against. Defaults to '--staged'.
7746
+ * @param git - The SimpleGit instance.
7747
+ * @returns A Promise that resolves to the file diff as a string.
7748
+ */
7749
+ async function parseDefaultFileDiff(nodeFile, commit = '--staged', git) {
7750
+ if (commit === '--staged') {
7751
+ return await git.diff(['--staged', nodeFile.filePath]);
7752
+ }
7753
+ else if (commit === '--unstaged') {
7754
+ return await git.diff([nodeFile.filePath]);
7755
+ }
7756
+ else if (commit === '--untracked') {
7757
+ // For untracked files, read the file content directly from the filesystem
7758
+ try {
7759
+ const fileContent = await fs.promises.readFile(nodeFile.filePath, 'utf-8');
7760
+ return fileContent;
7761
+ }
7762
+ catch (error) {
7763
+ throw new Error(`Error reading untracked file: ${error?.message || 'Unknown error'}`);
7764
+ }
7765
+ }
7766
+ return await git.diff([commit, nodeFile.filePath]);
7767
+ }
7768
+ /**
7769
+ * Parses the diff for a renamed file.
7770
+ *
7771
+ * @param nodeFile - The file change object.
7772
+ * @param commit - The commit hash or '--staged'.
7773
+ * @param git - The SimpleGit instance.
7774
+ * @param logger - The logger instance.
7775
+ * @returns A Promise that resolves to the diff string.
7776
+ */
7777
+ async function parseRenamedFileDiff(nodeFile, commit, git, logger) {
7778
+ let result = '';
7779
+ const oldFilePath = nodeFile?.oldFilePath || nodeFile.filePath;
7780
+ let previousCommitHash = 'HEAD';
7781
+ let newCommitHash = '';
7782
+ if (commit !== '--staged') {
7783
+ try {
7784
+ previousCommitHash = await git.revparse([`${commit}~1`]);
7785
+ }
7786
+ catch (err) {
7787
+ logger.verbose(`Error getting previous commit hash for ${nodeFile.filePath}`, {
7788
+ color: 'red',
7789
+ });
7790
+ }
7791
+ newCommitHash = commit;
7792
+ }
7793
+ try {
7794
+ const [previousContent, newContent] = await Promise.all([
7795
+ git.show([`${previousCommitHash}:${oldFilePath}`]),
7796
+ git.show([`${newCommitHash}:${nodeFile.filePath}`]),
7797
+ ]);
7798
+ if (previousContent !== newContent) {
7799
+ result = diff.createTwoFilesPatch(oldFilePath, nodeFile.filePath, previousContent, newContent, '', '', {
7800
+ context: 3,
7801
+ });
7802
+ // remove the first 4 lines of the patch (they contain the old and new file names)
7803
+ result = result.split('\n').slice(4).join('\n');
7804
+ }
7805
+ else {
7806
+ result = 'File contents are unchanged.';
7807
+ }
7808
+ }
7809
+ catch (err) {
7810
+ logger.verbose(`Error comparing file contents for ${nodeFile.filePath}`, { color: 'red' });
7811
+ result = 'Error comparing file contents.';
7643
7812
  }
7813
+ return result;
7814
+ }
7815
+ /**
7816
+ * Retrieves the diff for a given file change in a specific commit.
7817
+ * If the file is deleted, it returns a message indicating that the file has been deleted.
7818
+ * If the file is renamed, it parses the renamed file diff and returns it.
7819
+ * Otherwise, it retrieves the default diff from the index and returns it.
7820
+ *
7821
+ * @param nodeFile - The file change object.
7822
+ * @param commit - The commit hash.
7823
+ * @param git - The SimpleGit instance.
7824
+ * @param logger - The logger instance.
7825
+ * @returns A promise that resolves to the diff as a string.
7826
+ */
7827
+ async function getDiff(nodeFile, commit, { git, logger, }) {
7828
+ if (nodeFile.status === 'deleted') {
7829
+ return 'This file has been deleted.';
7830
+ }
7831
+ if (nodeFile.status === 'renamed' && nodeFile.oldFilePath) {
7832
+ const renamedDiff = await parseRenamedFileDiff(nodeFile, commit, git, logger);
7833
+ return renamedDiff;
7834
+ }
7835
+ // If not deleted or renamed, get the diff from the index
7836
+ const defaultDiff = await parseDefaultFileDiff(nodeFile, commit, git);
7837
+ return defaultDiff;
7644
7838
  }
7645
-
7646
- var llm_chain = /*#__PURE__*/Object.freeze({
7647
- __proto__: null,
7648
- LLMChain: LLMChain
7649
- });
7650
7839
 
7651
7840
  /* eslint-disable spaced-comment */
7652
7841
  const API_URL_RAW_PROMPT_TEMPLATE = `You are given the below API Documentation:
@@ -9396,8 +9585,6 @@ const loadSummarizationChain = (llm, params = { type: "map_reduce" }) => {
9396
9585
  throw new Error(`Invalid _type: ${params.type}`);
9397
9586
  };
9398
9587
 
9399
- new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
9400
-
9401
9588
  /*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */
9402
9589
  function isNothing(subject) {
9403
9590
  return (typeof subject === 'undefined') || (subject === null);
@@ -10422,225 +10609,12 @@ for (var i = 0; i < 256; i++) {
10422
10609
  simpleEscapeMap[i] = simpleEscapeSequence(i);
10423
10610
  }
10424
10611
 
10425
- /**
10426
- * Get Summarization Chain
10427
- * @param model
10428
- * @param options
10429
- * @returns
10430
- */
10431
- function getSummarizationChain(model, options = { type: 'map_reduce' }) {
10432
- return loadSummarizationChain(model, options);
10433
- }
10434
-
10435
- /**
10436
- * Get Recursive Character Text Splitter
10437
- *
10438
- * @param options
10439
- * @returns
10440
- */
10441
- function getTextSplitter(options = {}) {
10442
- return new RecursiveCharacterTextSplitter(options);
10443
- }
10444
-
10445
- /**
10446
- * Asynchronously collect diffs for a given node and its children.
10447
- */
10448
- async function collectDiffs(node, getFileDiff, tokenizer, logger) {
10449
- // Collect diffs for the files of the current node
10450
- const diffPromises = node.files.map(async (nodeFile) => {
10451
- const diff = await getFileDiff(nodeFile);
10452
- const tokenCount = tokenizer(diff);
10453
- logger.verbose(`Collected diff for ${nodeFile.filePath} (${tokenCount} tokens)`, {
10454
- color: 'magenta',
10455
- });
10456
- return {
10457
- file: nodeFile.filePath,
10458
- summary: nodeFile.summary,
10459
- diff,
10460
- tokenCount,
10461
- };
10462
- });
10463
- // Collect diffs for the children of the current node
10464
- const childrenPromises = Array.from(node.children.values()).map(async (child) => collectDiffs(child, getFileDiff, tokenizer, logger));
10465
- const [diffs, children] = await Promise.all([
10466
- Promise.all(diffPromises),
10467
- Promise.all(childrenPromises),
10468
- ]);
10469
- return {
10470
- path: node.getPath(),
10471
- diffs,
10472
- children,
10473
- };
10474
- }
10475
-
10476
- class DiffTreeNode {
10477
- constructor(path) {
10478
- this.path = [];
10479
- this.files = [];
10480
- this.children = new Map();
10481
- if (path)
10482
- this.path = path;
10483
- }
10484
- addFile(file) {
10485
- this.files.push(file);
10486
- }
10487
- addChild(part, node) {
10488
- this.children.set(part, node);
10489
- }
10490
- getChild(part) {
10491
- return this.children.get(part);
10492
- }
10493
- getPath() {
10494
- return this.path.join('/');
10495
- }
10496
- print(indentation = 0) {
10497
- const indent = ' '.repeat(indentation);
10498
- let output = `${indent}- Path: ${this.getPath()}\n`;
10499
- if (this.files.length > 0) {
10500
- output += `${indent} Files:\n`;
10501
- for (const file of this.files) {
10502
- output += `${indent} - ${file.summary}\n`;
10503
- }
10504
- }
10505
- if (this.children.size > 0) {
10506
- output += `${indent} Children:\n`;
10507
- for (const [, child] of this.children) {
10508
- output += child.print(indentation + 4);
10509
- }
10510
- }
10511
- return output;
10512
- }
10513
- }
10514
- const createDiffTree = (changes) => {
10515
- const root = new DiffTreeNode();
10516
- for (const change of changes) {
10517
- let currentParent = root;
10518
- const parts = change.filePath.split('/');
10519
- parts.pop();
10520
- for (const part of parts) {
10521
- let childNode = currentParent.getChild(part);
10522
- if (!childNode) {
10523
- childNode = new DiffTreeNode([...currentParent.path, part]);
10524
- currentParent.addChild(part, childNode);
10525
- }
10526
- currentParent = childNode;
10527
- }
10528
- // Create a NodeFile object and add it to the parent
10529
- currentParent.addFile({
10530
- filePath: change.filePath,
10531
- oldFilePath: change.oldFilePath,
10532
- summary: change.summary,
10533
- status: change.status,
10534
- });
10535
- }
10536
- return root;
10537
- };
10538
-
10539
- /**
10540
- * Parses the default file diff for a given nodeFile.
10541
- *
10542
- * @param nodeFile - The file change object.
10543
- * @param commit - The commit to diff against. Defaults to '--staged'.
10544
- * @param git - The SimpleGit instance.
10545
- * @returns A Promise that resolves to the file diff as a string.
10546
- */
10547
- async function parseDefaultFileDiff(nodeFile, commit = '--staged', git) {
10548
- if (commit === '--staged') {
10549
- return await git.diff(['--staged', nodeFile.filePath]);
10550
- }
10551
- else if (commit === '--unstaged') {
10552
- return await git.diff([nodeFile.filePath]);
10553
- }
10554
- else if (commit === '--untracked') {
10555
- // For untracked files, read the file content directly from the filesystem
10556
- try {
10557
- const fileContent = await fs.promises.readFile(nodeFile.filePath, 'utf-8');
10558
- return fileContent;
10559
- }
10560
- catch (error) {
10561
- throw new Error(`Error reading untracked file: ${error?.message || 'Unknown error'}`);
10562
- }
10563
- }
10564
- return await git.diff([commit, nodeFile.filePath]);
10565
- }
10566
- /**
10567
- * Parses the diff for a renamed file.
10568
- *
10569
- * @param nodeFile - The file change object.
10570
- * @param commit - The commit hash or '--staged'.
10571
- * @param git - The SimpleGit instance.
10572
- * @param logger - The logger instance.
10573
- * @returns A Promise that resolves to the diff string.
10574
- */
10575
- async function parseRenamedFileDiff(nodeFile, commit, git, logger) {
10576
- let result = '';
10577
- const oldFilePath = nodeFile?.oldFilePath || nodeFile.filePath;
10578
- let previousCommitHash = 'HEAD';
10579
- let newCommitHash = '';
10580
- if (commit !== '--staged') {
10581
- try {
10582
- previousCommitHash = await git.revparse([`${commit}~1`]);
10583
- }
10584
- catch (err) {
10585
- logger.verbose(`Error getting previous commit hash for ${nodeFile.filePath}`, {
10586
- color: 'red',
10587
- });
10588
- }
10589
- newCommitHash = commit;
10590
- }
10591
- try {
10592
- const [previousContent, newContent] = await Promise.all([
10593
- git.show([`${previousCommitHash}:${oldFilePath}`]),
10594
- git.show([`${newCommitHash}:${nodeFile.filePath}`]),
10595
- ]);
10596
- if (previousContent !== newContent) {
10597
- result = diff.createTwoFilesPatch(oldFilePath, nodeFile.filePath, previousContent, newContent, '', '', {
10598
- context: 3,
10599
- });
10600
- // remove the first 4 lines of the patch (they contain the old and new file names)
10601
- result = result.split('\n').slice(4).join('\n');
10602
- }
10603
- else {
10604
- result = 'File contents are unchanged.';
10605
- }
10606
- }
10607
- catch (err) {
10608
- logger.verbose(`Error comparing file contents for ${nodeFile.filePath}`, { color: 'red' });
10609
- result = 'Error comparing file contents.';
10610
- }
10611
- return result;
10612
- }
10613
- /**
10614
- * Retrieves the diff for a given file change in a specific commit.
10615
- * If the file is deleted, it returns a message indicating that the file has been deleted.
10616
- * If the file is renamed, it parses the renamed file diff and returns it.
10617
- * Otherwise, it retrieves the default diff from the index and returns it.
10618
- *
10619
- * @param nodeFile - The file change object.
10620
- * @param commit - The commit hash.
10621
- * @param git - The SimpleGit instance.
10622
- * @param logger - The logger instance.
10623
- * @returns A promise that resolves to the diff as a string.
10624
- */
10625
- async function getDiff(nodeFile, commit, { git, logger, }) {
10626
- if (nodeFile.status === 'deleted') {
10627
- return 'This file has been deleted.';
10628
- }
10629
- if (nodeFile.status === 'renamed' && nodeFile.oldFilePath) {
10630
- const renamedDiff = await parseRenamedFileDiff(nodeFile, commit, git, logger);
10631
- return renamedDiff;
10632
- }
10633
- // If not deleted or renamed, get the diff from the index
10634
- const defaultDiff = await parseDefaultFileDiff(nodeFile, commit, git);
10635
- return defaultDiff;
10636
- }
10637
-
10638
10612
  // Max tokens for GPT-3 is 4096
10639
10613
  // const MAX_TOKENS_PER_SUMMARY = 4096
10640
10614
  const MAX_TOKENS_PER_SUMMARY = 12288;
10641
10615
  async function fileChangeParser({ changes, commit, options: { tokenizer, git, llm: model, logger }, }) {
10642
- const textSplitter = getTextSplitter({ chunkSize: 10000, chunkOverlap: 250 });
10643
- const summarizationChain = getSummarizationChain(model, {
10616
+ const textSplitter = new RecursiveCharacterTextSplitter({ chunkSize: 10000, chunkOverlap: 250 });
10617
+ const summarizationChain = loadSummarizationChain(model, {
10644
10618
  type: 'map_reduce',
10645
10619
  combineMapPrompt: SUMMARIZE_PROMPT,
10646
10620
  combinePrompt: SUMMARIZE_PROMPT,
@@ -10911,7 +10885,9 @@ const handler$3 = async (argv, logger) => {
10911
10885
  const llm = getLlm(provider, model, config);
10912
10886
  const INTERACTIVE = argv.interactive || isInteractive(config);
10913
10887
  if (INTERACTIVE) {
10914
- logger.log(LOGO);
10888
+ if (!config.hideCocoBanner) {
10889
+ logger.log(LOGO);
10890
+ }
10915
10891
  }
10916
10892
  else {
10917
10893
  logger.setConfig({ silent: true });
@@ -10962,7 +10938,8 @@ const handler$3 = async (argv, logger) => {
10962
10938
  const schema = useConventional
10963
10939
  ? ConventionalCommitMessageResponseSchema
10964
10940
  : CommitMessageResponseSchema;
10965
- const parser = new output_parsers.StructuredOutputParser(schema);
10941
+ const formatInstructions = `You must always return valid JSON fenced by a markdown code block. Do not return any additional text. The JSON object you return should match the following schema:
10942
+ {{ body: string, title: string }}`;
10966
10943
  // Use conventional commit prompt if enabled
10967
10944
  const promptTemplate = useConventional ? CONVENTIONAL_COMMIT_PROMPT : COMMIT_PROMPT;
10968
10945
  const prompt = getPrompt({
@@ -10970,7 +10947,11 @@ const handler$3 = async (argv, logger) => {
10970
10947
  variables: promptTemplate.inputVariables,
10971
10948
  fallback: promptTemplate,
10972
10949
  });
10973
- const formatInstructions = "Respond with a valid JSON object, containing two fields: 'title' and 'body', both strings.";
10950
+ if (config.service.provider === 'ollama') {
10951
+ logger.log('Note: Ollama models may not strictly adhere to the output format instructions.', {
10952
+ color: 'yellow',
10953
+ });
10954
+ }
10974
10955
  // Get additional context if provided
10975
10956
  let additional_context = '';
10976
10957
  if (argv.additional) {
@@ -11003,11 +10984,25 @@ const handler$3 = async (argv, logger) => {
11003
10984
  commit_history: commit_history,
11004
10985
  branch_name_context: branchNameContext,
11005
10986
  };
11006
- const commitMsg = await executeChain({
11007
- llm,
11008
- prompt,
11009
- variables,
11010
- parser,
10987
+ const maxAttempts = config.service.provider === 'ollama' && 'maxParsingAttempts' in config.service
10988
+ ? config.service.maxParsingAttempts || 3
10989
+ : 3;
10990
+ const commitMsg = await executeChainWithSchema(schema, llm, prompt, variables, {
10991
+ retryOptions: {
10992
+ maxAttempts,
10993
+ onRetry: (attempt, error) => {
10994
+ logger.verbose(`Failed to parse commit message (attempt ${attempt}/${maxAttempts}): ${error.message}`, { color: 'yellow' });
10995
+ }
10996
+ },
10997
+ fallbackParser: (text) => ({
10998
+ title: text.split('\n')[0] || 'Auto-generated commit',
10999
+ body: text.split('\n').slice(1).join('\n') || 'Generated commit message',
11000
+ }),
11001
+ onFallback: () => {
11002
+ logger.verbose('Max retry attempts reached. Falling back to simple text output.', {
11003
+ color: 'red',
11004
+ });
11005
+ },
11011
11006
  });
11012
11007
  // Construct the full commit message
11013
11008
  const appendedText = argv.append ? `\n\n${argv.append}` : '';
@@ -11225,12 +11220,15 @@ const OPEN_AI_MODELS = [
11225
11220
  'gpt-3.5-turbo',
11226
11221
  ];
11227
11222
  const ANTHROPIC_MODELS = [
11223
+ 'claude-sonnet-4-0',
11224
+ 'claude-3-7-sonnet-latest',
11225
+ 'claude-3-5-haiku-latest',
11226
+ 'claude-3-5-sonnet-latest',
11227
+ 'claude-3-5-sonnet-20241022',
11228
11228
  'claude-3-5-sonnet-20240620',
11229
11229
  'claude-3-opus-20240229',
11230
11230
  'claude-3-sonnet-20240229',
11231
11231
  'claude-3-haiku-20240307',
11232
- 'claude-2.1',
11233
- 'claude-2.0',
11234
11232
  ];
11235
11233
 
11236
11234
  const questions = {
@@ -11522,9 +11520,9 @@ var init = {
11522
11520
  options: options$2,
11523
11521
  };
11524
11522
 
11525
- const RecapLlmResponseSchema = z.object({
11526
- title: z.string().optional(),
11527
- summary: z.string().optional(),
11523
+ const RecapLlmResponseSchema = objectType({
11524
+ title: stringType().optional(),
11525
+ summary: stringType().optional(),
11528
11526
  });
11529
11527
  const command$1 = 'recap';
11530
11528
  /**
@@ -11598,7 +11596,9 @@ const handler$1 = async (argv, logger) => {
11598
11596
  const llm = getLlm(provider, model, config);
11599
11597
  const INTERACTIVE = argv.interactive || isInteractive(config);
11600
11598
  if (INTERACTIVE) {
11601
- logger.log(LOGO);
11599
+ if (!config.hideCocoBanner) {
11600
+ logger.log(LOGO);
11601
+ }
11602
11602
  }
11603
11603
  else {
11604
11604
  logger.setConfig({ silent: true });
@@ -11747,26 +11747,26 @@ var recap = {
11747
11747
  options: options$1,
11748
11748
  };
11749
11749
 
11750
- const ReviewFeedbackItemSchema = z.object({
11751
- title: z.string(),
11752
- summary: z.string(),
11753
- severity: z.union([
11754
- z.literal(1),
11755
- z.literal(2),
11756
- z.literal(3),
11757
- z.literal(4),
11758
- z.literal(5),
11759
- z.literal(6),
11760
- z.literal(7),
11761
- z.literal(8),
11762
- z.literal(9),
11763
- z.literal(10),
11750
+ const ReviewFeedbackItemSchema = objectType({
11751
+ title: stringType(),
11752
+ summary: stringType(),
11753
+ severity: unionType([
11754
+ literalType(1),
11755
+ literalType(2),
11756
+ literalType(3),
11757
+ literalType(4),
11758
+ literalType(5),
11759
+ literalType(6),
11760
+ literalType(7),
11761
+ literalType(8),
11762
+ literalType(9),
11763
+ literalType(10),
11764
11764
  ]),
11765
- category: z.string(),
11766
- filePath: z.string(),
11765
+ category: stringType(),
11766
+ filePath: stringType(),
11767
11767
  });
11768
11768
  // Array schema for review feedback items
11769
- const ReviewFeedbackItemArraySchema = z.array(ReviewFeedbackItemSchema);
11769
+ const ReviewFeedbackItemArraySchema = arrayType(ReviewFeedbackItemSchema);
11770
11770
  const command = 'review';
11771
11771
  /**
11772
11772
  * Command line options via yargs
@@ -14036,7 +14036,9 @@ const handler = async (argv, logger) => {
14036
14036
  const llm = getLlm(provider, model, config);
14037
14037
  const INTERACTIVE = isInteractive(config);
14038
14038
  if (INTERACTIVE) {
14039
- logger.log(LOGO);
14039
+ if (!config.hideCocoBanner) {
14040
+ logger.log(LOGO);
14041
+ }
14040
14042
  }
14041
14043
  async function factory() {
14042
14044
  if (argv.branch) {