@railway-ts/pipelines 0.1.19 → 0.1.20

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.
@@ -0,0 +1,890 @@
1
+ # Recipes
2
+
3
+ Patterns and techniques. Each recipe is self-contained.
4
+
5
+ ---
6
+
7
+ ## Point-Free Composition
8
+
9
+ Eliminate wrapper lambdas in pipelines with curried helpers. Exported from both `result` and `option` modules.
10
+
11
+ ### The Problem
12
+
13
+ ```typescript
14
+ // Ugly: repetitive wrapper lambdas
15
+ const result = pipe(
16
+ ok(5),
17
+ (r) => map(r, (x) => x * 2),
18
+ (r) => map(r, (x) => x + 1),
19
+ (r) => flatMap(r, (x) => divide(x, 3)),
20
+ );
21
+ ```
22
+
23
+ ### The Solution
24
+
25
+ ```typescript
26
+ // Clean: point-free composition
27
+ const result = pipe(
28
+ ok(5),
29
+ mapWith((x) => x * 2),
30
+ mapWith((x) => x + 1),
31
+ flatMapWith((x) => divide(x, 3)),
32
+ );
33
+ ```
34
+
35
+ ### Result Helpers
36
+
37
+ ```typescript
38
+ import { mapWith, flatMapWith, mapErrWith, filterWith, tapWith, tapErrWith } from '@railway-ts/pipelines/result';
39
+ ```
40
+
41
+ ### Option Helpers
42
+
43
+ ```typescript
44
+ import { mapWith, flatMapWith, filterWith, tapWith, mapToResultWith } from '@railway-ts/pipelines/option';
45
+ ```
46
+
47
+ ### Usage
48
+
49
+ ```typescript
50
+ import { flow } from '@railway-ts/pipelines/composition';
51
+ import { mapWith, flatMapWith, tapWith } from '@railway-ts/pipelines/result';
52
+ import { validate } from '@railway-ts/pipelines/schema';
53
+
54
+ const processData = flow(
55
+ (input: unknown) => validate(input, schema),
56
+ mapWith(transformData),
57
+ flatMapWith(validateBusinessRules),
58
+ tapWith((data) => console.log('Processing:', data)),
59
+ mapWith(enrichData),
60
+ );
61
+ ```
62
+
63
+ ---
64
+
65
+ ## Async Pipelines
66
+
67
+ ### Sequential Steps
68
+
69
+ ```typescript
70
+ import { flatMapWith } from '@railway-ts/pipelines/result';
71
+ import { pipeAsync } from '@railway-ts/pipelines/composition';
72
+
73
+ const processOrder = async (input: unknown) => {
74
+ const result = await pipeAsync(
75
+ validate(input, orderSchema),
76
+ flatMapWith(validateInventory),
77
+ flatMapWith(chargePayment),
78
+ flatMapWith(createShipment),
79
+ );
80
+
81
+ return match(result, {
82
+ ok: (order) => ({ success: true, order }),
83
+ err: (error) => ({ success: false, error }),
84
+ });
85
+ };
86
+ ```
87
+
88
+ ### Parallel Execution in Object Schemas
89
+
90
+ When an `object()` schema contains async validators, all fields are validated concurrently using `Promise.all`. This means three async field validators that each take 50ms finish in ~50ms total, not 150ms:
91
+
92
+ ```typescript
93
+ import { object, required, chainAsync, string, refineAsync, validate } from '@railway-ts/pipelines/schema';
94
+
95
+ const signupSchema = object({
96
+ email: required(
97
+ chainAsync(
98
+ string(),
99
+ refineAsync(async (email) => {
100
+ return !(await isEmailTaken(email)); // ~50ms
101
+ }, 'Email already in use'),
102
+ ),
103
+ ),
104
+ username: required(
105
+ chainAsync(
106
+ string(),
107
+ refineAsync(async (name) => {
108
+ return !(await isUsernameTaken(name)); // ~50ms
109
+ }, 'Username taken'),
110
+ ),
111
+ ),
112
+ invite: required(
113
+ chainAsync(
114
+ string(),
115
+ refineAsync(async (code) => {
116
+ return await isValidInvite(code); // ~50ms
117
+ }, 'Invalid invite code'),
118
+ ),
119
+ ),
120
+ });
121
+
122
+ // All three checks run in parallel: ~50ms total, not ~150ms
123
+ const result = await validate(input, signupSchema);
124
+ ```
125
+
126
+ This applies to `object()`, `tuple()`, and `tupleOf()`. If all validators in the schema are synchronous, the return type stays synchronous -- you don't pay for async when you don't use it.
127
+
128
+ ### Mixing Sync and Async
129
+
130
+ `pipeAsync` awaits each step, so you can freely mix sync and async functions:
131
+
132
+ ```typescript
133
+ const process = async (input: unknown) =>
134
+ await pipeAsync(
135
+ validate(input, schema), // sync
136
+ mapWith(enrichData), // sync
137
+ flatMapWith(fetchDB), // async
138
+ mapWith(transform), // sync
139
+ flatMapWith(saveDB), // async
140
+ );
141
+ ```
142
+
143
+ ### Async Side Effects
144
+
145
+ `tapWith` accepts async functions. Side effects run without altering the Result:
146
+
147
+ ```typescript
148
+ import { tapWith, tapErrWith } from '@railway-ts/pipelines/result';
149
+
150
+ const processAndAudit = async (input: unknown) =>
151
+ await pipeAsync(
152
+ validate(input, schema),
153
+ flatMapWith(processPayment),
154
+ tapWith(async (payment) => {
155
+ await auditLog.write({ event: 'payment_processed', payment });
156
+ }),
157
+ tapErrWith(async (errors) => {
158
+ await auditLog.write({ event: 'payment_failed', errors });
159
+ }),
160
+ );
161
+ ```
162
+
163
+ ### Reusable Async Pipelines
164
+
165
+ Use `flowAsync` to define an async pipeline as a reusable function:
166
+
167
+ ```typescript
168
+ import { flowAsync } from '@railway-ts/pipelines/composition';
169
+ import { mapWith, flatMapWith, tapWith } from '@railway-ts/pipelines/result';
170
+
171
+ const processOrder = flowAsync(
172
+ (input: unknown) => validate(input, orderSchema),
173
+ flatMapWith(validateInventory),
174
+ flatMapWith(chargePayment),
175
+ tapWith(async (order) => {
176
+ await sendConfirmationEmail(order);
177
+ }),
178
+ flatMapWith(createShipment),
179
+ );
180
+
181
+ // Use it
182
+ const result = await processOrder(rawInput);
183
+ ```
184
+
185
+ ---
186
+
187
+ ## Validation Patterns
188
+
189
+ ### Multi-Step Validation
190
+
191
+ ```typescript
192
+ import { flow } from '@railway-ts/pipelines/composition';
193
+ import { mapWith, flatMapWith, tapWith, tapErrWith } from '@railway-ts/pipelines/result';
194
+
195
+ const validateAndTransform = flow(
196
+ (input: unknown) => validate(input, inputSchema),
197
+ flatMapWith(validateBusinessRules),
198
+ flatMapWith(checkAgainstDatabase),
199
+ mapWith(transformForStorage),
200
+ );
201
+ ```
202
+
203
+ ### Cross-Field Validation
204
+
205
+ Use `refineAt` after `object()` to validate relationships between fields. Errors are attached to a specific path:
206
+
207
+ ```typescript
208
+ import { object, required, string, chain, refineAt } from '@railway-ts/pipelines/schema';
209
+
210
+ const signupSchema = chain(
211
+ object({
212
+ password: required(string()),
213
+ confirmPassword: required(string()),
214
+ }),
215
+ refineAt('confirmPassword', (data) => data.password === data.confirmPassword, 'Passwords must match'),
216
+ );
217
+
218
+ const result = validate({ password: 'abc', confirmPassword: 'xyz' }, signupSchema);
219
+ // Err([{ path: ['confirmPassword'], message: 'Passwords must match' }])
220
+ ```
221
+
222
+ ### Formatting Errors for UI
223
+
224
+ `formatErrors` flattens `ValidationError[]` into `Record<string, string>` keyed by dot-path. `ROOT_ERROR_KEY` (`"_root"`) is used for errors without a field path:
225
+
226
+ ```typescript
227
+ import { validate, formatErrors, ROOT_ERROR_KEY } from '@railway-ts/pipelines/schema';
228
+ import { match } from '@railway-ts/pipelines/result';
229
+
230
+ const result = validate(input, schema);
231
+
232
+ match(result, {
233
+ ok: (data) => submitForm(data),
234
+ err: (errors) => {
235
+ const formatted = formatErrors(errors);
236
+ // { name: 'Required', 'address.zip': 'Must be 5 digits', _root: 'Form invalid' }
237
+
238
+ // Wire to form state
239
+ for (const [field, message] of Object.entries(formatted)) {
240
+ if (field === ROOT_ERROR_KEY) {
241
+ showBanner(message);
242
+ } else {
243
+ setFieldError(field, message);
244
+ }
245
+ }
246
+ },
247
+ });
248
+ ```
249
+
250
+ ### Conditional Validation
251
+
252
+ ```typescript
253
+ const validateConditionally = (input: unknown) => {
254
+ const baseResult = validate(input, baseSchema);
255
+
256
+ return flatMap(baseResult, (data) => {
257
+ if (data.type === 'premium') {
258
+ return validate(data, premiumSchema);
259
+ }
260
+ return ok(data);
261
+ });
262
+ };
263
+ ```
264
+
265
+ ### Validation with Side Effects
266
+
267
+ ```typescript
268
+ const validateAndLog = flow(
269
+ (input: unknown) => validate(input, schema),
270
+ tapWith((data) => logger.info('Validated:', data)),
271
+ tapErrWith((errors) => logger.error('Failed:', errors)),
272
+ );
273
+ ```
274
+
275
+ ---
276
+
277
+ ## Combining Results
278
+
279
+ ### `combine` -- Fail on First Error
280
+
281
+ Use when you need all results to succeed. Returns the first error encountered:
282
+
283
+ ```typescript
284
+ import { combine } from '@railway-ts/pipelines/result';
285
+
286
+ const fetchUserData = async (userId: string) => {
287
+ const [profile, settings, preferences] = await Promise.all([
288
+ fetchProfile(userId),
289
+ fetchSettings(userId),
290
+ fetchPreferences(userId),
291
+ ]);
292
+
293
+ return combine([profile, settings, preferences]);
294
+ // Result<[Profile, Settings, Preferences], Error>
295
+ };
296
+
297
+ match(await fetchUserData('123'), {
298
+ ok: ([profile, settings, preferences]) => {
299
+ // All three succeeded, full type safety
300
+ return { profile, settings, preferences };
301
+ },
302
+ err: (error) => handleError(error),
303
+ });
304
+ ```
305
+
306
+ ### `combineAll` -- Collect All Errors
307
+
308
+ Use for form validation where you want to show every error at once:
309
+
310
+ ```typescript
311
+ import { combineAll } from '@railway-ts/pipelines/result';
312
+
313
+ const validateForm = (data: { name: unknown; email: unknown; age: unknown }) => {
314
+ const name = validate(data.name, nameSchema);
315
+ const email = validate(data.email, emailSchema);
316
+ const age = validate(data.age, ageSchema);
317
+
318
+ return combineAll([name, email, age]);
319
+ // Result<[string, string, number], ValidationError[][]>
320
+ };
321
+
322
+ match(validateForm(input), {
323
+ ok: ([name, email, age]) => createUser({ name, email, age }),
324
+ err: (errorGroups) => displayAllErrors(errorGroups.flat()),
325
+ });
326
+ ```
327
+
328
+ ### `partition` -- Keep Both Sides
329
+
330
+ When you need both successes and failures from a batch operation:
331
+
332
+ ```typescript
333
+ import { ok, err, partition } from '@railway-ts/pipelines/result';
334
+
335
+ const results = users.map((user) => validateUser(user));
336
+ const { successes, failures } = partition(results);
337
+
338
+ console.log(`${successes.length} valid, ${failures.length} invalid`);
339
+ // Process valid users
340
+ saveUsers(successes);
341
+ // Report invalid ones
342
+ reportErrors(failures);
343
+ ```
344
+
345
+ ### When to Use Which
346
+
347
+ | | `combine` | `combineAll` | `partition` |
348
+ | -------------- | -------------------------------------- | -------------------------------- | ----------------------------------- |
349
+ | **Stops at** | First error | Collects all | Collects all |
350
+ | **Returns** | `Result<T[], E>` | `Result<T[], E[]>` | `{ successes: T[]; failures: E[] }` |
351
+ | **Error type** | `E` (single) | `E[]` (array of all) | `E[]` (array of all) |
352
+ | **Use case** | Parallel fetches, dependent operations | Form validation (all-or-nothing) | Batch processing (partial success) |
353
+
354
+ ---
355
+
356
+ ## Error Recovery
357
+
358
+ ### `orElse` -- Fallback on Error
359
+
360
+ Recover from an `Err` by providing an alternative `Result`:
361
+
362
+ ```typescript
363
+ import { ok, err, orElse } from '@railway-ts/pipelines/result';
364
+
365
+ const primary = err('primary failed');
366
+ const recovered = orElse(primary, (error) => ok('fallback value'));
367
+ // Ok('fallback value')
368
+ ```
369
+
370
+ ### `orElseWith` -- Curried for Pipelines
371
+
372
+ ```typescript
373
+ import { pipe } from '@railway-ts/pipelines/composition';
374
+ import { orElseWith, flatMapWith, mapWith } from '@railway-ts/pipelines/result';
375
+
376
+ const fetchWithFallback = (id: string) =>
377
+ pipe(
378
+ fetchFromCache(id),
379
+ orElseWith(() => fetchFromDatabase(id)),
380
+ orElseWith(() => fetchFromBackupService(id)),
381
+ mapWith(normalize),
382
+ );
383
+ ```
384
+
385
+ ### `bimap` -- Transform Both Branches
386
+
387
+ Apply different transformations to `Ok` and `Err` in one step:
388
+
389
+ ```typescript
390
+ import { bimap } from '@railway-ts/pipelines/result';
391
+
392
+ const result = bimap(
393
+ fetchUser(id),
394
+ (user) => user.displayName, // transform Ok
395
+ (error) => `Failed: ${error.code}`, // transform Err
396
+ );
397
+ // Result<string, string>
398
+ ```
399
+
400
+ ---
401
+
402
+ ## Discriminated Unions and Enums
403
+
404
+ ### Discriminated Unions
405
+
406
+ ```typescript
407
+ import { discriminatedUnion, literal, object, required, number } from '@railway-ts/pipelines/schema';
408
+
409
+ const shapeSchema = discriminatedUnion('type', {
410
+ circle: object({
411
+ type: required(literal('circle')),
412
+ radius: required(number()),
413
+ }),
414
+ rectangle: object({
415
+ type: required(literal('rectangle')),
416
+ width: required(number()),
417
+ height: required(number()),
418
+ }),
419
+ });
420
+
421
+ const result = validate(input, shapeSchema);
422
+
423
+ match(result, {
424
+ ok: (shape) => {
425
+ // TypeScript knows shape.type is 'circle' | 'rectangle'
426
+ if (shape.type === 'circle') {
427
+ return Math.PI * shape.radius ** 2;
428
+ } else {
429
+ return shape.width * shape.height;
430
+ }
431
+ },
432
+ err: (errors) => 0,
433
+ });
434
+ ```
435
+
436
+ ### Enum Validation
437
+
438
+ Three ways to validate enums, each for a different use case:
439
+
440
+ **`stringEnum`** -- String union types (most common):
441
+
442
+ ```typescript
443
+ import { stringEnum } from '@railway-ts/pipelines/schema';
444
+
445
+ const roleValidator = stringEnum(['admin', 'editor', 'viewer'] as const);
446
+ // Validator<unknown, 'admin' | 'editor' | 'viewer'>
447
+
448
+ validate('admin', roleValidator); // Ok('admin')
449
+ validate('hacker', roleValidator); // Err(...)
450
+ ```
451
+
452
+ **`enumValue`** -- TypeScript `enum` keyword:
453
+
454
+ ```typescript
455
+ import { enumValue } from '@railway-ts/pipelines/schema';
456
+
457
+ enum Status {
458
+ Active = 'active',
459
+ Inactive = 'inactive',
460
+ }
461
+
462
+ const statusValidator = enumValue(Status);
463
+ // Validator<unknown, Status>
464
+
465
+ validate('active', statusValidator); // Ok(Status.Active)
466
+ ```
467
+
468
+ **`oneOf`** -- Any fixed set of values:
469
+
470
+ ```typescript
471
+ import { oneOf } from '@railway-ts/pipelines/schema';
472
+
473
+ const priorityValidator = oneOf([1, 2, 3] as const);
474
+ // Validator<unknown, 1 | 2 | 3>
475
+
476
+ validate(2, priorityValidator); // Ok(2)
477
+ validate(5, priorityValidator); // Err(...)
478
+ ```
479
+
480
+ | | `stringEnum` | `enumValue` | `oneOf` |
481
+ | --------------- | ------------------- | ---------------- | -------------------- |
482
+ | **Input** | `readonly string[]` | TS `enum` object | `readonly T[]` |
483
+ | **Output type** | String union | Enum type | Union of values |
484
+ | **Use when** | String literals | TS enums | Numbers, mixed types |
485
+
486
+ ---
487
+
488
+ ## Type Interop: Option, Result, Promise
489
+
490
+ Convert between `Option`, `Result`, and `Promise` when crossing module boundaries.
491
+
492
+ ### Option -> Result
493
+
494
+ When an optional lookup needs to participate in a Result pipeline:
495
+
496
+ ```typescript
497
+ import { fromNullable, mapToResult } from '@railway-ts/pipelines/option';
498
+
499
+ const users = new Map([['1', 'Alice']]);
500
+
501
+ const userResult = mapToResult(fromNullable(users.get('999')), 'User not found');
502
+ // Result<string, string> -- Err('User not found')
503
+ ```
504
+
505
+ ### Result -> Option
506
+
507
+ When you care about the value but not the specific error:
508
+
509
+ ```typescript
510
+ import { fromTry, mapToOption } from '@railway-ts/pipelines/result';
511
+
512
+ const parsed = mapToOption(fromTry(() => JSON.parse(text)));
513
+ // Option<any> -- Some if parsed, None if threw
514
+ ```
515
+
516
+ ### Result -> Promise
517
+
518
+ Bridge into async code that expects thrown errors:
519
+
520
+ ```typescript
521
+ import { err, ok, toPromise } from '@railway-ts/pipelines/result';
522
+
523
+ const value = await toPromise(ok(42));
524
+ // 42
525
+
526
+ await toPromise(err('boom'));
527
+ // throws 'boom'
528
+ ```
529
+
530
+ ### Mixed Workflow
531
+
532
+ ```typescript
533
+ import { pipe } from '@railway-ts/pipelines/composition';
534
+ import { fromNullable, mapToResult } from '@railway-ts/pipelines/option';
535
+ import { err, flatMapWith, match, ok } from '@railway-ts/pipelines/result';
536
+
537
+ const getApiKey = () => fromNullable(process.env.API_KEY);
538
+
539
+ const callApi = (key: string) => (key === 'valid' ? ok('response data') : err('Invalid API key'));
540
+
541
+ const result = pipe(mapToResult(getApiKey(), 'API key not configured'), flatMapWith(callApi));
542
+
543
+ match(result, {
544
+ ok: (data) => console.log(data),
545
+ err: (error) => console.error(error),
546
+ });
547
+ ```
548
+
549
+ ---
550
+
551
+ ## Specialized Validators
552
+
553
+ ### Number Validators
554
+
555
+ ```typescript
556
+ import { chain, parseNumber, positive, precision, min, max, integer, between } from '@railway-ts/pipelines/schema';
557
+
558
+ // Currency: positive, 2 decimal places
559
+ const currency = chain(parseNumber(), positive(), precision(2));
560
+
561
+ // Age: integer between 0 and 150
562
+ const age = chain(parseNumber(), integer(), between(0, 150));
563
+
564
+ // Temperature: any number in range
565
+ const temperature = chain(parseNumber(), min(-273.15), max(1_000_000));
566
+ ```
567
+
568
+ ### Date Validators
569
+
570
+ ```typescript
571
+ import { chain, parseDate, parseISODate, todayOrFuture, pastDate, dateRange } from '@railway-ts/pipelines/schema';
572
+
573
+ // Booking date: must be in the future
574
+ const bookingDate = chain(parseDate(), todayOrFuture());
575
+
576
+ // Birth date: must be in the past
577
+ const birthDate = chain(parseDate(), pastDate());
578
+
579
+ // Event window: within a specific range
580
+ const eventDate = chain(parseISODate(), dateRange(new Date('2025-01-01'), new Date('2025-12-31')));
581
+ ```
582
+
583
+ ### Empty-String Handling
584
+
585
+ `emptyAsOptional` treats empty strings (and `null`/`undefined`) as `undefined` instead of failing validation. Useful for HTML forms where blank fields submit as `""`:
586
+
587
+ ```typescript
588
+ import { object, required, optional, string, emptyAsOptional, chain, parseNumber } from '@railway-ts/pipelines/schema';
589
+
590
+ const formSchema = object({
591
+ name: required(string()),
592
+ nickname: optional(emptyAsOptional(string())), // "" -> undefined
593
+ age: optional(emptyAsOptional(chain(parseNumber()))), // "" -> undefined, "25" -> 25
594
+ });
595
+
596
+ validate({ name: 'Alice', nickname: '', age: '' }, formSchema);
597
+ // Ok({ name: 'Alice' }) -- nickname and age are undefined, not errors
598
+ ```
599
+
600
+ ### Reusable Validators
601
+
602
+ ```typescript
603
+ import { chain, object, optional, pattern, required, string } from '@railway-ts/pipelines/schema';
604
+
605
+ const email = () => chain(string(), pattern(/^[^@]+@[^@]+\.[^@]+$/));
606
+ const phoneUS = () => chain(string(), pattern(/^\d{3}-\d{3}-\d{4}$/));
607
+ const zipCode = () => chain(string(), pattern(/^\d{5}$/));
608
+
609
+ const contactSchema = object({
610
+ email: required(email()),
611
+ phone: optional(phoneUS()),
612
+ zip: required(zipCode()),
613
+ });
614
+ ```
615
+
616
+ ---
617
+
618
+ ## Standard Schema Interop
619
+
620
+ `toStandardSchema` wraps any validator as a [Standard Schema v1](https://github.com/standard-schema/standard-schema) object, making it compatible with tRPC, TanStack Form, React Hook Form, and other tools that accept Standard Schema.
621
+
622
+ ```typescript
623
+ import { toStandardSchema, type StandardSchemaV1 } from '@railway-ts/pipelines/schema';
624
+
625
+ const userSchema = object({
626
+ name: required(string()),
627
+ age: required(chain(parseNumber(), min(18))),
628
+ });
629
+
630
+ const standardUser = toStandardSchema(userSchema);
631
+ // StandardSchemaV1<unknown, { name: string; age: number }>
632
+ ```
633
+
634
+ Works with both sync and async validators:
635
+
636
+ ```typescript
637
+ const asyncSchema = chainAsync(
638
+ object({ email: required(string()) }),
639
+ refineAtAsync(
640
+ 'email',
641
+ async (data) => {
642
+ const exists = await checkEmailExists(data.email);
643
+ return !exists;
644
+ },
645
+ 'Email already in use',
646
+ ),
647
+ );
648
+
649
+ const standardAsync = toStandardSchema(asyncSchema);
650
+ // Can be passed to any Standard Schema consumer
651
+ ```
652
+
653
+ ---
654
+
655
+ ## Composition Utilities
656
+
657
+ ### `curry` / `uncurry` -- Partial Application
658
+
659
+ Convert multi-argument functions to chains of single-argument functions and back:
660
+
661
+ ```typescript
662
+ import { curry, uncurry } from '@railway-ts/pipelines/composition';
663
+
664
+ const add = (a: number, b: number) => a + b;
665
+
666
+ const curriedAdd = curry(add);
667
+ const add5 = curriedAdd(5);
668
+ add5(3); // 8
669
+
670
+ // Reverse it
671
+ const originalAdd = uncurry(curriedAdd);
672
+ originalAdd(5, 3); // 8
673
+ ```
674
+
675
+ ### `tupled` / `untupled` -- Tuple Conversion
676
+
677
+ Convert between multi-argument and tuple-accepting functions. Pairs naturally with `combine`:
678
+
679
+ ```typescript
680
+ import { tupled, untupled } from '@railway-ts/pipelines/composition';
681
+ import { combine, mapWith, match } from '@railway-ts/pipelines/result';
682
+ import { pipe } from '@railway-ts/pipelines/composition';
683
+
684
+ const createUser = (name: string, age: number) => ({ name, age });
685
+
686
+ const tupledCreate = tupled(createUser);
687
+ // ([string, number]) => { name: string; age: number }
688
+
689
+ // Combine validated fields, then pass the tuple directly
690
+ const result = pipe(combine([validateName(input.name), validateAge(input.age)]), mapWith(tupledCreate));
691
+ // Result<{ name: string; age: number }, ValidationError>
692
+
693
+ // Reverse it
694
+ const originalCreate = untupled(tupledCreate);
695
+ originalCreate('Alice', 30); // { name: 'Alice', age: 30 }
696
+ ```
697
+
698
+ ---
699
+
700
+ ## Testing Pipelines
701
+
702
+ ### Sync Pipelines
703
+
704
+ ```typescript
705
+ import { isOk, isErr } from '@railway-ts/pipelines/result';
706
+
707
+ test('validates user input', () => {
708
+ const result = validateUser({ name: 'Alice', age: 25 });
709
+
710
+ expect(isOk(result)).toBe(true);
711
+ if (isOk(result)) {
712
+ expect(result.value.name).toBe('Alice');
713
+ }
714
+ });
715
+
716
+ test('rejects invalid age', () => {
717
+ const result = validateUser({ name: 'Bob', age: -5 });
718
+
719
+ expect(isErr(result)).toBe(true);
720
+ if (isErr(result)) {
721
+ expect(result.error).toContain('age');
722
+ }
723
+ });
724
+ ```
725
+
726
+ ### Async Pipelines
727
+
728
+ ```typescript
729
+ test('processes order end-to-end', async () => {
730
+ const result = await processOrder({ item: 'widget', quantity: 5 });
731
+
732
+ expect(isOk(result)).toBe(true);
733
+ if (isOk(result)) {
734
+ expect(result.value.status).toBe('shipped');
735
+ }
736
+ });
737
+
738
+ test('rejects invalid quantity', async () => {
739
+ const result = await processOrder({ item: 'widget', quantity: -1 });
740
+
741
+ expect(isErr(result)).toBe(true);
742
+ });
743
+ ```
744
+
745
+ ---
746
+
747
+ ## Full Example: Launch Decision Pipeline
748
+
749
+ Full pipeline: validate launch parameters, fetch weather data, make GO/NO-GO decision.
750
+
751
+ ```typescript
752
+ import { pipeAsync } from '@railway-ts/pipelines/composition';
753
+ import { err, flatMapWith, fromPromise, match, ok, type Result } from '@railway-ts/pipelines/result';
754
+ import {
755
+ formatErrors,
756
+ object,
757
+ required,
758
+ chain,
759
+ parseNumber,
760
+ min,
761
+ max,
762
+ stringEnum,
763
+ parseDate,
764
+ validate,
765
+ type ValidationError,
766
+ type ValidationResult,
767
+ type InferSchemaType,
768
+ } from '@railway-ts/pipelines/schema';
769
+
770
+ // Schema
771
+ const launchSchema = object({
772
+ vehicleType: required(stringEnum(['falcon9', 'atlas5'] as const)),
773
+ payload: required(chain(parseNumber(), min(1000), max(25_000))),
774
+ latitude: required(chain(parseNumber(), min(-90), max(90))),
775
+ longitude: required(chain(parseNumber(), min(-180), max(180))),
776
+ windowStart: required(parseDate()),
777
+ });
778
+
779
+ type LaunchParams = InferSchemaType<typeof launchSchema>;
780
+ type VehicleType = LaunchParams['vehicleType'];
781
+
782
+ // Weather API types
783
+ type WeatherData = {
784
+ wind_speed_10m: number;
785
+ wind_direction_10m: number;
786
+ wind_gusts_10m: number;
787
+ };
788
+
789
+ type LaunchContext = {
790
+ params: LaunchParams;
791
+ weather: WeatherData;
792
+ };
793
+
794
+ // Helper for API responses
795
+ const toJsonIfOk = (res: Response) => (res.ok ? res.json() : Promise.reject(`HTTP ${res.status}`));
796
+
797
+ // Fetch daily forecast for the launch window date
798
+ const fetchWeatherWithParams = async (params: LaunchParams): Promise<Result<LaunchContext, ValidationError[]>> => {
799
+ const date = params.windowStart.toISOString().split('T')[0]!;
800
+ const url = new URL('https://api.open-meteo.com/v1/forecast');
801
+ url.searchParams.append('latitude', params.latitude.toString());
802
+ url.searchParams.append('longitude', params.longitude.toString());
803
+ url.searchParams.append('daily', 'wind_speed_10m_max,wind_direction_10m_dominant,wind_gusts_10m_max');
804
+ url.searchParams.append('wind_speed_unit', 'ms');
805
+ url.searchParams.append('start_date', date);
806
+ url.searchParams.append('end_date', date);
807
+
808
+ const result = await fromPromise(fetch(url.toString()).then(toJsonIfOk));
809
+
810
+ return match(result, {
811
+ ok: (data) =>
812
+ ok({
813
+ params,
814
+ weather: {
815
+ wind_speed_10m: data.daily.wind_speed_10m_max[0],
816
+ wind_direction_10m: data.daily.wind_direction_10m_dominant[0],
817
+ wind_gusts_10m: data.daily.wind_gusts_10m_max[0],
818
+ },
819
+ }),
820
+ err: (msg) => err([{ path: ['weather_api'], message: String(msg) }]),
821
+ });
822
+ };
823
+
824
+ type LaunchDecision = {
825
+ windSpeed: number;
826
+ windGusts: number;
827
+ maxAllowed: number;
828
+ };
829
+
830
+ // Business rule check — can fail, so flatMapWith
831
+ const assessLaunchConditions = (context: LaunchContext): Result<LaunchDecision, ValidationError[]> => {
832
+ const windLimits: Record<VehicleType, number> = {
833
+ falcon9: 15,
834
+ atlas5: 12,
835
+ };
836
+
837
+ const maxWind = windLimits[context.params.vehicleType];
838
+ const actualMaxWind = Math.max(context.weather.wind_speed_10m, context.weather.wind_gusts_10m);
839
+
840
+ if (actualMaxWind > maxWind) {
841
+ return err([{ path: ['weather'], message: `Wind ${actualMaxWind} m/s exceeds ${maxWind} m/s limit` }]);
842
+ }
843
+
844
+ return ok({
845
+ windSpeed: context.weather.wind_speed_10m,
846
+ windGusts: context.weather.wind_gusts_10m,
847
+ maxAllowed: maxWind,
848
+ });
849
+ };
850
+
851
+ // Main pipeline
852
+ const evaluateLaunch = async (input: unknown): Promise<ValidationResult<LaunchDecision>> => {
853
+ const validationResult = validate(input, launchSchema);
854
+
855
+ const result = await pipeAsync(
856
+ validationResult,
857
+ flatMapWith(fetchWeatherWithParams),
858
+ flatMapWith(assessLaunchConditions),
859
+ );
860
+
861
+ return match(result, {
862
+ ok: (decision) => ({ valid: true as const, data: decision }),
863
+ err: (errors) => ({ valid: false as const, errors: formatErrors(errors) }),
864
+ });
865
+ };
866
+
867
+ // Usage
868
+ const result = await evaluateLaunch({
869
+ vehicleType: 'falcon9',
870
+ payload: 1000,
871
+ latitude: 28.5721,
872
+ longitude: -80.648,
873
+ windowStart: new Date(),
874
+ });
875
+
876
+ console.log(result);
877
+ ```
878
+
879
+ **The pattern:**
880
+
881
+ 1. Validate at boundary with schema
882
+ 2. Chain async operations with `pipeAsync` + `flatMapWith`
883
+ 3. Pure business logic as sync functions that return `Result` (can fail via `Err`)
884
+ 4. Branch once at the end with `match`
885
+
886
+ ---
887
+
888
+ ## Next Steps
889
+
890
+ - **[API Reference](API.md)** — Every function signature and description