@aklinker1/zeta 2.1.2 → 2.1.3

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/src/types.ts DELETED
@@ -1,1102 +0,0 @@
1
- /**
2
- * Types used internally by Zeta to build the type system. You probably don't
3
- * need to use these, and there is no guarantee that they will remain stable
4
- * between non-major versions.
5
- *
6
- * @internal Subject to breaking changes outside of major versions.
7
- * @module
8
- */
9
- import type { StandardSchemaV1 } from "@standard-schema/spec";
10
- import type { OpenAPI } from "openapi-types";
11
- import type { IsStatusResult } from "./internal/utils";
12
- import type { HttpStatus } from "./status";
13
-
14
- //
15
- // APP
16
- //
17
-
18
- /**
19
- * Represents an App object. TAppData represents additional type information not
20
- * always stored on the app object itself.
21
- */
22
- export interface App<TAppData extends AppData = AppData> {
23
- /**
24
- * Internal references for implementing routing and calling registered
25
- * handlers. Subject to breaking changes outside of major versions.
26
- * @internal
27
- */
28
- "~zeta": {
29
- /**
30
- * Used for deduplication of hooks.
31
- */
32
- id: string;
33
-
34
- /**
35
- * When true, hooks defined on this app should be added to any app that
36
- * imports this app.
37
- */
38
- exported?: boolean;
39
-
40
- /**
41
- * Path prefix from `CreateAppOptions.prefix`.
42
- */
43
- prefix: string;
44
-
45
- /**
46
- * List of routes registered with the app.
47
- */
48
- routes: { [method: string]: { [path: string]: RouterData } };
49
-
50
- /**
51
- * Stores arrays of hooks registered on the app.
52
- */
53
- hooks: LifeCycleHooks;
54
- };
55
-
56
- /**
57
- * Merge and simplify all the app routes into a single fetch function.
58
- */
59
- build: () => ServerSideFetch;
60
-
61
- /**
62
- * Returns your application's OpenAPI spec. You do not need to listen to a
63
- * port to call this method.
64
- */
65
- getOpenApiSpec: () => OpenAPI.Document;
66
-
67
- /**
68
- * Mark the app as "exported". When an exported app is `use`d by a
69
- * parent app, the parent app will inherit all of it's hooks and modifiers.
70
- *
71
- * Regular, non-exported apps isolate their hooks and modifiers from the
72
- * parent app (except for the global hooks, `onGlobalRequest`, `onGlobalError`, and
73
- * `onGlobalAfterResponse`, which are always inherited by the parent app).
74
- *
75
- * The basic example is you can't access a decorated value from a parent app
76
- * unless the child app is exported.
77
- *
78
- * @example
79
- * ```ts
80
- * const child = createApp()
81
- * .decorate("a", "A");
82
- *
83
- * const bad = createApp()
84
- * .use(child)
85
- * .get("/", ({ a }) => {
86
- * console.log(a); // => undefined
87
- * });
88
- *
89
- * const good = createApp()
90
- * .use(child.export())
91
- * .get("/", ({ a }) => {
92
- * console.log(a); // => "A"
93
- * });
94
- * ```
95
- */
96
- export: () => App<MergeAppData<TAppData, { exported: true }>>;
97
-
98
- /**
99
- * Detect the current environment and use `Bun.serve` or `Deno.serve` to serve the app over a port.
100
- * @param port The port to listen on.
101
- * @param cb Optional callback to be called when the server is ready.
102
- */
103
- listen: (port: number, cb?: () => void) => this;
104
-
105
- /**
106
- * Add a static value to the handler context.
107
- */
108
- decorate<TKey extends string, TValue>(
109
- key: TKey,
110
- value: TValue,
111
- ): App<
112
- Simplify<
113
- MergeAppData<TAppData, { ctx: { [key in TKey]: Readonly<TValue> } }>
114
- >
115
- >;
116
- /**
117
- * Add multiple static values to the handler context.
118
- */
119
- decorate<TValues extends Record<string, any>>(
120
- values: TValues,
121
- ): App<Simplify<MergeAppData<TAppData, { ctx: TValues }>>>;
122
-
123
- /**
124
- * Add a callback that is called before the route is matched. If the callback
125
- * returns a value, it will be merged into the `ctx` object. If the callback
126
- * returns a `Response`, it will be returned immediately.
127
- *
128
- * @param callback The function to call.
129
- */
130
- onGlobalRequest(
131
- callback: (
132
- ctx: OnGlobalRequestContext<GetAppDataCtx<TAppData>>,
133
- ) => MaybePromise<Response | void>,
134
- ): this;
135
- onGlobalRequest<TNewCtx extends Record<string, any>>(
136
- callback: (
137
- ctx: OnGlobalRequestContext<GetAppDataCtx<TAppData>>,
138
- ) => MaybePromise<TNewCtx>,
139
- ): App<MergeAppData<TAppData, { ctx: TNewCtx }>>;
140
-
141
- /**
142
- * Add a callback that is called after the route is matched and before the
143
- * inputs are validated. If the callback returns a value, it will be merged
144
- * into the `ctx` object. If the callback returns a `Response`, it will be
145
- * returned immediately.
146
- *
147
- * @param callback The function to call.
148
- */
149
- onTransform(
150
- callback: (
151
- ctx: OnTransformContext<GetAppDataCtx<TAppData>>,
152
- ) => MaybePromise<Response | void>,
153
- ): this;
154
- onTransform<TNewCtx extends Record<string, any>>(
155
- callback: (
156
- ctx: OnTransformContext<GetAppDataCtx<TAppData>>,
157
- ) => MaybePromise<TNewCtx>,
158
- ): App<MergeAppData<TAppData, { ctx: TNewCtx }>>;
159
-
160
- /**
161
- * Add a callback that is called after inputs are validated and before the
162
- * handler is called. If the callback returns a value, it will be merged into
163
- * the `ctx` object. If the callback returns a `Response`, it will be returned
164
- * immediately.
165
- *
166
- * @param callback The function to call.
167
- */
168
- onBeforeHandle(
169
- callback: (
170
- ctx: OnBeforeHandleContext<GetAppDataCtx<TAppData>>,
171
- ) => MaybePromise<Response | void>,
172
- ): this;
173
- onBeforeHandle<TNewCtx extends Record<string, any>>(
174
- callback: (
175
- ctx: OnBeforeHandleContext<GetAppDataCtx<TAppData>>,
176
- ) => MaybePromise<TNewCtx>,
177
- ): App<MergeAppData<TAppData, { ctx: TNewCtx }>>;
178
-
179
- /**
180
- * Add a callback that is called after the handler is called and before the
181
- * response is validated. If the callback returns a value, it replaces the
182
- * response with it.
183
- *
184
- * @param callback The function to call.
185
- */
186
- onAfterHandle(
187
- callback: (
188
- ctx: AfterHandleContext<GetAppDataCtx<TAppData>>,
189
- ) => MaybePromise<unknown | void>,
190
- ): this;
191
-
192
- /**
193
- * Add a callback that is called after the response is validated and before it
194
- * is sent to the client. The callback can return a `Response` if you want to
195
- * change how the response is built.
196
- *
197
- * @param callback The function to call.
198
- */
199
- onMapResponse(
200
- callback: (
201
- ctx: AfterHandleContext<GetAppDataCtx<TAppData>>,
202
- ) => MaybePromise<unknown | void>,
203
- ): this;
204
-
205
- /**
206
- * Add a callback that is called when an error is thrown. The callback can
207
- * optionally return a `Response`, which will be used to respond to the
208
- * client.
209
- *
210
- * @param callback The function to call.
211
- */
212
- onGlobalError(
213
- callback: (
214
- ctx: OnGlobalErrorContext<GetAppDataCtx<TAppData>>,
215
- ) => MaybePromise<void>,
216
- ): this;
217
-
218
- /**
219
- * Add a callback that is called after the response is sent.
220
- * @param callback The function to call.
221
- */
222
- onGlobalAfterResponse(
223
- callback: (
224
- ctx: AfterResponseContext<GetAppDataCtx<TAppData>>,
225
- ) => MaybePromise<void>,
226
- ): this;
227
-
228
- /**
229
- * Add an undocumented GET route to the app.
230
- */
231
- get<TPath extends BasePath>(
232
- path: TPath,
233
- handler: RouteHandler<TAppData, TPath, AnyDef>,
234
- ): App<
235
- MergeAppData<TAppData, { routes: { GET: { [path in TPath]: AnyDef } } }>
236
- >;
237
- /**
238
- * Add a documented GET route to the app.
239
- */
240
- get<TPath extends BasePath, TRouteDef extends RouteDef>(
241
- path: TPath,
242
- def: TRouteDef,
243
- handler: RouteHandler<TAppData, TPath, TRouteDef>,
244
- ): App<
245
- MergeAppData<TAppData, { routes: { GET: { [path in TPath]: TRouteDef } } }>
246
- >;
247
-
248
- /**
249
- * Add an undocumented POST route to the app.
250
- */
251
- post<TPath extends BasePath>(
252
- path: TPath,
253
- handler: RouteHandler<TAppData, TPath, AnyDef>,
254
- ): App<
255
- MergeAppData<TAppData, { routes: { POST: { [path in TPath]: AnyDef } } }>
256
- >;
257
- /**
258
- * Add a documented POST route to the app.
259
- */
260
- post<TPath extends BasePath, TRouteDef extends RouteDef>(
261
- path: TPath,
262
- def: TRouteDef,
263
- handler: RouteHandler<TAppData, TPath, TRouteDef>,
264
- ): App<
265
- MergeAppData<TAppData, { routes: { POST: { [path in TPath]: TRouteDef } } }>
266
- >;
267
-
268
- /**
269
- * Add an undocumented PUT route to the app.
270
- */
271
- put<TPath extends BasePath>(
272
- path: TPath,
273
- handler: RouteHandler<TAppData, TPath, AnyDef>,
274
- ): App<
275
- MergeAppData<TAppData, { routes: { PUT: { [path in TPath]: AnyDef } } }>
276
- >;
277
- /**
278
- * Add a documented PUT route to the app.
279
- */
280
- put<TPath extends BasePath, TRouteDef extends RouteDef>(
281
- path: TPath,
282
- def: TRouteDef,
283
- handler: RouteHandler<TAppData, TPath, TRouteDef>,
284
- ): App<
285
- MergeAppData<TAppData, { routes: { PUT: { [path in TPath]: TRouteDef } } }>
286
- >;
287
-
288
- /**
289
- * Add an undocumented DELETE route to the app.
290
- */
291
- delete<TPath extends BasePath>(
292
- path: TPath,
293
- handler: RouteHandler<TAppData, TPath, AnyDef>,
294
- ): App<
295
- MergeAppData<TAppData, { routes: { DELETE: { [path in TPath]: AnyDef } } }>
296
- >;
297
- /**
298
- * Add a documented DELETE route to the app.
299
- */
300
- delete<TPath extends BasePath, TRouteDef extends RouteDef>(
301
- path: TPath,
302
- def: TRouteDef,
303
- handler: RouteHandler<TAppData, TPath, TRouteDef>,
304
- ): App<
305
- MergeAppData<
306
- TAppData,
307
- { routes: { DELETE: { [path in TPath]: TRouteDef } } }
308
- >
309
- >;
310
-
311
- /**
312
- * Add an undocumented route to the app that responds to any method used.
313
- */
314
- any<TPath extends BasePath>(
315
- path: TPath,
316
- handler: RouteHandler<TAppData, TPath, AnyDef>,
317
- ): App<
318
- MergeAppData<TAppData, { routes: { ANY: { [path in TPath]: AnyDef } } }>
319
- >;
320
-
321
- /**
322
- * Add an documented route to the app that responds to any method used.
323
- */
324
- any<TPath extends BasePath, TRouteDef extends RouteDef>(
325
- path: TPath,
326
- def: TRouteDef,
327
- handler: RouteHandler<TAppData, TPath, AnyDef>,
328
- ): App<
329
- MergeAppData<TAppData, { routes: { ANY: { [path in TPath]: TRouteDef } } }>
330
- >;
331
-
332
- /**
333
- * Add an undocumented route to the app using a custom method.
334
- */
335
- method<TMethod extends string, TPath extends BasePath>(
336
- method: TMethod,
337
- path: TPath,
338
- handler: RouteHandler<TAppData, TPath, AnyDef>,
339
- ): App<
340
- MergeAppData<
341
- TAppData,
342
- { routes: { [method in TMethod]: { [path in TPath]: AnyDef } } }
343
- >
344
- >;
345
- /**
346
- * Add a documented route to the app using a custom method.
347
- */
348
- method<
349
- TMethod extends string,
350
- TPath extends BasePath,
351
- TRouteDef extends RouteDef,
352
- >(
353
- method: TMethod,
354
- path: TPath,
355
- def: TRouteDef,
356
- handler: RouteHandler<TAppData, TPath, TRouteDef>,
357
- ): App<
358
- MergeAppData<
359
- TAppData,
360
- { routes: { [method in TMethod]: { [path in TPath]: TRouteDef } } }
361
- >
362
- >;
363
-
364
- /**
365
- * Mount another fetch function at `/**`.
366
- */
367
- mount(
368
- fetch: ServerSideFetch,
369
- ): App<MergeAppData<TAppData, { routes: { ANY: { "/**": AnyDef } } }>>;
370
- /**
371
- * Mount another fetch function at `${path}/**`.
372
- */
373
- mount<TPath extends BasePath>(
374
- path: TPath,
375
- fetch: ServerSideFetch,
376
- ): App<
377
- MergeAppData<
378
- TAppData,
379
- { routes: { ANY: { [path in `${TPath}/**`]: AnyDef } } }
380
- >
381
- >;
382
- /**
383
- * Mount another fetch function at `${path}/**`.
384
- */
385
- mount<TPath extends BasePath, TRouteDef extends RouteDef>(
386
- path: TPath,
387
- def: TRouteDef,
388
- fetch: ServerSideFetch,
389
- ): App<
390
- MergeAppData<
391
- TAppData,
392
- { routes: { ANY: { [path in `${TPath}/**`]: TRouteDef } } }
393
- >
394
- >;
395
-
396
- /**
397
- * Add a subapp to the app.
398
- */
399
- use<TNewApp extends App>(
400
- app: TNewApp,
401
- ): App<UseAppData<TAppData, GetAppData<TNewApp>>>;
402
- }
403
-
404
- /**
405
- * Given an `App`, return it's `AppData`.
406
- */
407
- export type GetAppData<TApp extends App> =
408
- TApp extends App<infer TAppData> ? TAppData : never;
409
-
410
- /**
411
- * Given an `App`, return the routes defined on it.
412
- */
413
- export type GetAppRoutes<TApp extends App> = GetAppData<TApp>["routes"];
414
-
415
- /**
416
- * Data stored internally for each route inside the `rou3` router.
417
- */
418
- export type RouterData = {
419
- def?: RouteDef;
420
- route: string;
421
- hooks: LifeCycleHooks;
422
- compiledHandler: CompiledRouteHandler;
423
- } & (
424
- | { fetch: ServerSideFetch }
425
- | { handler: (ctx: OnBeforeHandleContext) => Promise<any> }
426
- );
427
-
428
- /**
429
- * Function type called internally once a route is matched for a request.
430
- */
431
- export type CompiledRouteHandler = (
432
- request: Request,
433
- ctx: any,
434
- ) => MaybePromise<Response>;
435
-
436
- //
437
- // HANDLERS
438
- //
439
-
440
- /**
441
- * Type of the callback function used for each route.
442
- */
443
- export type RouteHandler<
444
- TAppData extends AppData,
445
- TPath extends BasePath,
446
- TRouteDef extends RouteDef,
447
- > = (
448
- ctx: BuildHandlerContext<TAppData, TPath, TRouteDef>,
449
- ) => MaybePromise<GetRouteHandlerReturnType<TRouteDef>>;
450
-
451
- export type GetRouteHandlerReturnType<TRouteDef extends RouteDef> =
452
- TRouteDef extends { responses: symbol } // is any check
453
- ? any
454
- : TRouteDef extends { responses: infer TResponses }
455
- ? TResponses extends StandardSchemaV1
456
- ? StandardSchemaV1.InferInput<TResponses>
457
- : TRouteDef["responses"] extends Record<number, StandardSchemaV1<any>>
458
- ? StatusResult
459
- : never
460
- : void;
461
-
462
- /**
463
- * Given an `App`, a method, and a route, return the handler function's type.
464
- */
465
- export type GetRouteHandler<
466
- TApp extends App,
467
- TMethod extends keyof GetAppRoutes<TApp>,
468
- TRoute extends keyof GetAppRoutes<TApp>[TMethod],
469
- > = TRoute extends BasePath
470
- ? GetAppRoutes<TApp>[TMethod][TRoute] extends RouteDef
471
- ? RouteHandler<
472
- GetAppData<TApp>,
473
- TRoute,
474
- GetAppRoutes<TApp>[TMethod][TRoute]
475
- >
476
- : never
477
- : never;
478
-
479
- //
480
- // LIFECYCLE HOOKS
481
- //
482
-
483
- /**
484
- * Internal type used to store a hook on an app.
485
- */
486
- export type LifeCycleHook<TCallback extends Function> = {
487
- /**
488
- * Used for deducplication.
489
- */
490
- id: string;
491
- /**
492
- * Where this plugin should be applied.
493
- * - `global`: Global plugins are hoisted to the top-level app.
494
- * - `local`: Local plugins are applied to the app they were added to.
495
- * @default "local"
496
- */
497
- applyTo: "global" | "local";
498
- /**
499
- * The function called when the hook is triggered.
500
- */
501
- callback: TCallback;
502
- };
503
-
504
- /**
505
- * Called immediately after receiving the request. Returned record is merged
506
- * into the handler context.
507
- */
508
- export type OnGlobalRequestHook = LifeCycleHook<
509
- (ctx: Simplify<OnGlobalRequestContext>) => Record<string, any> | void
510
- >;
511
-
512
- /**
513
- * Called before validating the request inputs. Returned record is merged into
514
- * the handler context.
515
- */
516
- export type OnTransformHook = LifeCycleHook<
517
- (
518
- ctx: Simplify<OnTransformContext>,
519
- ) => MaybePromise<Record<string, any> | void>
520
- >;
521
-
522
- /**
523
- * Called before calling the route handler. Returned record is merged into the
524
- * handler context.
525
- */
526
- export type OnBeforeHandleHook = LifeCycleHook<
527
- (
528
- ctx: Simplify<OnBeforeHandleContext>,
529
- ) => MaybePromise<Record<string, any> | void>
530
- >;
531
-
532
- /**
533
- * Called after calling the route handler. If there is a return value, it
534
- * replaces the return value from the handler. Similar to the `onTransform` hook,
535
- * but for the response.
536
- */
537
- export type OnAfterHandleHook = LifeCycleHook<
538
- (ctx: Simplify<AfterHandleContext>) => MaybePromise<unknown | void>
539
- >;
540
-
541
- /**
542
- * Called after validating the handler return value. Used to transform the
543
- * return value into a `Response`.
544
- */
545
- export type OnMapResponseHook = LifeCycleHook<
546
- (ctx: Simplify<OnMapResponseContext>) => MaybePromise<Response | void>
547
- >;
548
-
549
- /**
550
- * Called if an error is thrown in any other hook other than `onGlobalAfterResponse`.
551
- *
552
- * Zeta will handle any `HttpError`s thrown, but you can handle your own errors
553
- * here.
554
- */
555
- export type OnGlobalErrorHook = LifeCycleHook<
556
- (ctx: Simplify<OnGlobalErrorContext>) => void
557
- >;
558
-
559
- /**
560
- * Called after the response is sent back to the client.
561
- */
562
- export type OnGlobalAfterResponseHook = LifeCycleHook<
563
- (ctx: Simplify<AfterResponseContext>) => void
564
- >;
565
-
566
- export type LifeCycleHooks = {
567
- onGlobalRequest?: OnGlobalRequestHook[];
568
- onTransform?: OnTransformHook[];
569
- onBeforeHandle?: OnBeforeHandleHook[];
570
- onAfterHandle?: OnAfterHandleHook[];
571
- onMapResponse?: OnMapResponseHook[];
572
- onGlobalError?: OnGlobalErrorHook[];
573
- onGlobalAfterResponse?: OnGlobalAfterResponseHook[];
574
- };
575
-
576
- export type LifeCycleHookName = keyof LifeCycleHooks;
577
-
578
- //
579
- // BASE TYPES
580
- //
581
-
582
- /**
583
- * Base data type associated with each app.
584
- */
585
- export type AppData = {
586
- exported: boolean;
587
- prefix: BasePrefix;
588
- ctx: BaseCtx;
589
- routes: BaseRoutes;
590
- };
591
-
592
- /**
593
- * Minimal data type that works with `AppData`.
594
- */
595
- export type DefaultAppData = {
596
- exported: false;
597
- prefix: "";
598
- ctx: {};
599
- routes: {};
600
- };
601
-
602
- /**
603
- * Minimal data type that matches `AppData["ctx"]`.
604
- */
605
- export type BaseCtx = Record<string, any>;
606
-
607
- /**
608
- * Minimal data type that matches `AppData["routes"]`.
609
- */
610
- export type BaseRoutes = {
611
- [method: string]: {
612
- [path: BasePath]: RouteDef;
613
- };
614
- };
615
-
616
- /**
617
- * Minimal data type that matches `AppData["routes"][method][path]`, containing information about the route.
618
- */
619
- export type RouteDef = Simplify<
620
- Omit<OpenAPI.Operation, "parameters" | "responses"> & {
621
- headers?: StandardSchemaV1<Record<string, any>>;
622
- params?: StandardSchemaV1<Record<string, any>>;
623
- query?: StandardSchemaV1<Record<string, any>>;
624
- body?: StandardSchemaV1;
625
- responses?: StandardSchemaV1 | Record<number, StandardSchemaV1>;
626
- }
627
- >;
628
-
629
- /**
630
- * Used for `TDef` when a route definition is not passed. Essentially removes type-safety from a route.
631
- */
632
- export type AnyDef = {
633
- headers: StandardSchemaV1<Record<string, string>>;
634
- params: StandardSchemaV1<Record<string, string>>;
635
- query: StandardSchemaV1<Record<string, string>>;
636
- body: StandardSchemaV1<any>;
637
- responses: any;
638
- };
639
-
640
- /**
641
- * Base type representing what strings can be passed as a `prefix` when creating an app.
642
- */
643
- export type BasePrefix = BasePath | "";
644
-
645
- /**
646
- * Base type representing what a route's string must look like.
647
- */
648
- export type BasePath = `/${string}`;
649
-
650
- //
651
- // CONTEXT OBJECTS
652
- //
653
-
654
- /**
655
- * `ctx` type used in the `onGlobalRequest` hook.
656
- */
657
- export type OnGlobalRequestContext<TCtx extends BaseCtx = {}> = TCtx & {
658
- request: Request;
659
- url: URL;
660
- path: string;
661
- method: string;
662
- set: Setter;
663
- };
664
-
665
- /**
666
- * `ctx` type used in the `onTransform` hook.
667
- */
668
- export type OnTransformContext<TCtx extends BaseCtx = {}> =
669
- OnGlobalRequestContext<TCtx> & {
670
- route: string;
671
- params?: Record<string, string>;
672
- query?: Record<string, string>;
673
- headers?: Record<string, string>;
674
- body?: any;
675
- };
676
-
677
- /**
678
- * `ctx` type used in the `onBeforeHandle` hook.
679
- */
680
- export type OnBeforeHandleContext<TCtx extends BaseCtx = {}> =
681
- OnTransformContext<TCtx>;
682
-
683
- /**
684
- * `ctx` type used in the `onAfterHandle` hook.
685
- */
686
- export type AfterHandleContext<TCtx extends BaseCtx = {}> =
687
- OnTransformContext<TCtx> & {
688
- response?: unknown;
689
- };
690
-
691
- /**
692
- * `ctx` type used in the `onMapResponse` hook.
693
- */
694
- export type OnMapResponseContext<TCtx extends BaseCtx = {}> =
695
- AfterHandleContext<TCtx> & {};
696
-
697
- /**
698
- * `ctx` type used in the `onGlobalError` hook.
699
- */
700
- export type OnGlobalErrorContext<TCtx extends BaseCtx = {}> =
701
- OnGlobalRequestContext<TCtx> &
702
- Partial<OnMapResponseContext> & { error: unknown };
703
-
704
- /**
705
- * `ctx` type used in the `onGlobalAfterResponse` hook.
706
- */
707
- export type AfterResponseContext<TCtx extends BaseCtx = {}> =
708
- OnGlobalRequestContext<TCtx> &
709
- Partial<OnMapResponseContext> & { response: Response };
710
-
711
- /**
712
- * Given an `AppData` type, return the type of it's `ctx`.
713
- */
714
- export type GetAppDataCtx<TAppData extends AppData> = TAppData extends {
715
- ctx: infer TCtx;
716
- }
717
- ? TCtx
718
- : never;
719
-
720
- export type StatusFn<TMap extends Record<any, any>> = TMap extends never
721
- ? never
722
- : <TStatus extends keyof TMap>(
723
- status: TStatus,
724
- body: StandardSchemaV1.InferInput<TMap[TStatus]>,
725
- ) => StatusResult;
726
-
727
- export type GetResponseStatusMap<TRouteDef extends RouteDef> =
728
- TRouteDef extends { responses: unknown }
729
- ? TRouteDef["responses"] extends symbol // is any check
730
- ? Record<number, StandardSchemaV1<any, any>>
731
- : TRouteDef["responses"] extends StandardSchemaV1
732
- ? { 200: TRouteDef["responses"] }
733
- : TRouteDef["responses"] extends Record<
734
- number | string,
735
- StandardSchemaV1
736
- >
737
- ? TRouteDef["responses"]
738
- : any
739
- : never;
740
-
741
- export type StatusResult = {
742
- [IsStatusResult]: true;
743
- status: number;
744
- body: unknown;
745
- };
746
-
747
- /**
748
- * Build the `ctx` type used for request handlers.
749
- */
750
- export type BuildHandlerContext<
751
- TAppData extends AppData,
752
- TPath extends BasePath,
753
- TRouteDef extends RouteDef,
754
- > = Simplify<
755
- Omit<OnBeforeHandleContext<GetAppDataCtx<TAppData>>, InputParams> & {
756
- route: TPath;
757
- } & GetRequestParamsOutputFromDef<TRouteDef> & {
758
- status: StatusFn<GetResponseStatusMap<TRouteDef>>;
759
- }
760
- >;
761
-
762
- //
763
- // MERGING OBJECTS
764
- //
765
-
766
- /**
767
- * Given two `App`s, merge their data to match the behavior of `TParent.use(TChild)`.
768
- */
769
- export type UseApp<TParent extends App, TChild extends App> = App<
770
- Simplify<UseAppData<GetAppData<TParent>, GetAppData<TChild>>>
771
- >;
772
-
773
- /**
774
- * Same as `UseApp`, but instead of app instances, it merges the `AppData` of each.
775
- */
776
- export type UseAppData<
777
- TParentData extends AppData,
778
- TChildData extends AppData,
779
- > = TChildData extends { exported: true }
780
- ? MergeAppData<
781
- TParentData,
782
- Pick<ApplyAppDataPrefix<TChildData>, "ctx" | "routes">
783
- >
784
- : MergeAppData<TParentData, Pick<ApplyAppDataPrefix<TChildData>, "routes">>;
785
-
786
- /**
787
- * Merge two `App` types together. See `MergeAppData` for details.
788
- */
789
- export type MergeApp<T1, T2> =
790
- T1 extends App<infer D1>
791
- ? T2 extends App<infer D2>
792
- ? App<Simplify<MergeAppData<D1, D2>>>
793
- : never
794
- : never;
795
-
796
- /**
797
- * Merge two `AppData` types together.
798
- * - `prefix`: The second app's prefix overrides the first if present.
799
- * - `ctx`: The second app's context gets merged with the first if present. Any
800
- * existing keys are overwritten to match the second app's context.
801
- * - `exported`: The second app's exported status overrides the first if
802
- * present.
803
- * - `routes`: See `MergeRoutes` for details.
804
- */
805
- export type MergeAppData<
806
- T1 extends AppData,
807
- T2 extends Partial<AppData>,
808
- > = Simplify<{
809
- prefix: T2["prefix"] extends string ? T2["prefix"] : T1["prefix"];
810
- ctx: T2["ctx"] extends BaseCtx
811
- ? Simplify<Spread<T1["ctx"], T2["ctx"]>>
812
- : T1["ctx"];
813
- exported: T2["exported"] extends boolean ? T2["exported"] : T1["exported"];
814
- routes: T2["routes"] extends BaseRoutes
815
- ? Simplify<MergeRoutes<T1["routes"], T2["routes"]>>
816
- : T1["routes"];
817
- }>;
818
-
819
- /**
820
- * Merges two route objects together, 2 levels deep. If the same method/path
821
- * combination exists in both apps, the second app's route overrides the first.
822
- */
823
- export type MergeRoutes<
824
- A extends Record<string, any>,
825
- B extends Record<string, any>,
826
- > = Simplify<Merge<A, B>>;
827
-
828
- //
829
- // APPLY PREFIX
830
- //
831
-
832
- /**
833
- * Given an app and a new prefix, return a new app type with app's original
834
- * prefix applied to each route, and with the new prefix stored in the
835
- * `AppData`.
836
- */
837
- export type ApplyAppPrefix<
838
- TApp extends App,
839
- TNewPrefix extends BasePrefix = "",
840
- > = App<Simplify<ApplyAppDataPrefix<GetAppData<TApp>, TNewPrefix>>>;
841
-
842
- /**
843
- * Same as `ApplyAppPrefix`, but at the `AppData` level.
844
- */
845
- export type ApplyAppDataPrefix<
846
- TAppData extends AppData,
847
- TNewPrefix extends BasePrefix = "",
848
- > = {
849
- ctx: TAppData["ctx"];
850
- exported: TAppData["exported"];
851
- prefix: TNewPrefix;
852
- routes: TAppData["prefix"] extends BasePath
853
- ? {
854
- [TMethod in keyof TAppData["routes"]]: Simplify<
855
- PrefixObjectKeys<TAppData["prefix"], TAppData["routes"][TMethod]>
856
- >;
857
- }
858
- : TAppData["routes"];
859
- };
860
-
861
- //
862
- // SCHEMA CONVERSION
863
- //
864
-
865
- /**
866
- * Given a route definition, return the input types of all the params.
867
- */
868
- export type GetRequestParamsInputFromDef<TRouteDef extends RouteDef> =
869
- TRouteDef extends AnyDef
870
- ? {
871
- headers?: Record<string, string>;
872
- params?: Record<string, string>;
873
- query?: Record<string, string>;
874
- body?: any;
875
- }
876
- : Simplify<{
877
- [key in keyof GetDefParams<TRouteDef>]: TRouteDef[key] extends StandardSchemaV1
878
- ? StandardSchemaV1.InferInput<TRouteDef[key]>
879
- : never;
880
- }>;
881
-
882
- /**
883
- * Given a set of routes, a method, and a route, return the input types of all
884
- * the schemas in the route definition.
885
- */
886
- export type GetRequestParamsInput<
887
- TRoutes extends BaseRoutes,
888
- TMethod extends keyof TRoutes,
889
- TRoute extends keyof TRoutes[TMethod],
890
- > = TRoute extends BasePath
891
- ? GetRequestParamsInputFromDef<TRoutes[TMethod][TRoute]>
892
- : never;
893
-
894
- /**
895
- * Given a route definition, return the input type of the response schema.
896
- */
897
- export type GetResponseInputFromDef<TRouteDef extends RouteDef> =
898
- TRouteDef["responses"] extends undefined
899
- ? undefined
900
- : TRouteDef["responses"] extends StandardSchemaV1
901
- ? StandardSchemaV1.InferInput<TRouteDef["responses"]>
902
- : never;
903
-
904
- /**
905
- * Given a set of routes, a method, and a route, return the input type of the
906
- * response schema in the route definition.
907
- */
908
- export type GetResponseInput<
909
- TRoutes extends BaseRoutes,
910
- TMethod extends keyof TRoutes,
911
- TPath extends keyof TRoutes[TMethod],
912
- > = TPath extends BasePath
913
- ? GetResponseInputFromDef<TRoutes[TMethod][TPath]>
914
- : never;
915
-
916
- /**
917
- * Helper type for converting a schema or object containing schemas to their
918
- * output types.
919
- */
920
- type ToStandardSchemaOutputs<T> = T extends StandardSchemaV1
921
- ? StandardSchemaV1.InferOutput<T>
922
- : T extends { [key in keyof T]: any }
923
- ? { [key in keyof T]: ToStandardSchemaOutputs<T[key]> }
924
- : never;
925
-
926
- /**
927
- * Given a route definition, return the output type of the param schemas.
928
- */
929
- export type GetRequestParamsOutputFromDef<TRouteDef extends RouteDef> =
930
- ToStandardSchemaOutputs<GetDefParams<TRouteDef>>;
931
-
932
- /**
933
- * Given a set of routes, a method, and a route, return the output type of the
934
- * param schemas.
935
- */
936
- export type GetRequestParamsOutput<
937
- TRoutes extends BaseRoutes,
938
- TMethod extends keyof TRoutes,
939
- TRoute extends keyof TRoutes[TMethod],
940
- > = TRoute extends BasePath
941
- ? GetRequestParamsOutputFromDef<TRoutes[TMethod][TRoute]>
942
- : never;
943
-
944
- type SuccessStatusCodes =
945
- | 200
946
- | HttpStatus.Ok
947
- | 201
948
- | HttpStatus.Created
949
- | 202
950
- | HttpStatus.Accepted
951
- | 203
952
- | HttpStatus.NonAuthoritativeInformation
953
- | 204
954
- | HttpStatus.NoContent
955
- | 205
956
- | HttpStatus.ResetContent
957
- | 206
958
- | HttpStatus.PartialContent
959
- | 207
960
- | HttpStatus.MultiStatus
961
- | 208
962
- | HttpStatus.AlreadyReported
963
- | 226
964
- | HttpStatus.ImUsed;
965
-
966
- /**
967
- * Given a `RouteDef`, return a union of all possible handler return values.
968
- *
969
- * If `responses` is defined, it will be a discriminated union of objects
970
- * containing the status and body.
971
- *
972
- * If only `response` is defined, it will be the output of that schema.
973
- *
974
- * If neither is defined, it will be `void`.
975
- */
976
- export type GetResponseOutputFromDef<TRouteDef extends RouteDef> =
977
- TRouteDef["responses"] extends undefined
978
- ? undefined
979
- : TRouteDef["responses"] extends StandardSchemaV1
980
- ? StandardSchemaV1.InferOutput<TRouteDef["responses"]>
981
- : {
982
- [key in SuccessStatusCodes &
983
- keyof TRouteDef["responses"]]: TRouteDef["responses"][key] extends StandardSchemaV1
984
- ? StandardSchemaV1.InferOutput<TRouteDef["responses"][key]>
985
- : unknown;
986
- }[SuccessStatusCodes & keyof TRouteDef["responses"]];
987
-
988
- /**
989
- * Given a set of routes, a method, and a route, return the output type of the
990
- * response schema.
991
- */
992
- export type GetResponseOutput<
993
- TRoutes extends BaseRoutes,
994
- TMethod extends keyof TRoutes,
995
- TPath extends keyof TRoutes[TMethod],
996
- > = TPath extends BasePath
997
- ? GetResponseOutputFromDef<TRoutes[TMethod][TPath]>
998
- : 1;
999
-
1000
- type InputParams = "headers" | "params" | "query" | "body";
1001
-
1002
- /**
1003
- * Given a route definition, return an object with only the input parameeters.
1004
- */
1005
- type GetDefParams<TRouteDef extends RouteDef> = {
1006
- [key in InputParams & keyof TRouteDef]: TRouteDef[key];
1007
- };
1008
-
1009
- //
1010
- // SCHEMA ADAPTER
1011
- //
1012
-
1013
- /**
1014
- * To generate open API docs, Zeta needs to know how process and extract
1015
- * some information from your schema. This adapter is responsible for
1016
- * providing additional functions for parsing your schema.
1017
- */
1018
- export interface SchemaAdapter {
1019
- /**
1020
- * Convert a standard schema definition to it's JSON schema.
1021
- * @param schema The schema to convert.
1022
- * @returns The JSON schema.
1023
- */
1024
- toJsonSchema: (schema: any) => any;
1025
- getMeta: (schema: StandardSchemaV1) => Record<string, any> | undefined;
1026
- }
1027
-
1028
- //
1029
- // TRANSPORTS
1030
- //
1031
-
1032
- export interface Transport {
1033
- listen: (port: number, fetch: ServerSideFetch, cb?: () => void) => void;
1034
- }
1035
-
1036
- //
1037
- // SETTER
1038
- //
1039
-
1040
- /**
1041
- * Basic object type used to store custom status and headers set while handling the request.
1042
- */
1043
- export interface Setter {
1044
- /**
1045
- * Set this value to change the status code returned.
1046
- */
1047
- status: number;
1048
- /**
1049
- * Set a value on this header to change which headers are sent in the response.
1050
- */
1051
- headers: Record<string, string>;
1052
- }
1053
-
1054
- //
1055
- // GENERAL UTILS
1056
- //
1057
-
1058
- /**
1059
- * Given a union of objects, combine them into a single object that's easy to read.
1060
- */
1061
- export type Simplify<T> = T extends { [key: string]: any }
1062
- ? { [K in keyof T]: T[K] }
1063
- : T;
1064
-
1065
- /**
1066
- * Returns either a Promise of a type or just the type itself.
1067
- */
1068
- export type MaybePromise<T> = Promise<T> | T;
1069
-
1070
- /**
1071
- * A function that, given a request, returns a response. This type is compliant with WinterCG.
1072
- */
1073
- export type ServerSideFetch = (request: Request) => MaybePromise<Response>;
1074
-
1075
- /**
1076
- * Apply a string prefix to all the keys of an object.
1077
- */
1078
- export type PrefixObjectKeys<
1079
- TPrefix extends string,
1080
- TObject extends Record<string, unknown>,
1081
- > = {
1082
- [K in keyof TObject as `${TPrefix}${string & K extends "/" ? "" : string & K}`]: TObject[K];
1083
- };
1084
-
1085
- /**
1086
- * A helper type that models a single-level object spread: { ...L, ...R }
1087
- * It takes all properties from R, and all properties from L that are not in R.
1088
- */
1089
- type Spread<L, R> = Omit<L, keyof R> & R;
1090
-
1091
- /**
1092
- * Merges two objects, A and B, two levels deep.
1093
- *
1094
- * It combines the keys from both A and B.
1095
- * - If a key exists only in A or only in B, it's carried over.
1096
- * - If a key exists in *both* A and B, it recursively merges their
1097
- * values using a single-level spread (`Spread<A[K], B[K]>`).
1098
- * This ensures properties from B's inner objects overwrite those from A's.
1099
- */
1100
- export type Merge<A, B> = Omit<A, keyof B> & {
1101
- [K in keyof B]: K extends keyof A ? Simplify<Spread<A[K], B[K]>> : B[K];
1102
- };