@railway-ts/pipelines 0.1.20 → 0.1.22

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.
@@ -171,6 +171,12 @@ declare function emptyAsOptional<I, O>(validator: MaybeAsyncValidator<I, O>): Ma
171
171
  */
172
172
  declare function literal<T>(expectedValue: T, message?: string): Validator<unknown, T>;
173
173
 
174
+ /**
175
+ * Options for controlling validation behavior.
176
+ */
177
+ type ValidateOptions = {
178
+ abortEarly?: boolean;
179
+ };
174
180
  /**
175
181
  * The key used in formatted error objects for root-level validation errors (i.e. errors with an empty path).
176
182
  */
@@ -222,15 +228,24 @@ declare function chainAsync<A, B, C, D, E, F, G, H, I, J, K>(v1: MaybeAsyncValid
222
228
  * const result = validate(10, chain(number(), min(5)));
223
229
  * // ok(10)
224
230
  *
231
+ * @example
232
+ * // With abortEarly option — stops on first error
233
+ * const result = validate(input, userSchema, { abortEarly: true });
234
+ *
225
235
  * @param value - The value to validate
226
236
  * @param validator - The validator to apply
227
- * @param path - Optional base path for error reporting
237
+ * @param pathOrOptions - Optional base path for error reporting, or options object
238
+ * @param maybeOptions - Options object when path is also provided
228
239
  * @returns A Result containing either the validated value or validation errors
229
240
  */
230
241
  declare function validate<T>(value: unknown, validator: Validator<unknown, T>): Result<T, ValidationError[]>;
231
242
  declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[]): Result<T, ValidationError[]>;
243
+ declare function validate<T>(value: unknown, validator: Validator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]>;
244
+ declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]>;
232
245
  declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
233
246
  declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[]): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
247
+ declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
248
+ declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
234
249
  /**
235
250
  * Format validation errors into a user-friendly object.
236
251
  * Converts array paths to dot/bracket notation strings.
@@ -259,8 +274,8 @@ declare function formatErrors(errors: ValidationError[]): Record<string, string>
259
274
  * @param schema - The validator/schema to validate against
260
275
  * @returns An object with either `{ valid: true, data }` or `{ valid: false, errors }`
261
276
  */
262
- declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>): ValidationResult<T>;
263
- declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>): ValidationResult<T> | Promise<ValidationResult<T>>;
277
+ declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>, options?: ValidateOptions): ValidationResult<T>;
278
+ declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>, options?: ValidateOptions): ValidationResult<T> | Promise<ValidationResult<T>>;
264
279
  /**
265
280
  * Create a validator that transforms a value during validation.
266
281
  * The transformer function must be pure and not throw exceptions.
@@ -701,6 +716,18 @@ declare function nonEmpty(message?: string): Validator<string>;
701
716
  * @returns A validator that checks if a string is a valid email
702
717
  */
703
718
  declare function email(message?: string): Validator<string>;
719
+ /**
720
+ * Create a validator that ensures a string is a valid URL.
721
+ *
722
+ * @example
723
+ * const validate = url();
724
+ * validate('https://example.com'); // ok("https://example.com")
725
+ * validate('not-a-url'); // err([{ path: [], message: 'Invalid URL format' }])
726
+ *
727
+ * @param message - Custom error message
728
+ * @returns A validator that checks if a string is a valid URL
729
+ */
730
+ declare function url(message?: string): Validator<string>;
704
731
  /**
705
732
  * Create a validator that ensures a string is a valid phone number.
706
733
  * Accepts common formats including international (+), spaces, dashes, and parentheses.
@@ -1116,4 +1143,4 @@ declare namespace StandardSchemaV1 {
1116
1143
  declare function toStandardSchema<O>(validator: Validator<unknown, O>): StandardSchemaV1<unknown, O>;
1117
1144
  declare function toStandardSchema<O>(validator: MaybeAsyncValidator<unknown, O>): StandardSchemaV1<unknown, O>;
1118
1145
 
1119
- export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, refineAsync, refineAt, refineAtAsync, required, string, stringEnum, toStandardSchema, todayOrFuture, transform, tuple, tupleOf, union, unique, validate, validateAndFormatResult };
1146
+ export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidateOptions, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, refineAsync, refineAt, refineAtAsync, required, string, stringEnum, toStandardSchema, todayOrFuture, transform, tuple, tupleOf, union, unique, url, validate, validateAndFormatResult };
@@ -171,6 +171,12 @@ declare function emptyAsOptional<I, O>(validator: MaybeAsyncValidator<I, O>): Ma
171
171
  */
172
172
  declare function literal<T>(expectedValue: T, message?: string): Validator<unknown, T>;
173
173
 
174
+ /**
175
+ * Options for controlling validation behavior.
176
+ */
177
+ type ValidateOptions = {
178
+ abortEarly?: boolean;
179
+ };
174
180
  /**
175
181
  * The key used in formatted error objects for root-level validation errors (i.e. errors with an empty path).
176
182
  */
@@ -222,15 +228,24 @@ declare function chainAsync<A, B, C, D, E, F, G, H, I, J, K>(v1: MaybeAsyncValid
222
228
  * const result = validate(10, chain(number(), min(5)));
223
229
  * // ok(10)
224
230
  *
231
+ * @example
232
+ * // With abortEarly option — stops on first error
233
+ * const result = validate(input, userSchema, { abortEarly: true });
234
+ *
225
235
  * @param value - The value to validate
226
236
  * @param validator - The validator to apply
227
- * @param path - Optional base path for error reporting
237
+ * @param pathOrOptions - Optional base path for error reporting, or options object
238
+ * @param maybeOptions - Options object when path is also provided
228
239
  * @returns A Result containing either the validated value or validation errors
229
240
  */
230
241
  declare function validate<T>(value: unknown, validator: Validator<unknown, T>): Result<T, ValidationError[]>;
231
242
  declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[]): Result<T, ValidationError[]>;
243
+ declare function validate<T>(value: unknown, validator: Validator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]>;
244
+ declare function validate<T>(value: unknown, validator: Validator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]>;
232
245
  declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
233
246
  declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[]): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
247
+ declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
248
+ declare function validate<T>(value: unknown, validator: MaybeAsyncValidator<unknown, T>, path: string[], options: ValidateOptions): Result<T, ValidationError[]> | Promise<Result<T, ValidationError[]>>;
234
249
  /**
235
250
  * Format validation errors into a user-friendly object.
236
251
  * Converts array paths to dot/bracket notation strings.
@@ -259,8 +274,8 @@ declare function formatErrors(errors: ValidationError[]): Record<string, string>
259
274
  * @param schema - The validator/schema to validate against
260
275
  * @returns An object with either `{ valid: true, data }` or `{ valid: false, errors }`
261
276
  */
262
- declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>): ValidationResult<T>;
263
- declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>): ValidationResult<T> | Promise<ValidationResult<T>>;
277
+ declare function validateAndFormatResult<T>(input: unknown, schema: Validator<unknown, T>, options?: ValidateOptions): ValidationResult<T>;
278
+ declare function validateAndFormatResult<T>(input: unknown, schema: MaybeAsyncValidator<unknown, T>, options?: ValidateOptions): ValidationResult<T> | Promise<ValidationResult<T>>;
264
279
  /**
265
280
  * Create a validator that transforms a value during validation.
266
281
  * The transformer function must be pure and not throw exceptions.
@@ -701,6 +716,18 @@ declare function nonEmpty(message?: string): Validator<string>;
701
716
  * @returns A validator that checks if a string is a valid email
702
717
  */
703
718
  declare function email(message?: string): Validator<string>;
719
+ /**
720
+ * Create a validator that ensures a string is a valid URL.
721
+ *
722
+ * @example
723
+ * const validate = url();
724
+ * validate('https://example.com'); // ok("https://example.com")
725
+ * validate('not-a-url'); // err([{ path: [], message: 'Invalid URL format' }])
726
+ *
727
+ * @param message - Custom error message
728
+ * @returns A validator that checks if a string is a valid URL
729
+ */
730
+ declare function url(message?: string): Validator<string>;
704
731
  /**
705
732
  * Create a validator that ensures a string is a valid phone number.
706
733
  * Accepts common formats including international (+), spaces, dashes, and parentheses.
@@ -1116,4 +1143,4 @@ declare namespace StandardSchemaV1 {
1116
1143
  declare function toStandardSchema<O>(validator: Validator<unknown, O>): StandardSchemaV1<unknown, O>;
1117
1144
  declare function toStandardSchema<O>(validator: MaybeAsyncValidator<unknown, O>): StandardSchemaV1<unknown, O>;
1118
1145
 
1119
- export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, refineAsync, refineAt, refineAtAsync, required, string, stringEnum, toStandardSchema, todayOrFuture, transform, tuple, tupleOf, union, unique, validate, validateAndFormatResult };
1146
+ export { type AsyncValidator, type InferSchemaType, type MaybeAsyncValidator, ROOT_ERROR_KEY, type Schema, StandardSchemaV1, type SyncSchema, type ValidateOptions, type ValidationError, type ValidationResult, type Validator, type ValidatorMapOutput, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, refineAsync, refineAt, refineAtAsync, required, string, stringEnum, toStandardSchema, todayOrFuture, transform, tuple, tupleOf, union, unique, url, validate, validateAndFormatResult };
@@ -37,16 +37,33 @@ function fromTry(f) {
37
37
  }
38
38
 
39
39
  // src/schema/core.ts
40
+ var _abortEarly = false;
41
+ function _getAbortEarly() {
42
+ return _abortEarly;
43
+ }
44
+ function _withAbortEarly(enabled, fn) {
45
+ const prev = _abortEarly;
46
+ _abortEarly = enabled;
47
+ try {
48
+ return fn();
49
+ } finally {
50
+ _abortEarly = prev;
51
+ }
52
+ }
40
53
  function object(schema, { strict = true } = {}) {
41
54
  return (obj, parentPath = []) => {
42
55
  if (obj === null || typeof obj !== "object") {
43
56
  return err([{ path: parentPath, message: "Expected an object" }]);
44
57
  }
58
+ const abortEarly = _getAbortEarly();
45
59
  const allErrors = [];
46
60
  const validatedObj = {};
47
61
  if (strict !== false) {
48
62
  const extraKeys = Object.keys(obj).filter((key) => !Object.prototype.hasOwnProperty.call(schema, key));
49
63
  if (extraKeys.length > 0) {
64
+ if (abortEarly) {
65
+ return err([{ path: [...parentPath, extraKeys[0]], message: `Unexpected field: '${extraKeys[0]}'` }]);
66
+ }
50
67
  for (const key of extraKeys) {
51
68
  allErrors.push({
52
69
  path: [...parentPath, key],
@@ -55,15 +72,18 @@ function object(schema, { strict = true } = {}) {
55
72
  }
56
73
  }
57
74
  }
75
+ if (abortEarly && allErrors.length > 0) return err(allErrors);
58
76
  const pendingResults = [];
59
77
  for (const key in schema) {
60
78
  if (!Object.prototype.hasOwnProperty.call(schema, key)) continue;
61
79
  const validator = schema[key];
62
80
  if (!validator) continue;
81
+ if (abortEarly && allErrors.length > 0) break;
63
82
  const value = obj[key];
64
83
  const fieldPath = [...parentPath, key];
65
84
  const result = validator(value, fieldPath);
66
85
  if (result instanceof Promise) {
86
+ if (abortEarly && allErrors.length > 0) continue;
67
87
  pendingResults.push(
68
88
  result.then((r) => {
69
89
  if (isOk(r)) {
@@ -77,6 +97,7 @@ function object(schema, { strict = true } = {}) {
77
97
  validatedObj[key] = result.value;
78
98
  } else {
79
99
  allErrors.push(...result.error);
100
+ if (abortEarly) break;
80
101
  }
81
102
  }
82
103
  if (pendingResults.length > 0) {
@@ -154,7 +175,12 @@ function chainAsync(...validators) {
154
175
  return ok(current);
155
176
  };
156
177
  }
157
- function validate(value, validator, path = []) {
178
+ function validate(value, validator, pathOrOptions = [], maybeOptions) {
179
+ const path = Array.isArray(pathOrOptions) ? pathOrOptions : [];
180
+ const options = Array.isArray(pathOrOptions) ? maybeOptions : pathOrOptions;
181
+ if (options?.abortEarly) {
182
+ return _withAbortEarly(true, () => validator(value, path));
183
+ }
158
184
  return validator(value, path);
159
185
  }
160
186
  function formatErrors(errors) {
@@ -173,20 +199,26 @@ function formatErrors(errors) {
173
199
  {}
174
200
  );
175
201
  }
176
- function validateAndFormatResult(input, schema) {
177
- const result = schema(input);
178
- if (result instanceof Promise) {
179
- return result.then(
180
- (r) => match(r, {
181
- ok: (data) => ({ valid: true, data }),
182
- err: (errors) => ({ valid: false, errors: formatErrors(errors) })
183
- })
184
- );
202
+ function validateAndFormatResult(input, schema, options) {
203
+ const run = () => {
204
+ const result = schema(input);
205
+ if (result instanceof Promise) {
206
+ return result.then(
207
+ (r) => match(r, {
208
+ ok: (data) => ({ valid: true, data }),
209
+ err: (errors) => ({ valid: false, errors: formatErrors(errors) })
210
+ })
211
+ );
212
+ }
213
+ return match(result, {
214
+ ok: (data) => ({ valid: true, data }),
215
+ err: (errors) => ({ valid: false, errors: formatErrors(errors) })
216
+ });
217
+ };
218
+ if (options?.abortEarly) {
219
+ return _withAbortEarly(true, run);
185
220
  }
186
- return match(result, {
187
- ok: (data) => ({ valid: true, data }),
188
- err: (errors) => ({ valid: false, errors: formatErrors(errors) })
189
- });
221
+ return run();
190
222
  }
191
223
  function transform(transformer) {
192
224
  return (value) => ok(transformer(value));
@@ -271,6 +303,16 @@ function email(message = "Invalid email format") {
271
303
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
272
304
  return pattern(emailRegex, message);
273
305
  }
306
+ function url(message = "Invalid URL format") {
307
+ return (value, path = []) => {
308
+ try {
309
+ new URL(value);
310
+ return ok(value);
311
+ } catch {
312
+ return err([{ path, message }]);
313
+ }
314
+ };
315
+ }
274
316
  function phoneNumber(message = "Invalid phone number format") {
275
317
  const phoneRegex = /^\+?[\d\s\-()]{8,20}$/;
276
318
  return (value, path = []) => {
@@ -288,13 +330,16 @@ function array(itemValidator) {
288
330
  if (!Array.isArray(value)) {
289
331
  return err([{ path: parentPath, message: "Expected an array" }]);
290
332
  }
333
+ const abortEarly = _getAbortEarly();
291
334
  const allErrors = [];
292
335
  const validatedItems = Array.from({ length: value.length });
293
336
  const pendingResults = [];
294
337
  for (const [i, item] of value.entries()) {
338
+ if (abortEarly && allErrors.length > 0) break;
295
339
  const itemPath = [...parentPath, i.toString()];
296
340
  const result = itemValidator(item, itemPath);
297
341
  if (result instanceof Promise) {
342
+ if (abortEarly && allErrors.length > 0) continue;
298
343
  const index = i;
299
344
  pendingResults.push(
300
345
  result.then((r) => {
@@ -309,6 +354,7 @@ function array(itemValidator) {
309
354
  validatedItems[i] = result.value;
310
355
  } else {
311
356
  allErrors.push(...result.error);
357
+ if (abortEarly) break;
312
358
  }
313
359
  }
314
360
  if (pendingResults.length > 0) {
@@ -389,14 +435,17 @@ function tuple(validators) {
389
435
  }
390
436
  ]);
391
437
  }
438
+ const abortEarly = _getAbortEarly();
392
439
  const allErrors = [];
393
440
  const validatedItems = Array.from({ length: validators.length });
394
441
  const pendingResults = [];
395
442
  for (const [i, validator] of validators.entries()) {
443
+ if (abortEarly && allErrors.length > 0) break;
396
444
  const itemPath = [...parentPath, i.toString()];
397
445
  const item = value.at(i);
398
446
  const result = validator(item, itemPath);
399
447
  if (result instanceof Promise) {
448
+ if (abortEarly && allErrors.length > 0) continue;
400
449
  const index = i;
401
450
  pendingResults.push(
402
451
  result.then((r) => {
@@ -411,6 +460,7 @@ function tuple(validators) {
411
460
  validatedItems[i] = result.value;
412
461
  } else {
413
462
  allErrors.push(...result.error);
463
+ if (abortEarly) break;
414
464
  }
415
465
  }
416
466
  if (pendingResults.length > 0) {
@@ -436,13 +486,16 @@ function tupleOf(elementValidator, length) {
436
486
  }
437
487
  ]);
438
488
  }
489
+ const abortEarly = _getAbortEarly();
439
490
  const allErrors = [];
440
491
  const validatedItems = Array.from({ length });
441
492
  const pendingResults = [];
442
493
  for (const [i, item] of value.entries()) {
494
+ if (abortEarly && allErrors.length > 0) break;
443
495
  const itemPath = [...parentPath, i.toString()];
444
496
  const result = elementValidator(item, itemPath);
445
497
  if (result instanceof Promise) {
498
+ if (abortEarly && allErrors.length > 0) continue;
446
499
  const index = i;
447
500
  pendingResults.push(
448
501
  result.then((r) => {
@@ -457,6 +510,7 @@ function tupleOf(elementValidator, length) {
457
510
  validatedItems[i] = result.value;
458
511
  } else {
459
512
  allErrors.push(...result.error);
513
+ if (abortEarly) break;
460
514
  }
461
515
  }
462
516
  if (pendingResults.length > 0) {
@@ -933,6 +987,6 @@ function toStandardSchema(validator) {
933
987
  };
934
988
  }
935
989
 
936
- export { ROOT_ERROR_KEY, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, refineAsync, refineAt, refineAtAsync, required, string, stringEnum, toStandardSchema, todayOrFuture, transform, tuple, tupleOf, union, unique, validate, validateAndFormatResult };
990
+ export { ROOT_ERROR_KEY, _getAbortEarly, _withAbortEarly, array, between, bigint, boolean, chain, chainAsync, date, dateRange, discriminatedUnion, divisibleBy, email, emptyAsOptional, enumValue, finite, formatErrors, futureDate, integer, literal, matches, max, maxItems, maxLength, min, minItems, minLength, negative, nonEmpty, nonZero, notEmpty, nullable, number, object, oneOf, optional, parseBigInt, parseBool, parseDate, parseEnum, parseISODate, parseJSON, parseNumber, parseString, parseURL, pastDate, pattern, phoneNumber, positive, precision, refine, refineAsync, refineAt, refineAtAsync, required, string, stringEnum, toStandardSchema, todayOrFuture, transform, tuple, tupleOf, union, unique, url, validate, validateAndFormatResult };
937
991
  //# sourceMappingURL=index.mjs.map
938
992
  //# sourceMappingURL=index.mjs.map