express-zod-api 26.3.1 → 26.3.2
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/CHANGELOG.md +4 -0
- package/dist/index.d.ts +329 -137
- package/dist/index.js +1 -1
- package/package.json +4 -3
package/CHANGELOG.md
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -14,11 +14,10 @@ import compression from "compression";
|
|
|
14
14
|
import * as express_fileupload0 from "express-fileupload";
|
|
15
15
|
import fileUpload from "express-fileupload";
|
|
16
16
|
import { ListenOptions } from "node:net";
|
|
17
|
-
import * as
|
|
18
|
-
import * as
|
|
17
|
+
import * as express_serve_static_core0 from "express-serve-static-core";
|
|
18
|
+
import * as qs0 from "qs";
|
|
19
19
|
import ts from "typescript";
|
|
20
20
|
import * as zod_v4_core0 from "zod/v4/core";
|
|
21
|
-
|
|
22
21
|
//#region src/method.d.ts
|
|
23
22
|
declare const methods: ("get" | "post" | "put" | "delete" | "patch")[];
|
|
24
23
|
declare const clientMethods: ("get" | "post" | "put" | "delete" | "patch" | "head")[];
|
|
@@ -56,7 +55,7 @@ type EmptySchema = typeof emptySchema;
|
|
|
56
55
|
type EmptyObject = z.output<EmptySchema>;
|
|
57
56
|
type FlatObject = Record<string, unknown>;
|
|
58
57
|
/** @link https://stackoverflow.com/a/65492934 */
|
|
59
|
-
type NoNever<T
|
|
58
|
+
type NoNever<T, F> = [T] extends [never] ? F : T;
|
|
60
59
|
/**
|
|
61
60
|
* @desc Using module augmentation approach you can specify tags as the keys of this interface
|
|
62
61
|
* @example declare module "express-zod-api" { interface TagOverrides { users: unknown } }
|
|
@@ -119,12 +118,7 @@ interface ProfilerOptions {
|
|
|
119
118
|
declare class BuiltinLogger implements AbstractLogger {
|
|
120
119
|
protected readonly config: BuiltinLoggerConfig;
|
|
121
120
|
/** @example new BuiltinLogger({ level: "debug", color: true, depth: 4 }) */
|
|
122
|
-
constructor({
|
|
123
|
-
color,
|
|
124
|
-
level,
|
|
125
|
-
depth,
|
|
126
|
-
ctx
|
|
127
|
-
}?: Partial<BuiltinLoggerConfig>);
|
|
121
|
+
constructor({ color, level, depth, ctx }?: Partial<BuiltinLoggerConfig>);
|
|
128
122
|
protected format(subject: unknown): string;
|
|
129
123
|
protected print(method: Severity, message: string, meta?: unknown): void;
|
|
130
124
|
debug(message: string, meta?: unknown): void;
|
|
@@ -149,18 +143,25 @@ type Base$1 = object & {
|
|
|
149
143
|
/** @desc The type allowed on the top level of Middlewares and Endpoints */
|
|
150
144
|
type IOSchema = z.ZodType<Base$1>;
|
|
151
145
|
/** EndpointsFactory schema extended type when adding a Middleware */
|
|
152
|
-
type Extension<Current extends IOSchema | undefined, Inc extends IOSchema | undefined> = Current extends IOSchema
|
|
146
|
+
type Extension<Current extends IOSchema | undefined, Inc extends IOSchema | undefined> = Current extends IOSchema
|
|
147
|
+
? Inc extends IOSchema
|
|
148
|
+
? z.ZodIntersection<Current, Inc>
|
|
149
|
+
: Current
|
|
150
|
+
: Inc;
|
|
153
151
|
/** The Endpoint input schema type, condition wrapped into schema to make it z.output-compatible */
|
|
154
|
-
type FinalInputSchema<FIN extends IOSchema | undefined, BIN extends IOSchema> = z.ZodIntersection<
|
|
152
|
+
type FinalInputSchema<FIN extends IOSchema | undefined, BIN extends IOSchema> = z.ZodIntersection<
|
|
153
|
+
FIN extends IOSchema ? FIN : BIN,
|
|
154
|
+
BIN
|
|
155
|
+
>;
|
|
155
156
|
//#endregion
|
|
156
157
|
//#region src/logical-container.d.ts
|
|
157
|
-
type LogicalOr<T
|
|
158
|
-
or: T
|
|
158
|
+
type LogicalOr<T> = {
|
|
159
|
+
or: T[];
|
|
159
160
|
};
|
|
160
|
-
type LogicalAnd<T
|
|
161
|
-
and: T
|
|
161
|
+
type LogicalAnd<T> = {
|
|
162
|
+
and: T[];
|
|
162
163
|
};
|
|
163
|
-
type LogicalContainer<T
|
|
164
|
+
type LogicalContainer<T> = LogicalOr<T | LogicalAnd<T>> | LogicalAnd<T | LogicalOr<T>> | T;
|
|
164
165
|
//#endregion
|
|
165
166
|
//#region src/security.d.ts
|
|
166
167
|
interface BasicSecurity {
|
|
@@ -170,9 +171,9 @@ interface BearerSecurity {
|
|
|
170
171
|
type: "bearer";
|
|
171
172
|
format?: "JWT" | string;
|
|
172
173
|
}
|
|
173
|
-
interface InputSecurity<K
|
|
174
|
+
interface InputSecurity<K extends string> {
|
|
174
175
|
type: "input";
|
|
175
|
-
name: K
|
|
176
|
+
name: K;
|
|
176
177
|
}
|
|
177
178
|
interface HeaderSecurity {
|
|
178
179
|
type: "header";
|
|
@@ -205,9 +206,9 @@ interface RefreshUrl {
|
|
|
205
206
|
/** @desc The URL to be used for obtaining refresh tokens. Can be relative to the API server URL. */
|
|
206
207
|
refreshUrl?: string;
|
|
207
208
|
}
|
|
208
|
-
interface Scopes<K
|
|
209
|
+
interface Scopes<K extends string> {
|
|
209
210
|
/** @desc The available scopes for the OAuth2 security and their short descriptions. Optional. */
|
|
210
|
-
scopes?: Record<K
|
|
211
|
+
scopes?: Record<K, string>;
|
|
211
212
|
}
|
|
212
213
|
type AuthCodeFlow<S extends string> = AuthUrl & TokenUrl & RefreshUrl & Scopes<S>;
|
|
213
214
|
type ImplicitFlow<S extends string> = AuthUrl & RefreshUrl & Scopes<S>;
|
|
@@ -234,7 +235,14 @@ interface OAuth2Security<S extends string> {
|
|
|
234
235
|
* @param K is an optional input field used by InputSecurity
|
|
235
236
|
* @param S is an optional union of scopes used by OAuth2Security
|
|
236
237
|
* */
|
|
237
|
-
type Security<K
|
|
238
|
+
type Security<K extends string = string, S extends string = string> =
|
|
239
|
+
| BasicSecurity
|
|
240
|
+
| BearerSecurity
|
|
241
|
+
| InputSecurity<K>
|
|
242
|
+
| HeaderSecurity
|
|
243
|
+
| CookieSecurity
|
|
244
|
+
| OpenIdSecurity
|
|
245
|
+
| OAuth2Security<S>;
|
|
238
246
|
//#endregion
|
|
239
247
|
//#region src/middleware.d.ts
|
|
240
248
|
type Handler$2<IN, CTX, RET> = (params: {
|
|
@@ -261,12 +269,17 @@ declare abstract class AbstractMiddleware {
|
|
|
261
269
|
logger: ActualLogger;
|
|
262
270
|
}): Promise<FlatObject>;
|
|
263
271
|
}
|
|
264
|
-
declare class Middleware<
|
|
272
|
+
declare class Middleware<
|
|
273
|
+
CTX extends FlatObject,
|
|
274
|
+
RET extends FlatObject,
|
|
275
|
+
SCO extends string,
|
|
276
|
+
IN extends IOSchema | undefined = undefined,
|
|
277
|
+
> extends AbstractMiddleware {
|
|
265
278
|
#private;
|
|
266
279
|
constructor({
|
|
267
280
|
input,
|
|
268
281
|
security,
|
|
269
|
-
handler
|
|
282
|
+
handler,
|
|
270
283
|
}: {
|
|
271
284
|
/**
|
|
272
285
|
* @desc Input schema of the Middleware, combining properties from all the enabled input sources
|
|
@@ -291,25 +304,34 @@ declare class Middleware<CTX extends FlatObject, RET extends FlatObject, SCO ext
|
|
|
291
304
|
logger: ActualLogger;
|
|
292
305
|
}): Promise<RET>;
|
|
293
306
|
}
|
|
294
|
-
declare class ExpressMiddleware<R extends Request, S extends Response, RET extends FlatObject> extends Middleware<
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
307
|
+
declare class ExpressMiddleware<R extends Request, S extends Response, RET extends FlatObject> extends Middleware<
|
|
308
|
+
FlatObject,
|
|
309
|
+
RET,
|
|
310
|
+
string
|
|
311
|
+
> {
|
|
312
|
+
constructor(
|
|
313
|
+
nativeMw: (request: R, response: S, next: NextFunction) => any,
|
|
314
|
+
{
|
|
315
|
+
provider,
|
|
316
|
+
transformer,
|
|
317
|
+
}?: {
|
|
318
|
+
provider?: (request: R, response: S) => RET | Promise<RET>;
|
|
319
|
+
transformer?: (err: Error) => Error;
|
|
320
|
+
},
|
|
321
|
+
);
|
|
302
322
|
}
|
|
303
323
|
//#endregion
|
|
304
324
|
//#region src/result-helpers.d.ts
|
|
305
325
|
type ResultSchema<R extends Result> = R extends Result<infer S> ? S : never;
|
|
306
|
-
type DiscriminatedResult =
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
326
|
+
type DiscriminatedResult =
|
|
327
|
+
| {
|
|
328
|
+
output: FlatObject;
|
|
329
|
+
error: null;
|
|
330
|
+
}
|
|
331
|
+
| {
|
|
332
|
+
output: null;
|
|
333
|
+
error: Error;
|
|
334
|
+
};
|
|
313
335
|
/**
|
|
314
336
|
* @example InputValidationError —> BadRequest(400)
|
|
315
337
|
* @example Error —> InternalServerError(500)
|
|
@@ -317,15 +339,17 @@ type DiscriminatedResult = {
|
|
|
317
339
|
declare const ensureHttpError: (error: Error) => HttpError;
|
|
318
340
|
//#endregion
|
|
319
341
|
//#region src/result-handler.d.ts
|
|
320
|
-
type Handler$1<RES = unknown> = (
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
342
|
+
type Handler$1<RES = unknown> = (
|
|
343
|
+
params: DiscriminatedResult & {
|
|
344
|
+
/** null in case of failure to parse or to find the matching endpoint (error: not found) */
|
|
345
|
+
input: FlatObject | null;
|
|
346
|
+
/** can be empty: check presence of the required property using "in" operator */
|
|
347
|
+
ctx: FlatObject;
|
|
348
|
+
request: Request;
|
|
349
|
+
response: Response<RES>;
|
|
350
|
+
logger: ActualLogger;
|
|
351
|
+
},
|
|
352
|
+
) => void | Promise<void>;
|
|
329
353
|
type Result<S extends z.ZodType = z.ZodType> = S | ApiResponse<S> | ApiResponse<S>[];
|
|
330
354
|
type LazyResult<R extends Result, A extends unknown[] = []> = (...args: A) => R;
|
|
331
355
|
declare abstract class AbstractResultHandler {
|
|
@@ -344,24 +368,39 @@ declare class ResultHandler<POS extends Result, NEG extends Result> extends Abst
|
|
|
344
368
|
handler: Handler$1<z.output<ResultSchema<POS> | ResultSchema<NEG>>>;
|
|
345
369
|
});
|
|
346
370
|
}
|
|
347
|
-
declare const defaultResultHandler: ResultHandler<
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
371
|
+
declare const defaultResultHandler: ResultHandler<
|
|
372
|
+
z.ZodObject<
|
|
373
|
+
{
|
|
374
|
+
status: z.ZodLiteral<"success">;
|
|
375
|
+
data: IOSchema;
|
|
376
|
+
},
|
|
377
|
+
z.core.$strip
|
|
378
|
+
>,
|
|
379
|
+
z.ZodObject<
|
|
380
|
+
{
|
|
381
|
+
status: z.ZodLiteral<"error">;
|
|
382
|
+
error: z.ZodObject<
|
|
383
|
+
{
|
|
384
|
+
message: z.ZodString;
|
|
385
|
+
},
|
|
386
|
+
z.core.$strip
|
|
387
|
+
>;
|
|
388
|
+
},
|
|
389
|
+
z.core.$strip
|
|
390
|
+
>
|
|
391
|
+
>;
|
|
356
392
|
/**
|
|
357
393
|
* @deprecated Resist the urge of using it: this handler is designed only to simplify the migration of legacy APIs.
|
|
358
394
|
* @desc Responding with array is a bad practice keeping your endpoints from evolving without breaking changes.
|
|
359
395
|
* @desc This handler expects your endpoint to have the property 'items' in the output object schema
|
|
360
396
|
* */
|
|
361
|
-
declare const arrayResultHandler: ResultHandler<
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
397
|
+
declare const arrayResultHandler: ResultHandler<
|
|
398
|
+
z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>,
|
|
399
|
+
{
|
|
400
|
+
schema: z.ZodString;
|
|
401
|
+
mimeType: string;
|
|
402
|
+
}
|
|
403
|
+
>;
|
|
365
404
|
//#endregion
|
|
366
405
|
//#region src/serve-static.d.ts
|
|
367
406
|
type OriginalStatic = typeof express.static;
|
|
@@ -429,7 +468,7 @@ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, CTX extends Fl
|
|
|
429
468
|
request,
|
|
430
469
|
response,
|
|
431
470
|
logger,
|
|
432
|
-
config
|
|
471
|
+
config,
|
|
433
472
|
}: {
|
|
434
473
|
request: Request;
|
|
435
474
|
response: Response;
|
|
@@ -449,10 +488,7 @@ type HeadersProvider = (params: {
|
|
|
449
488
|
endpoint: AbstractEndpoint;
|
|
450
489
|
logger: ActualLogger;
|
|
451
490
|
}) => Headers | Promise<Headers>;
|
|
452
|
-
type ChildLoggerProvider = (params: {
|
|
453
|
-
request: Request;
|
|
454
|
-
parent: ActualLogger;
|
|
455
|
-
}) => ActualLogger | Promise<ActualLogger>;
|
|
491
|
+
type ChildLoggerProvider = (params: { request: Request; parent: ActualLogger }) => ActualLogger | Promise<ActualLogger>;
|
|
456
492
|
type LogAccess = (request: Request, logger: ActualLogger) => void;
|
|
457
493
|
interface CommonConfig {
|
|
458
494
|
/**
|
|
@@ -512,11 +548,19 @@ interface CommonConfig {
|
|
|
512
548
|
*/
|
|
513
549
|
inputSources?: Partial<InputSources>;
|
|
514
550
|
}
|
|
515
|
-
type BeforeUpload = (params: {
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
551
|
+
type BeforeUpload = (params: { request: Request; logger: ActualLogger }) => void | Promise<void>;
|
|
552
|
+
type UploadOptions = Pick<
|
|
553
|
+
fileUpload.Options,
|
|
554
|
+
| "createParentPath"
|
|
555
|
+
| "uriDecodeFileNames"
|
|
556
|
+
| "safeFileNames"
|
|
557
|
+
| "preserveExtension"
|
|
558
|
+
| "useTempFiles"
|
|
559
|
+
| "tempFileDir"
|
|
560
|
+
| "debug"
|
|
561
|
+
| "uploadTimeout"
|
|
562
|
+
| "limits"
|
|
563
|
+
> & {
|
|
520
564
|
/**
|
|
521
565
|
* @desc The error to throw when the file exceeds the configured fileSize limit (handled by errorHandler).
|
|
522
566
|
* @see limits
|
|
@@ -530,7 +574,10 @@ type UploadOptions = Pick<fileUpload.Options, "createParentPath" | "uriDecodeFil
|
|
|
530
574
|
* */
|
|
531
575
|
beforeUpload?: BeforeUpload;
|
|
532
576
|
};
|
|
533
|
-
type CompressionOptions = Pick<
|
|
577
|
+
type CompressionOptions = Pick<
|
|
578
|
+
compression.CompressionOptions,
|
|
579
|
+
"threshold" | "level" | "strategy" | "chunkSize" | "memLevel"
|
|
580
|
+
>;
|
|
534
581
|
interface GracefulOptions {
|
|
535
582
|
/**
|
|
536
583
|
* @desc Time given to drain ongoing requests before closing the server.
|
|
@@ -626,7 +673,13 @@ declare function createConfig(config: ServerConfig): ServerConfig;
|
|
|
626
673
|
declare function createConfig(config: AppConfig): AppConfig;
|
|
627
674
|
//#endregion
|
|
628
675
|
//#region src/endpoints-factory.d.ts
|
|
629
|
-
interface BuildProps<
|
|
676
|
+
interface BuildProps<
|
|
677
|
+
IN extends IOSchema,
|
|
678
|
+
OUT extends IOSchema | z.ZodVoid,
|
|
679
|
+
MIN extends IOSchema | undefined,
|
|
680
|
+
CTX extends FlatObject,
|
|
681
|
+
SCO extends string,
|
|
682
|
+
> {
|
|
630
683
|
/**
|
|
631
684
|
* @desc Input schema of the Endpoint, combining properties from all the enabled input sources (path params, headers)
|
|
632
685
|
* @default z.object({})
|
|
@@ -661,20 +714,34 @@ interface BuildProps<IN extends IOSchema, OUT extends IOSchema | z.ZodVoid, MIN
|
|
|
661
714
|
/** @desc Marks the operation deprecated in the generated Documentation */
|
|
662
715
|
deprecated?: boolean;
|
|
663
716
|
}
|
|
664
|
-
|
|
665
|
-
|
|
717
|
+
declare class EndpointsFactory<
|
|
718
|
+
IN extends IOSchema | undefined = undefined,
|
|
719
|
+
CTX extends FlatObject = EmptyObject,
|
|
720
|
+
SCO extends string = string,
|
|
721
|
+
> {
|
|
666
722
|
#private;
|
|
667
723
|
protected resultHandler: AbstractResultHandler;
|
|
668
724
|
protected schema: IN;
|
|
669
725
|
protected middlewares: AbstractMiddleware[];
|
|
670
726
|
constructor(resultHandler: AbstractResultHandler);
|
|
671
|
-
addMiddleware<RET extends FlatObject, ASCO extends string, AIN extends IOSchema | undefined = undefined>(
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
727
|
+
addMiddleware<RET extends FlatObject, ASCO extends string, AIN extends IOSchema | undefined = undefined>(
|
|
728
|
+
subject: Middleware<CTX, RET, ASCO, AIN> | ConstructorParameters<typeof Middleware<CTX, RET, ASCO, AIN>>[0],
|
|
729
|
+
): EndpointsFactory<Extension<IN, AIN>, (CTX extends Record<string, never> ? RET : CTX) & RET, SCO & ASCO>;
|
|
730
|
+
use: <R extends Request, S extends Response, AOUT extends FlatObject = Record<string, never>>(
|
|
731
|
+
nativeMw: (request: R, response: S, next: express0.NextFunction) => any,
|
|
732
|
+
params_1?:
|
|
733
|
+
| {
|
|
734
|
+
provider?: ((request: R, response: S) => AOUT | Promise<AOUT>) | undefined;
|
|
735
|
+
transformer?: (err: Error) => Error;
|
|
736
|
+
}
|
|
737
|
+
| undefined,
|
|
738
|
+
) => EndpointsFactory<Extension<IN, undefined>, (CTX extends Record<string, never> ? AOUT : CTX) & AOUT, SCO>;
|
|
739
|
+
addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(
|
|
740
|
+
...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>
|
|
741
|
+
): EndpointsFactory<Extension<IN, undefined>, (CTX extends Record<string, never> ? AOUT : CTX) & AOUT, SCO>;
|
|
742
|
+
addContext<RET extends FlatObject>(
|
|
743
|
+
getContext: () => Promise<RET>,
|
|
744
|
+
): EndpointsFactory<Extension<IN, undefined>, (CTX extends Record<string, never> ? RET : CTX) & RET, SCO>;
|
|
678
745
|
build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({
|
|
679
746
|
input,
|
|
680
747
|
output: outputSchema,
|
|
@@ -688,7 +755,11 @@ declare class EndpointsFactory<IN extends IOSchema | undefined = undefined, CTX
|
|
|
688
755
|
buildVoid<BIN extends IOSchema = EmptySchema>({
|
|
689
756
|
handler,
|
|
690
757
|
...rest
|
|
691
|
-
}: Omit<BuildProps<BIN, z.ZodVoid, IN, CTX, SCO>, "output">): Endpoint<
|
|
758
|
+
}: Omit<BuildProps<BIN, z.ZodVoid, IN, CTX, SCO>, "output">): Endpoint<
|
|
759
|
+
FinalInputSchema<IN, BIN>,
|
|
760
|
+
z.ZodObject<{}, z.core.$strip>,
|
|
761
|
+
CTX
|
|
762
|
+
>;
|
|
692
763
|
}
|
|
693
764
|
declare const defaultEndpointsFactory: EndpointsFactory<undefined, Record<string, never>, string>;
|
|
694
765
|
/**
|
|
@@ -699,14 +770,29 @@ declare const defaultEndpointsFactory: EndpointsFactory<undefined, Record<string
|
|
|
699
770
|
declare const arrayEndpointsFactory: EndpointsFactory<undefined, Record<string, never>, string>;
|
|
700
771
|
//#endregion
|
|
701
772
|
//#region src/server.d.ts
|
|
702
|
-
declare const attachRouting: (
|
|
703
|
-
|
|
773
|
+
declare const attachRouting: (
|
|
774
|
+
config: AppConfig,
|
|
775
|
+
routing: Routing,
|
|
776
|
+
) => {
|
|
777
|
+
notFoundHandler: express.RequestHandler<
|
|
778
|
+
express_serve_static_core0.ParamsDictionary,
|
|
779
|
+
any,
|
|
780
|
+
any,
|
|
781
|
+
qs0.ParsedQs,
|
|
782
|
+
Record<string, any>
|
|
783
|
+
>;
|
|
704
784
|
logger: AbstractLogger | BuiltinLogger;
|
|
705
785
|
};
|
|
706
|
-
declare const createServer: (
|
|
707
|
-
|
|
786
|
+
declare const createServer: (
|
|
787
|
+
config: ServerConfig,
|
|
788
|
+
routing: Routing,
|
|
789
|
+
) => Promise<{
|
|
790
|
+
app: express_serve_static_core0.Express;
|
|
708
791
|
logger: AbstractLogger | BuiltinLogger;
|
|
709
|
-
servers: (
|
|
792
|
+
servers: (
|
|
793
|
+
| http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>
|
|
794
|
+
| https.Server<typeof http.IncomingMessage, typeof http.ServerResponse>
|
|
795
|
+
)[];
|
|
710
796
|
}>;
|
|
711
797
|
//#endregion
|
|
712
798
|
//#region src/documentation-helpers.d.ts
|
|
@@ -718,24 +804,37 @@ interface ReqResCommons {
|
|
|
718
804
|
interface OpenAPIContext extends ReqResCommons {
|
|
719
805
|
isResponse: boolean;
|
|
720
806
|
}
|
|
721
|
-
type Depicter = (
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
807
|
+
type Depicter = (
|
|
808
|
+
zodCtx: {
|
|
809
|
+
zodSchema: z.core.$ZodType;
|
|
810
|
+
jsonSchema: z.core.JSONSchema.BaseSchema;
|
|
811
|
+
},
|
|
812
|
+
oasCtx: OpenAPIContext,
|
|
813
|
+
) => z.core.JSONSchema.BaseSchema | SchemaObject;
|
|
725
814
|
/** @desc Using defaultIsHeader when returns null or undefined */
|
|
726
815
|
type IsHeader = (name: string, method: ClientMethod, path: string) => boolean | null | undefined;
|
|
727
816
|
type BrandHandling = Record<string | symbol, Depicter>;
|
|
728
|
-
declare const depictTags: (
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
817
|
+
declare const depictTags: (
|
|
818
|
+
tags: Partial<
|
|
819
|
+
Record<
|
|
820
|
+
Tag,
|
|
821
|
+
| string
|
|
822
|
+
| {
|
|
823
|
+
description: string;
|
|
824
|
+
url?: string;
|
|
825
|
+
}
|
|
826
|
+
>
|
|
827
|
+
>,
|
|
828
|
+
) => TagObject[];
|
|
732
829
|
//#endregion
|
|
733
830
|
//#region src/documentation.d.ts
|
|
734
831
|
type Component = "positiveResponse" | "negativeResponse" | "requestParameter" | "requestBody";
|
|
735
832
|
/** @desc user defined function that creates a component description from its properties */
|
|
736
|
-
type Descriptor = (
|
|
737
|
-
|
|
738
|
-
|
|
833
|
+
type Descriptor = (
|
|
834
|
+
props: Record<"method" | "path" | "operationId", string> & {
|
|
835
|
+
statusCode?: number;
|
|
836
|
+
},
|
|
837
|
+
) => string;
|
|
739
838
|
interface DocumentationParams {
|
|
740
839
|
title: string;
|
|
741
840
|
version: string;
|
|
@@ -792,7 +891,7 @@ declare class Documentation extends OpenApiBuilder {
|
|
|
792
891
|
isHeader,
|
|
793
892
|
hasSummaryFromDescription,
|
|
794
893
|
hasHeadMethod,
|
|
795
|
-
composition
|
|
894
|
+
composition,
|
|
796
895
|
}: DocumentationParams);
|
|
797
896
|
}
|
|
798
897
|
//#endregion
|
|
@@ -812,11 +911,7 @@ declare class RoutingError extends Error {
|
|
|
812
911
|
declare class DocumentationError extends Error {
|
|
813
912
|
name: string;
|
|
814
913
|
readonly cause: string;
|
|
815
|
-
constructor(message: string, {
|
|
816
|
-
method,
|
|
817
|
-
path,
|
|
818
|
-
isResponse
|
|
819
|
-
}: Pick<OpenAPIContext, "path" | "method" | "isResponse">);
|
|
914
|
+
constructor(message: string, { method, path, isResponse }: Pick<OpenAPIContext, "path" | "method" | "isResponse">);
|
|
820
915
|
}
|
|
821
916
|
/** @desc An error related to the input and output schemas declaration */
|
|
822
917
|
declare class IOSchemaError extends Error {
|
|
@@ -869,11 +964,14 @@ declare const testEndpoint: <LOG extends FlatObject, REQ extends RequestOptions>
|
|
|
869
964
|
/** @desc The endpoint to test */
|
|
870
965
|
endpoint: AbstractEndpoint;
|
|
871
966
|
}) => Promise<{
|
|
872
|
-
requestMock: node_mocks_http0.MockRequest<
|
|
967
|
+
requestMock: node_mocks_http0.MockRequest<
|
|
968
|
+
Request<express_serve_static_core0.ParamsDictionary, any, any, qs0.ParsedQs, Record<string, any>> & REQ
|
|
969
|
+
>;
|
|
873
970
|
responseMock: node_mocks_http0.MockResponse<Response<any, Record<string, any>>>;
|
|
874
|
-
loggerMock: AbstractLogger &
|
|
875
|
-
|
|
876
|
-
|
|
971
|
+
loggerMock: AbstractLogger &
|
|
972
|
+
LOG & {
|
|
973
|
+
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
|
|
974
|
+
};
|
|
877
975
|
}>;
|
|
878
976
|
declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOptions>({
|
|
879
977
|
middleware,
|
|
@@ -885,11 +983,14 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
|
|
|
885
983
|
/** @desc The aggregated returns of previously executed middlewares */
|
|
886
984
|
ctx?: FlatObject;
|
|
887
985
|
}) => Promise<{
|
|
888
|
-
requestMock: node_mocks_http0.MockRequest<
|
|
986
|
+
requestMock: node_mocks_http0.MockRequest<
|
|
987
|
+
Request<express_serve_static_core0.ParamsDictionary, any, any, qs0.ParsedQs, Record<string, any>> & REQ
|
|
988
|
+
>;
|
|
889
989
|
responseMock: node_mocks_http0.MockResponse<Response<any, Record<string, any>>>;
|
|
890
|
-
loggerMock: AbstractLogger &
|
|
891
|
-
|
|
892
|
-
|
|
990
|
+
loggerMock: AbstractLogger &
|
|
991
|
+
LOG & {
|
|
992
|
+
_getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
|
|
993
|
+
};
|
|
893
994
|
output: FlatObject;
|
|
894
995
|
}>;
|
|
895
996
|
//#endregion
|
|
@@ -907,10 +1008,17 @@ interface NextHandlerInc<U> {
|
|
|
907
1008
|
interface PrevInc<U> {
|
|
908
1009
|
prev: U;
|
|
909
1010
|
}
|
|
910
|
-
type SchemaHandler<
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
1011
|
+
type SchemaHandler<
|
|
1012
|
+
U,
|
|
1013
|
+
Context extends FlatObject = EmptyObject,
|
|
1014
|
+
Variant extends "regular" | "each" | "last" = "regular",
|
|
1015
|
+
> = (
|
|
1016
|
+
schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignment compatibility
|
|
1017
|
+
ctx: Context & (Variant extends "regular" ? NextHandlerInc<U> : Variant extends "each" ? PrevInc<U> : Context),
|
|
1018
|
+
) => U;
|
|
1019
|
+
type HandlingRules<U, Context extends FlatObject = EmptyObject, K extends string | symbol = string | symbol> = Partial<
|
|
1020
|
+
Record<K, SchemaHandler<U, Context>>
|
|
1021
|
+
>;
|
|
914
1022
|
//#endregion
|
|
915
1023
|
//#region src/zts-helpers.d.ts
|
|
916
1024
|
interface ZTSContext extends FlatObject {
|
|
@@ -977,13 +1085,10 @@ declare class Integration extends IntegrationBase {
|
|
|
977
1085
|
subscriptionClassName,
|
|
978
1086
|
serverUrl,
|
|
979
1087
|
noContent,
|
|
980
|
-
hasHeadMethod
|
|
1088
|
+
hasHeadMethod,
|
|
981
1089
|
}: IntegrationParams);
|
|
982
1090
|
print(printerOptions?: ts.PrinterOptions): string;
|
|
983
|
-
printFormatted({
|
|
984
|
-
printerOptions,
|
|
985
|
-
format: userDefined
|
|
986
|
-
}?: FormattedPrintingOptions): Promise<string>;
|
|
1091
|
+
printFormatted({ printerOptions, format: userDefined }?: FormattedPrintingOptions): Promise<string>;
|
|
987
1092
|
}
|
|
988
1093
|
//#endregion
|
|
989
1094
|
//#region src/sse.d.ts
|
|
@@ -994,7 +1099,7 @@ interface Emitter<E extends EventsMap> extends FlatObject {
|
|
|
994
1099
|
/** @desc Abort signal bound to the client connection lifecycle */
|
|
995
1100
|
signal: AbortSignal;
|
|
996
1101
|
/** @desc Sends an event to the stream according to the declared schema */
|
|
997
|
-
emit: <K
|
|
1102
|
+
emit: <K extends keyof E>(event: K, data: z.input<E[K]>) => void;
|
|
998
1103
|
}
|
|
999
1104
|
declare class EventStreamFactory<E extends EventsMap> extends EndpointsFactory<undefined, Emitter<E>> {
|
|
1000
1105
|
constructor(events: E);
|
|
@@ -1011,15 +1116,35 @@ interface DateOutParams extends Omit<Parameters<z.ZodString["meta"]>[0], "exampl
|
|
|
1011
1116
|
}
|
|
1012
1117
|
//#endregion
|
|
1013
1118
|
//#region src/raw-schema.d.ts
|
|
1014
|
-
declare const base: z.ZodObject<
|
|
1015
|
-
|
|
1016
|
-
|
|
1119
|
+
declare const base: z.ZodObject<
|
|
1120
|
+
{
|
|
1121
|
+
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol, "out">;
|
|
1122
|
+
},
|
|
1123
|
+
z.core.$strip
|
|
1124
|
+
>;
|
|
1017
1125
|
type Base = ReturnType<typeof base.brand<symbol>>;
|
|
1018
|
-
declare const extended: <S extends z.core.$ZodShape>(
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1126
|
+
declare const extended: <S extends z.core.$ZodShape>(
|
|
1127
|
+
extra: S,
|
|
1128
|
+
) => z.core.$ZodBranded<
|
|
1129
|
+
z.ZodObject<
|
|
1130
|
+
(
|
|
1131
|
+
"raw" & keyof S extends never
|
|
1132
|
+
? {
|
|
1133
|
+
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol, "out">;
|
|
1134
|
+
} & S
|
|
1135
|
+
: ({
|
|
1136
|
+
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol, "out">;
|
|
1137
|
+
} extends infer T_1 extends z.core.util.SomeObject
|
|
1138
|
+
? { [K in keyof T_1 as K extends keyof S ? never : K]: T_1[K] }
|
|
1139
|
+
: never) & { [K_1 in keyof S]: S[K_1] }
|
|
1140
|
+
) extends infer T
|
|
1141
|
+
? { [k in keyof T]: T[k] }
|
|
1142
|
+
: never,
|
|
1143
|
+
z.core.$strip
|
|
1144
|
+
>,
|
|
1145
|
+
symbol,
|
|
1146
|
+
"out"
|
|
1147
|
+
>;
|
|
1023
1148
|
declare function raw(): Base;
|
|
1024
1149
|
declare function raw<S extends z.core.$ZodShape>(extra: S): ReturnType<typeof extended<S>>;
|
|
1025
1150
|
//#endregion
|
|
@@ -1028,12 +1153,79 @@ declare const ez: {
|
|
|
1028
1153
|
dateIn: ({
|
|
1029
1154
|
examples,
|
|
1030
1155
|
...rest
|
|
1031
|
-
}?: DateInParams) => zod_v4_core0.$ZodBranded<
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1156
|
+
}?: DateInParams) => zod_v4_core0.$ZodBranded<
|
|
1157
|
+
zod0.ZodPipe<
|
|
1158
|
+
zod0.ZodPipe<
|
|
1159
|
+
zod0.ZodUnion<readonly [zod0.ZodISODate, zod0.ZodISODateTime, zod0.ZodISODateTime]>,
|
|
1160
|
+
zod0.ZodTransform<Date, string>
|
|
1161
|
+
>,
|
|
1162
|
+
zod0.ZodDate
|
|
1163
|
+
>,
|
|
1164
|
+
symbol,
|
|
1165
|
+
"out"
|
|
1166
|
+
>;
|
|
1167
|
+
dateOut: (
|
|
1168
|
+
meta?: DateOutParams,
|
|
1169
|
+
) => zod_v4_core0.$ZodBranded<zod0.ZodPipe<zod0.ZodDate, zod0.ZodTransform<string, Date>>, symbol, "out">;
|
|
1170
|
+
form: <S extends zod_v4_core0.$ZodShape>(
|
|
1171
|
+
base: S | zod0.ZodObject<S>,
|
|
1172
|
+
) => zod_v4_core0.$ZodBranded<zod0.ZodObject<S, zod_v4_core0.$strip>, symbol, "out">;
|
|
1173
|
+
upload: () => zod_v4_core0.$ZodBranded<
|
|
1174
|
+
zod0.ZodCustom<express_fileupload0.UploadedFile, express_fileupload0.UploadedFile>,
|
|
1175
|
+
symbol,
|
|
1176
|
+
"out"
|
|
1177
|
+
>;
|
|
1035
1178
|
raw: typeof raw;
|
|
1036
|
-
buffer: () => zod_v4_core0.$ZodBranded<
|
|
1179
|
+
buffer: () => zod_v4_core0.$ZodBranded<
|
|
1180
|
+
zod0.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>,
|
|
1181
|
+
symbol,
|
|
1182
|
+
"out"
|
|
1183
|
+
>;
|
|
1037
1184
|
};
|
|
1038
1185
|
//#endregion
|
|
1039
|
-
export {
|
|
1186
|
+
export {
|
|
1187
|
+
type ApiResponse,
|
|
1188
|
+
type AppConfig,
|
|
1189
|
+
type BasicSecurity,
|
|
1190
|
+
type BearerSecurity,
|
|
1191
|
+
BuiltinLogger,
|
|
1192
|
+
type CommonConfig,
|
|
1193
|
+
type CookieSecurity,
|
|
1194
|
+
type Depicter,
|
|
1195
|
+
Documentation,
|
|
1196
|
+
DocumentationError,
|
|
1197
|
+
EndpointsFactory,
|
|
1198
|
+
EventStreamFactory,
|
|
1199
|
+
type FlatObject,
|
|
1200
|
+
type HeaderSecurity,
|
|
1201
|
+
type IOSchema,
|
|
1202
|
+
type InputSecurity,
|
|
1203
|
+
InputValidationError,
|
|
1204
|
+
Integration,
|
|
1205
|
+
type LoggerOverrides,
|
|
1206
|
+
type Method,
|
|
1207
|
+
Middleware,
|
|
1208
|
+
MissingPeerError,
|
|
1209
|
+
type OAuth2Security,
|
|
1210
|
+
type OpenIdSecurity,
|
|
1211
|
+
OutputValidationError,
|
|
1212
|
+
type Producer,
|
|
1213
|
+
ResultHandler,
|
|
1214
|
+
type Routing,
|
|
1215
|
+
RoutingError,
|
|
1216
|
+
ServeStatic,
|
|
1217
|
+
type ServerConfig,
|
|
1218
|
+
type TagOverrides,
|
|
1219
|
+
arrayEndpointsFactory,
|
|
1220
|
+
arrayResultHandler,
|
|
1221
|
+
attachRouting,
|
|
1222
|
+
createConfig,
|
|
1223
|
+
createServer,
|
|
1224
|
+
defaultEndpointsFactory,
|
|
1225
|
+
defaultResultHandler,
|
|
1226
|
+
ensureHttpError,
|
|
1227
|
+
ez,
|
|
1228
|
+
getMessageFromError,
|
|
1229
|
+
testEndpoint,
|
|
1230
|
+
testMiddleware,
|
|
1231
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -14,7 +14,7 @@ ${i}888${n}
|
|
|
14
14
|
${r}
|
|
15
15
|
`;e.write(c.split(`
|
|
16
16
|
`).map((e,t)=>s[t]?s[t](e):e).join(`
|
|
17
|
-
`))},qt=e=>{e.startupLogo!==!1&&Kt(process.stdout);let t=e.errorHandler||W,n=rt(e.logger)?e.logger:new st(e.logger);n.debug(`Running`,{build:`v26.3.1`,env:process.env.NODE_ENV||`development`}),Wt(n);let r=Ht({logger:n,config:e}),i={getLogger:Ut(n),errorHandler:t},a=Lt(i),o=It(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},Jt=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=qt(e);return Ot({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},Yt=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=qt(e),s=v().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.compression){let t=await lt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r}),Ot({app:s,routing:t,getLogger:r,config:e,parsers:{json:[e.jsonParser||v.json()],raw:[e.rawParser||v.raw(),Vt],form:[e.formParser||v.urlencoded()],upload:e.upload?await Bt({config:e,getLogger:r}):[]}}),await e.afterRouting?.({app:s,getLogger:r}),s.use(a,i);let c=[],l=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),u=[];if(e.http){let t=y.createServer(s);c.push(t),u.push(l(t,e.http.listen))}if(e.https){let t=ee.createServer(e.https.options,s);c.push(t),u.push(l(t,e.https.listen))}return c.length||n.warn(`No servers configured.`),e.gracefulShutdown&&Gt({logger:n,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:u.map(e=>e())}},Xt=e=>O(e)&&`or`in e,Zt=e=>O(e)&&`and`in e,Qt=e=>!Zt(e)&&!Xt(e),$t=e=>{let t=n.filter(Qt,e),r=n.chain(n.prop(`and`),n.filter(Zt,e)),[i,a]=n.partition(Qt,r),o=n.concat(t,i),s=n.filter(Xt,e);return n.map(n.prop(`or`),n.concat(s,a)).reduce((e,t)=>E(e,n.map(e=>Qt(e)?[e]:e.and,t),([e,t])=>n.concat(e,t)),n.reject(n.isEmpty,[o]))};var en=`a-im.accept.accept-additions.accept-ch.accept-charset.accept-datetime.accept-encoding.accept-features.accept-language.accept-signature.access-control.access-control-request-headers.access-control-request-method.alpn.alt-used.alternates.amp-cache-transform.apply-to-redirect-ref.authentication-control.authentication-info.authorization.available-dictionary.c-ext.c-man.c-opt.c-pep.c-pep-info.cache-control.cal-managed-id.caldav-timezones.capsule-protocol.cert-not-after.cert-not-before.client-cert.client-cert-chain.close.cmcd-object.cmcd-request.cmcd-session.cmcd-status.cmsd-dynamic.cmsd-static.concealed-auth-export.configuration-context.connection.content-digest.content-disposition.content-encoding.content-id.content-language.content-length.content-location.content-md5.content-range.content-script-type.content-type.cookie.cookie2.cross-origin-embedder-policy.cross-origin-embedder-policy-report-only.cross-origin-opener-policy.cross-origin-opener-policy-report-only.cross-origin-resource-policy.cta-common-access-token.dasl.date.dav.default-style.delta-base.deprecation.depth.derived-from.destination.detached-jws.differential-id.dictionary-id.digest.dpop.dpop-nonce.early-data.ediint-features.expect.expect-ct.ext.forwarded.from.getprofile.hobareg.host.http2-settings.if.if-match.if-modified-since.if-none-match.if-range.if-schedule-tag-match.if-unmodified-since.im.include-referred-token-binding-id.isolation.keep-alive.label.last-event-id.link.link-template.lock-token.man.max-forwards.memento-datetime.meter.method-check.method-check-expires.mime-version.negotiate.nel.odata-entityid.odata-isolation.odata-maxversion.odata-version.opt.ordering-type.origin.origin-agent-cluster.oscore.oslc-core-version.overwrite.p3p.pep.pep-info.permissions-policy.pics-label.ping-from.ping-to.position.pragma.prefer.preference-applied.priority.profileobject.protocol.protocol-info.protocol-query.protocol-request.proxy-authorization.proxy-features.proxy-instruction.public.public-key-pins.public-key-pins-report-only.range.redirect-ref.referer.referer-root.referrer-policy.repeatability-client-id.repeatability-first-sent.repeatability-request-id.repeatability-result.replay-nonce.reporting-endpoints.repr-digest.safe.schedule-reply.schedule-tag.sec-fetch-storage-access.sec-gpc.sec-purpose.sec-token-binding.sec-websocket-extensions.sec-websocket-key.sec-websocket-protocol.sec-websocket-version.security-scheme.setprofile.signature.signature-input.slug.soapaction.status-uri.sunset.surrogate-capability.tcn.te.timeout.topic.traceparent.tracestate.trailer.transfer-encoding.ttl.upgrade.urgency.uri.use-as-dictionary.user-agent.variant-vary.via.want-content-digest.want-digest.want-repr-digest.warning.x-content-type-options.x-frame-options`.split(`.`);const tn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,nn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},rn=e=>e.replace(ue,e=>`{${e.slice(1)}}`),an=({},e)=>{if(e.isResponse)throw new N(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},on=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),sn=({zodSchema:e,jsonSchema:t})=>{if(!T(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},cn=n.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return J(e,`throw`)},(e,{jsonSchema:t})=>t),ln=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:hn(t.type)})},Y=e=>e,un=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new N(`Please use ez.dateOut() for output.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,pattern:`^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?)?Z?$`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},dn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new N(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},fn=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),pn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,mn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return nn?.[t]},hn=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],gn=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!T(r,`transform`))return t;let a=Y(Cn(i,{ctx:n}));if(b(a))if(n.isResponse){let e=ye(r,mn(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},_n=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!O(t.properties.raw)?e:t.properties.raw},vn=e=>e.length?n.fromPairs(n.zip(n.times(e=>`example${e+1}`,e.length),n.map(n.objOf(`value`),e))):void 0,yn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||en.includes(e),bn=({path:e,method:t,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let u=J(r),d=de(e),f=i.includes(`query`),p=i.includes(`params`),m=i.includes(`headers`),h=e=>p&&d.includes(e),g=n.chain(n.filter(e=>e.type===`header`),c??[]).map(({name:e})=>e),_=n=>m&&(s?.(n,t,e)??yn(n,g));return Object.entries(u.properties).reduce((e,[t,r])=>{if(!O(r))return e;let i=h(t)?`path`:_(t)?`header`:f?`query`:void 0;if(!i)return e;let s=Y(r),c=o===`components`?a(r.id||JSON.stringify(r),s,r.id||D(l,t)):s;return e.concat({name:t,in:i,deprecated:r.deprecated,required:u.required?.includes(t)||!1,description:s.description||l,schema:c,examples:vn(b(s)&&s.examples?.length?s.examples:n.pluck(t,u.examples?.filter(n.both(O,n.has(t)))||[]))})},[])},xn={nullable:ln,union:sn,bigint:fn,intersection:cn,tuple:pn,pipe:gn,[A]:un,[j]:dn,[F]:an,[I]:_n,[k]:on},Sn=(e,t,r)=>{let i=[e,t];for(;i.length;){let e=i.shift();if(n.is(Object,e)){if(re(e)&&!e.$ref.startsWith(`#/components`)){let n=t[e.$ref.split(`/`).pop()];n&&(e.$ref=r.makeRef(n.id||n,Y(n),n.id).$ref);continue}i.push(...n.values(e))}n.is(Array,e)&&i.push(...n.values(e))}return e},Cn=(e,{ctx:n,rules:r=xn})=>{let{$defs:a={},properties:o={}}=i.toJSONSchema(i.object({subject:e}),{unrepresentable:`any`,io:n.isResponse?`output`:`input`,override:e=>{let i=t(e.zodSchema),a=r[i&&i in r?i:e.zodSchema._zod.def.type];if(a){let t={...a(e,n)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,t)}}});return Sn(O(o.subject)?o.subject:{},a,n)},wn=(e,t)=>{if(re(e))return[e,!1];let r=!1,i=n.map(e=>{let[n,i]=wn(e,t);return r||=i,n}),a=n.omit(t),o={properties:a,examples:n.map(a),required:n.without(t),allOf:i,oneOf:i,anyOf:i},s=n.evolve(o,e);return[s,r||!!s.required?.length]},Tn=({method:e,path:t,schema:r,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${t} ${ve(a)} response ${c?l:``}`.trim()})=>{if(!xe(e,i))return{description:d};let f=Y(Cn(r,{rules:{...u,...xn},ctx:{isResponse:!0,makeRef:o,path:t,method:e}})),p=[];b(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(r,f,D(d)):f,examples:vn(p)};return{description:d,content:n.fromPairs(n.xprod(i,[m]))}},En=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Dn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},On=({name:e})=>({type:`apiKey`,in:`header`,name:e}),kn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),An=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),jn=({flows:e={}})=>({type:`oauth2`,flows:n.map(e=>({...e,scopes:e.scopes||{}}),n.reject(n.isNil,e))}),Mn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?En(e):e.type===`input`?Dn(e,t):e.type===`header`?On(e):e.type===`cookie`?kn(e):e.type===`openid`?An(e):jn(e);return e.map(e=>e.map(n))},Nn=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),Pn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Cn(e,{rules:{...t,...xn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Fn=({method:e,path:t,schema:r,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let[u,d]=wn(Y(i),c),f=[];b(u)&&u.examples&&(f.push(...u.examples),delete u.examples);let p={schema:s===`components`?o(r,u,D(l)):u,examples:vn(f.length?f:J(i).examples?.filter(e=>O(e)&&!Array.isArray(e)).map(n.omit(c))||[])},m={description:l,content:{[a]:p}};return(d||a===x.raw)&&(m.required=!0),m},In=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;let r={name:t,description:typeof n==`string`?n:n.description};return typeof n==`object`&&n.url&&(r.externalDocs={url:n.url}),e.concat(r)},[]),Ln=e=>e.length<=50?e:e.slice(0,49)+`…`,X=e=>e.length?e.slice():void 0;var Rn=class extends ne{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n){let r=this.#n.get(e);if(!r){let t=n?0:1;do r=`${n??`Schema`}${t?this.#n.size+t:``}`,t++;while(this.rootDoc.components?.schemas?.[r]);this.#n.set(e,r)}return this.addSchema(r,t),{$ref:`#/components/schemas/${r}`}}#i(e,t,n){let r=n||D(t,e),i=this.#t.get(r);if(i===void 0)return this.#t.set(r,1),r;if(n)throw new N(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#t.set(r,i),`${r}${i}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}constructor({routing:e,config:t,title:r,version:i,serverUrl:a,descriptions:o,brandHandling:s,tags:c,isHeader:l,hasSummaryFromDescription:u=!0,hasHeadMethod:d=!0,composition:f=`inline`}){super(),this.addInfo({title:r,version:i});for(let e of typeof a==`string`?[a]:a)this.addServer({url:e});let p=(e,r,i)=>{let a={path:r,method:e,endpoint:i,composition:f,brandHandling:s,makeRef:this.#r.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,h=d?Ln(d):u&&c?Ln(c):void 0,g=ge(e,t.inputSources),_=this.#i(r,e,i.getOperationId(e)),v=Pn({...a,schema:m}),y=$t(i.security),ee=bn({...a,inputSources:g,isHeader:l,security:y,request:v,description:o?.requestParameter?.call(null,{method:e,path:r,operationId:_})}),te={};for(let t of H){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)te[l]=Tn({...a,variant:t,schema:s,mimeTypes:i,statusCode:l,hasMultipleStatusCodes:n.length>1||c.length>1,description:o?.[`${t}Response`]?.call(null,{method:e,path:r,operationId:_,statusCode:l})})}let ne=g.includes(`body`)?Fn({...a,request:v,paramNames:n.pluck(`name`,ee),schema:m,mimeType:x[i.requestType],description:o?.requestBody?.call(null,{method:e,path:r,operationId:_})}):void 0,re=Nn(Mn(y,g),p,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),b={operationId:_,summary:h,description:c,deprecated:i.isDeprecated||void 0,tags:X(i.tags),parameters:X(ee),requestBody:ne,security:X(re),responses:te};this.addPath(rn(r),{[e]:b})};Ct({routing:e,config:t,onEndpoint:d?gt(p):p}),c&&(this.rootDoc.tags=In(c))}};const zn=e=>ie({...e,headers:{"content-type":x.json,...e?.headers}}),Bn=e=>ae(e),Vn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:it(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},Hn=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=zn(e),a=Bn({req:i,...t});a.req=t?.req||i,i.res=a;let o=Vn(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},Un=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=Hn(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},Wn=async({middleware:e,ctx:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=W}}=Hn(n),c={request:r,response:i,logger:a,input:_e(r,o),ctx:t};try{return{requestMock:r,responseMock:i,loggerMock:a,output:await e.execute(c)}}catch(e){return await s.execute({...c,error:C(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}};var Gn=class t{ts;f;exportModifier;asyncModifier;accessModifiers;#e;static#t=/^[A-Za-z_$][A-Za-z0-9_$]*$/;constructor(){this.ts=e(import.meta.url)(`typescript`),this.f=this.ts.factory,this.exportModifier=[this.f.createModifier(this.ts.SyntaxKind.ExportKeyword)],this.asyncModifier=[this.f.createModifier(this.ts.SyntaxKind.AsyncKeyword)],this.accessModifiers={public:[this.f.createModifier(this.ts.SyntaxKind.PublicKeyword)],protectedReadonly:[this.f.createModifier(this.ts.SyntaxKind.ProtectedKeyword),this.f.createModifier(this.ts.SyntaxKind.ReadonlyKeyword)]},this.#e=[this.ts.SyntaxKind.AnyKeyword,this.ts.SyntaxKind.BigIntKeyword,this.ts.SyntaxKind.BooleanKeyword,this.ts.SyntaxKind.NeverKeyword,this.ts.SyntaxKind.NumberKeyword,this.ts.SyntaxKind.ObjectKeyword,this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.SymbolKeyword,this.ts.SyntaxKind.UndefinedKeyword,this.ts.SyntaxKind.UnknownKeyword,this.ts.SyntaxKind.VoidKeyword]}addJsDoc=(e,t)=>this.ts.addSyntheticLeadingComment(e,this.ts.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0);printNode=(e,t)=>{let n=this.ts.createSourceFile(`print.ts`,``,this.ts.ScriptTarget.Latest,!1,this.ts.ScriptKind.TS);return this.ts.createPrinter(t).printNode(this.ts.EmitHint.Unspecified,e,n)};makePropertyIdentifier=e=>typeof e==`string`&&t.#t.test(e)?this.f.createIdentifier(e):this.literally(e);makeTemplate=(e,...t)=>this.f.createTemplateExpression(this.f.createTemplateHead(e),t.map(([e,n=``],r)=>this.f.createTemplateSpan(e,r===t.length-1?this.f.createTemplateTail(n):this.f.createTemplateMiddle(n))));makeParam=(e,{type:t,mod:n,init:r,optional:i}={})=>this.f.createParameterDeclaration(n,void 0,e,i?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,t?this.ensureTypeNode(t):void 0,r);makeParams=e=>Object.entries(e).map(([e,t])=>this.makeParam(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t));makePublicConstructor=(e,t=[])=>this.f.createConstructorDeclaration(this.accessModifiers.public,e,this.f.createBlock(t));ensureTypeNode=(e,t)=>typeof e==`number`?this.f.createKeywordTypeNode(e):typeof e==`string`||this.ts.isIdentifier(e)?this.f.createTypeReferenceNode(e,t&&n.map(this.ensureTypeNode.bind(this),t)):e;makeRecordStringAny=()=>this.ensureTypeNode(`Record`,[this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.AnyKeyword]);makeUnion=e=>{let t=new Map;for(let n of e)t.set(this.isPrimitive(n)?n.kind:n,n);return this.f.createUnionTypeNode(Array.from(t.values()))};makeInterfaceProp=(e,t,{isOptional:r,hasUndefined:i=r,isDeprecated:a,comment:o}={})=>{let s=this.ensureTypeNode(t),c=this.f.createPropertySignature(void 0,this.makePropertyIdentifier(e),r?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,i?this.makeUnion([s,this.ensureTypeNode(this.ts.SyntaxKind.UndefinedKeyword)]):s),l=n.reject(n.isNil,[a?`@deprecated`:void 0,o]);return l.length?this.addJsDoc(c,l.join(` `)):c};makeOneLine=e=>this.ts.setEmitFlags(e,this.ts.EmitFlags.SingleLine);makeDeconstruction=(...e)=>this.f.createArrayBindingPattern(e.map(e=>this.f.createBindingElement(void 0,void 0,e)));makeConst=(e,t,{type:n,expose:r}={})=>this.f.createVariableStatement(r&&this.exportModifier,this.f.createVariableDeclarationList([this.f.createVariableDeclaration(e,void 0,n?this.ensureTypeNode(n):void 0,t)],this.ts.NodeFlags.Const));makePublicLiteralType=(e,t)=>this.makeType(e,this.makeUnion(n.map(this.makeLiteralType.bind(this),t)),{expose:!0});makeType=(e,t,{expose:n,comment:r,params:i}={})=>{let a=this.f.createTypeAliasDeclaration(n?this.exportModifier:void 0,e,i&&this.makeTypeParams(i),t);return r?this.addJsDoc(a,r):a};makePublicProperty=(e,t)=>this.f.createPropertyDeclaration(this.accessModifiers.public,e,void 0,this.ensureTypeNode(t),void 0);makePublicMethod=(e,t,n,{typeParams:r,returns:i}={})=>this.f.createMethodDeclaration(this.accessModifiers.public,void 0,e,void 0,r&&this.makeTypeParams(r),t,i,this.f.createBlock(n));makePublicClass=(e,t,{typeParams:n}={})=>this.f.createClassDeclaration(this.exportModifier,e,n&&this.makeTypeParams(n),void 0,t);makeKeyOf=e=>this.f.createTypeOperatorNode(this.ts.SyntaxKind.KeyOfKeyword,this.ensureTypeNode(e));makePromise=e=>this.ensureTypeNode(Promise.name,[e]);makeInterface=(e,t,{expose:n,comment:r}={})=>{let i=this.f.createInterfaceDeclaration(n?this.exportModifier:void 0,e,void 0,void 0,t);return r?this.addJsDoc(i,r):i};makeTypeParams=e=>(Array.isArray(e)?e.map(e=>n.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return this.f.createTypeParameterDeclaration([],e,n?this.ensureTypeNode(n):void 0,r?this.ensureTypeNode(r):void 0)});makeArrowFn=(e,t,{isAsync:r}={})=>this.f.createArrowFunction(r?this.asyncModifier:void 0,void 0,Array.isArray(e)?n.map(this.makeParam.bind(this),e):this.makeParams(e),void 0,void 0,t);makeTernary=(e,t,n)=>this.f.createConditionalExpression(e,this.f.createToken(this.ts.SyntaxKind.QuestionToken),t,this.f.createToken(this.ts.SyntaxKind.ColonToken),n);makeCall=(e,...t)=>(...n)=>this.f.createCallExpression(t.reduce((e,t)=>typeof t==`string`||this.ts.isIdentifier(t)?this.f.createPropertyAccessExpression(e,t):this.f.createElementAccessExpression(e,t),typeof e==`string`?this.f.createIdentifier(e):e),void 0,n);makeNew=(e,...t)=>this.f.createNewExpression(this.f.createIdentifier(e),void 0,t);makeExtract=(e,t)=>this.ensureTypeNode(`Extract`,[e,t]);makeAssignment=(e,t)=>this.f.createExpressionStatement(this.f.createBinaryExpression(e,this.f.createToken(this.ts.SyntaxKind.EqualsToken),t));makeIndexed=(e,t)=>this.f.createIndexedAccessTypeNode(this.ensureTypeNode(e),this.ensureTypeNode(t));makeMaybeAsync=e=>this.makeUnion([this.ensureTypeNode(e),this.makePromise(e)]);makeFnType=(e,t)=>this.f.createFunctionTypeNode(void 0,this.makeParams(e),this.ensureTypeNode(t));literally=e=>typeof e==`number`?this.f.createNumericLiteral(e):typeof e==`bigint`?this.f.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?this.f.createTrue():this.f.createFalse():e===null?this.f.createNull():this.f.createStringLiteral(e);makeLiteralType=e=>this.f.createLiteralTypeNode(this.literally(e));isPrimitive=e=>this.#e.includes(e.kind)};const Z=e=>e;var Kn=class{api=new Gn;paths=new Set;tags=new Map;registry=new Map;#e={pathType:this.api.f.createIdentifier(`Path`),implementationType:this.api.f.createIdentifier(`Implementation`),keyParameter:this.api.f.createIdentifier(`key`),pathParameter:this.api.f.createIdentifier(`path`),paramsArgument:this.api.f.createIdentifier(`params`),ctxArgument:this.api.f.createIdentifier(`ctx`),methodParameter:this.api.f.createIdentifier(`method`),requestParameter:this.api.f.createIdentifier(`request`),eventParameter:this.api.f.createIdentifier(`event`),dataParameter:this.api.f.createIdentifier(`data`),handlerParameter:this.api.f.createIdentifier(`handler`),msgParameter:this.api.f.createIdentifier(`msg`),parseRequestFn:this.api.f.createIdentifier(`parseRequest`),substituteFn:this.api.f.createIdentifier(`substitute`),provideMethod:this.api.f.createIdentifier(`provide`),onMethod:this.api.f.createIdentifier(`on`),implementationArgument:this.api.f.createIdentifier(`implementation`),hasBodyConst:this.api.f.createIdentifier(`hasBody`),undefinedValue:this.api.f.createIdentifier(`undefined`),responseConst:this.api.f.createIdentifier(`response`),restConst:this.api.f.createIdentifier(`rest`),searchParamsConst:this.api.f.createIdentifier(`searchParams`),defaultImplementationConst:this.api.f.createIdentifier(`defaultImplementation`),clientConst:this.api.f.createIdentifier(`client`),contentTypeConst:this.api.f.createIdentifier(`contentType`),isJsonConst:this.api.f.createIdentifier(`isJSON`),sourceProp:this.api.f.createIdentifier(`source`)};interfaces={input:this.api.f.createIdentifier(`Input`),positive:this.api.f.createIdentifier(`PositiveResponse`),negative:this.api.f.createIdentifier(`NegativeResponse`),encoded:this.api.f.createIdentifier(`EncodedResponse`),response:this.api.f.createIdentifier(`Response`)};methodType=this.api.makePublicLiteralType(`Method`,ce);someOfType=this.api.makeType(`SomeOf`,this.api.makeIndexed(`T`,this.api.makeKeyOf(`T`)),{params:[`T`]});requestType=this.api.makeType(`Request`,this.api.makeKeyOf(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>this.api.ensureTypeNode(this.someOfType.name,[e]);makePathType=()=>this.api.makePublicLiteralType(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>this.api.makeInterface(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>this.api.makeInterfaceProp(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>this.api.makeConst(`endpointTags`,this.api.f.createObjectLiteralExpression(Array.from(this.tags).map(([e,t])=>this.api.f.createPropertyAssignment(this.api.makePropertyIdentifier(e),this.api.f.createArrayLiteralExpression(n.map(this.api.literally.bind(this.api),t))))),{expose:!0});makeImplementationType=()=>this.api.makeType(this.#e.implementationType,this.api.makeFnType({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.api.makeRecordStringAny(),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}},this.api.makePromise(this.api.ts.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:this.api.ts.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>this.api.makeConst(this.#e.parseRequestFn,this.api.makeArrowFn({[this.#e.requestParameter.text]:this.api.ts.SyntaxKind.StringKeyword},this.api.f.createAsExpression(this.api.makeCall(this.#e.requestParameter,Z(`split`))(this.api.f.createRegularExpressionLiteral(`/ (.+)/`),this.api.literally(2)),this.api.f.createTupleTypeNode([this.api.ensureTypeNode(this.methodType.name),this.api.ensureTypeNode(this.#e.pathType)]))));makeSubstituteFn=()=>this.api.makeConst(this.#e.substituteFn,this.api.makeArrowFn({[this.#e.pathParameter.text]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.api.makeRecordStringAny()},this.api.f.createBlock([this.api.makeConst(this.#e.restConst,this.api.f.createObjectLiteralExpression([this.api.f.createSpreadAssignment(this.#e.paramsArgument)])),this.api.f.createForInStatement(this.api.f.createVariableDeclarationList([this.api.f.createVariableDeclaration(this.#e.keyParameter)],this.api.ts.NodeFlags.Const),this.#e.paramsArgument,this.api.f.createBlock([this.api.makeAssignment(this.#e.pathParameter,this.api.makeCall(this.#e.pathParameter,Z(`replace`))(this.api.makeTemplate(`:`,[this.#e.keyParameter]),this.api.makeArrowFn([],this.api.f.createBlock([this.api.f.createExpressionStatement(this.api.f.createDeleteExpression(this.api.f.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),this.api.f.createReturnStatement(this.api.f.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),this.api.f.createReturnStatement(this.api.f.createAsExpression(this.api.f.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),this.api.ensureTypeNode(`const`)))])));#t=()=>this.api.makePublicMethod(this.#e.provideMethod,this.api.makeParams({[this.#e.requestParameter.text]:`K`,[this.#e.paramsArgument.text]:this.api.makeIndexed(this.interfaces.input,`K`),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.methodParameter,this.#e.pathParameter),this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter)),this.api.f.createReturnStatement(this.api.makeCall(this.api.f.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,this.api.f.createSpreadElement(this.api.makeCall(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:this.api.makePromise(this.api.makeIndexed(this.interfaces.response,`K`))});makeClientClass=e=>this.api.makePublicClass(e,[this.api.makePublicConstructor([this.api.makeParam(this.#e.implementationArgument,{type:this.api.ensureTypeNode(this.#e.implementationType,[`T`]),mod:this.api.accessModifiers.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:[`T`]});#n=e=>this.api.makeTemplate(`?`,[this.api.makeNew(URLSearchParams.name,e)]);#r=()=>this.api.makeNew(URL.name,this.api.makeTemplate(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),this.api.literally(this.serverUrl));makeDefaultImplementation=()=>{let e=this.api.f.createPropertyAssignment(Z(`method`),this.api.makeCall(this.#e.methodParameter,Z(`toUpperCase`))()),t=this.api.f.createPropertyAssignment(Z(`headers`),this.api.makeTernary(this.#e.hasBodyConst,this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(this.api.literally(`Content-Type`),this.api.literally(x.json))]),this.#e.undefinedValue)),n=this.api.f.createPropertyAssignment(Z(`body`),this.api.makeTernary(this.#e.hasBodyConst,this.api.makeCall(JSON[Symbol.toStringTag],Z(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=this.api.makeConst(this.#e.responseConst,this.api.f.createAwaitExpression(this.api.makeCall(fetch.name)(this.#r(),this.api.f.createObjectLiteralExpression([e,t,n])))),i=this.api.makeConst(this.#e.hasBodyConst,this.api.f.createLogicalNot(this.api.makeCall(this.api.f.createArrayLiteralExpression([this.api.literally(`get`),this.api.literally(`head`),this.api.literally(`delete`)]),Z(`includes`))(this.#e.methodParameter))),a=this.api.makeConst(this.#e.searchParamsConst,this.api.makeTernary(this.#e.hasBodyConst,this.api.literally(``),this.#n(this.#e.paramsArgument))),o=this.api.makeConst(this.#e.contentTypeConst,this.api.makeCall(this.#e.responseConst,Z(`headers`),Z(`get`))(this.api.literally(`content-type`))),s=this.api.f.createIfStatement(this.api.f.createPrefixUnaryExpression(this.api.ts.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),this.api.f.createReturnStatement()),c=this.api.makeConst(this.#e.isJsonConst,this.api.makeCall(this.#e.contentTypeConst,Z(`startsWith`))(this.api.literally(x.json))),l=this.api.f.createReturnStatement(this.api.makeCall(this.#e.responseConst,this.api.makeTernary(this.#e.isJsonConst,this.api.literally(Z(`json`)),this.api.literally(Z(`text`))))());return this.api.makeConst(this.#e.defaultImplementationConst,this.api.makeArrowFn([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],this.api.f.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#e.implementationType})};#i=()=>this.api.makePublicConstructor(this.api.makeParams({request:`K`,params:this.api.makeIndexed(this.interfaces.input,`K`)}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.pathParameter,this.#e.restConst),this.api.makeCall(this.#e.substituteFn)(this.api.f.createElementAccessExpression(this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter),this.api.literally(1)),this.#e.paramsArgument)),this.api.makeConst(this.#e.searchParamsConst,this.#n(this.#e.restConst)),this.api.makeAssignment(this.api.f.createPropertyAccessExpression(this.api.f.createThis(),this.#e.sourceProp),this.api.makeNew(`EventSource`,this.#r()))]);#a=e=>this.api.f.createTypeLiteralNode([this.api.makeInterfaceProp(Z(`event`),e)]);#o=()=>this.api.makePublicMethod(this.#e.onMethod,this.api.makeParams({[this.#e.eventParameter.text]:`E`,[this.#e.handlerParameter.text]:this.api.makeFnType({[this.#e.dataParameter.text]:this.api.makeIndexed(this.api.makeExtract(`R`,this.api.makeOneLine(this.#a(`E`))),this.api.makeLiteralType(Z(`data`)))},this.api.makeMaybeAsync(this.api.ts.SyntaxKind.VoidKeyword))}),[this.api.f.createExpressionStatement(this.api.makeCall(this.api.f.createThis(),this.#e.sourceProp,Z(`addEventListener`))(this.#e.eventParameter,this.api.makeArrowFn([this.#e.msgParameter],this.api.makeCall(this.#e.handlerParameter)(this.api.makeCall(JSON[Symbol.toStringTag],Z(`parse`))(this.api.f.createPropertyAccessExpression(this.api.f.createParenthesizedExpression(this.api.f.createAsExpression(this.#e.msgParameter,this.api.ensureTypeNode(MessageEvent.name))),Z(`data`))))))),this.api.f.createReturnStatement(this.api.f.createThis())],{typeParams:{E:this.api.makeIndexed(`R`,this.api.makeLiteralType(Z(`event`)))}});makeSubscriptionClass=e=>this.api.makePublicClass(e,[this.api.makePublicProperty(this.#e.sourceProp,`EventSource`),this.#i(),this.#o()],{typeParams:{K:this.api.makeExtract(this.requestType.name,this.api.f.createTemplateLiteralType(this.api.f.createTemplateHead(`get `),[this.api.f.createTemplateLiteralTypeSpan(this.api.ensureTypeNode(this.api.ts.SyntaxKind.StringKeyword),this.api.f.createTemplateTail(``))])),R:this.api.makeExtract(this.api.makeIndexed(this.interfaces.positive,`K`),this.api.makeOneLine(this.#a(this.api.ts.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[this.api.makeConst(this.#e.clientConst,this.api.makeNew(e)),this.api.makeCall(this.#e.clientConst,this.#e.provideMethod)(this.api.literally(`get /v1/user/retrieve`),this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(`id`,this.api.literally(`10`))])),this.api.makeCall(this.api.makeNew(t,this.api.literally(`get /v1/events/stream`),this.api.f.createObjectLiteralExpression()),this.#e.onMethod)(this.api.literally(`time`),this.api.makeArrowFn([`time`],this.api.f.createBlock([])))]};const qn=(e,{onEach:n,rules:r,onMissing:i,ctx:a={}})=>{let o=t(e),s=o&&o in r?r[o]:r[e._zod.def.type],c=e=>qn(e,{ctx:a,onEach:n,rules:r,onMissing:i}),l=s?s(e,{...a,next:c}):i(e,a),u=n&&n(e,{prev:l,...a});return u?{...l,...u}:l},Jn={name:n.path([`name`,`text`]),type:n.path([`type`]),optional:n.path([`questionToken`])},Yn=({_zod:{def:e}},{api:t})=>{let n=e.values.map(e=>e===void 0?t.ensureTypeNode(t.ts.SyntaxKind.UndefinedKeyword):t.makeLiteralType(e));return n.length===1?n[0]:t.makeUnion(n)},Xn=({_zod:{def:e}},{next:t,api:n})=>{let r=[...e.parts],i=()=>{let e=``;for(;r.length;){let t=r.shift();if(T(t)){r.unshift(t);break}e+=t??``}return e},a=n.f.createTemplateHead(i()),o=[];for(;r.length;){let e=t(r.shift()),a=i(),s=r.length?n.f.createTemplateMiddle:n.f.createTemplateTail;o.push(n.f.createTemplateLiteralTypeSpan(e,s(a)))}return o.length?n.f.createTemplateLiteralType(a,o):n.makeLiteralType(a.text)},Zn=(e,{isResponse:t,next:n,makeAlias:a,api:o})=>{let s=()=>{let a=Object.entries(e._zod.def.shape).map(([e,a])=>{let{description:s,deprecated:c}=r.get(a)||{},l=(t?a._zod.optout:a._zod.optin)===`optional`,u=l&&!(a instanceof i.core.$ZodExactOptional);return o.makeInterfaceProp(e,n(a),{comment:s,isDeprecated:c,isOptional:l,hasUndefined:u})});return o.f.createTypeLiteralNode(a)};return Le(e,{io:t?`output`:`input`})?a(e,s):s()},Qn=({_zod:{def:e}},{next:t,api:n})=>n.f.createArrayTypeNode(t(e.element)),$n=({_zod:{def:e}},{api:t})=>t.makeUnion(Object.values(e.entries).map(t.makeLiteralType.bind(t))),er=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion(e.options.map(t)),tr=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion([t(e.innerType),n.makeLiteralType(null)]),nr=({_zod:{def:e}},{next:t,api:n})=>n.f.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:n.f.createRestTypeNode(t(e.rest)))),rr=({_zod:{def:e}},{next:t,api:n})=>{let[r,i]=[e.keyType,e.valueType].map(t),a=n.ensureTypeNode(`Record`,[r,i]);return e.mode===`loose`?n.f.createIntersectionTypeNode([a,n.ensureTypeNode(`Record`,[`PropertyKey`,i])]):a},ir=n.tryCatch((e,t)=>{if(!t.every(e.ts.isTypeLiteralNode))throw Error(`Not objects`);let r=n.chain(n.prop(`members`),t),i=n.uniqWith((...e)=>{if(!n.eqBy(Jn.name,...e))return!1;if(n.both(n.eqBy(Jn.type),n.eqBy(Jn.optional))(...e))return!0;throw Error(`Has conflicting prop`)},r);return e.f.createTypeLiteralNode(i)},(e,t,n)=>t.f.createIntersectionTypeNode(n)),ar=({_zod:{def:e}},{next:t,api:n})=>ir(n,[e.left,e.right].map(t)),Q=e=>({},{api:t})=>t.ensureTypeNode(t.ts.SyntaxKind[e]),$=({_zod:{def:e}},{next:t})=>t(e.innerType),or=(e,t)=>e.ensureTypeNode(t?e.ts.SyntaxKind.UnknownKeyword:e.ts.SyntaxKind.AnyKeyword),sr=({_zod:{def:e}},{next:t,isResponse:n,api:r})=>{let i=e[n?`out`:`in`],a=e[n?`in`:`out`];if(!T(i,`transform`))return t(i);let o=t(a),s={[r.ts.SyntaxKind.AnyKeyword]:``,[r.ts.SyntaxKind.BigIntKeyword]:BigInt(0),[r.ts.SyntaxKind.BooleanKeyword]:!1,[r.ts.SyntaxKind.NumberKeyword]:0,[r.ts.SyntaxKind.ObjectKeyword]:{},[r.ts.SyntaxKind.StringKeyword]:``,[r.ts.SyntaxKind.UndefinedKeyword]:void 0}[o.kind],c=ye(i,s),l={number:r.ts.SyntaxKind.NumberKeyword,bigint:r.ts.SyntaxKind.BigIntKeyword,boolean:r.ts.SyntaxKind.BooleanKeyword,string:r.ts.SyntaxKind.StringKeyword,undefined:r.ts.SyntaxKind.UndefinedKeyword,object:r.ts.SyntaxKind.ObjectKeyword};return r.ensureTypeNode(c&&l[c]||or(r,n))},cr=({},{api:e})=>e.makeLiteralType(null),lr=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ur=({},{api:e})=>e.ensureTypeNode(`Buffer`),dr=(e,{next:t})=>t(e._zod.def.shape.raw),fr={string:Q(`StringKeyword`),number:Q(`NumberKeyword`),bigint:Q(`BigIntKeyword`),boolean:Q(`BooleanKeyword`),any:Q(`AnyKeyword`),undefined:Q(`UndefinedKeyword`),[A]:Q(`StringKeyword`),[j]:Q(`StringKeyword`),never:Q(`NeverKeyword`),void:Q(`UndefinedKeyword`),unknown:Q(`UnknownKeyword`),null:cr,array:Qn,tuple:nr,record:rr,object:Zn,literal:Yn,template_literal:Xn,intersection:ar,union:er,default:$,enum:$n,optional:$,nonoptional:$,nullable:tr,catch:$,pipe:sr,lazy:lr,readonly:$,[k]:ur,[I]:dr},pr=(e,{brandHandling:t,ctx:n})=>qn(e,{rules:{...t,...fr},onMissing:({},{isResponse:e,api:t})=>or(t,e),ctx:n});var mr=class extends Kn{#e=[this.someOfType];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=this.api.makeLiteralType(null);this.#t.set(e,this.api.makeType(n,r)),this.#t.set(e,this.api.makeType(n,t()))}return this.api.ensureTypeNode(n)}constructor({routing:e,config:t,brandHandling:r,variant:a=`client`,clientClassName:o=`Client`,subscriptionClassName:s=`Subscription`,serverUrl:c=`https://example.com`,noContent:l=i.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this),api:this.api},f={brandHandling:r,ctx:{...d,isResponse:!1}},p={brandHandling:r,ctx:{...d,isResponse:!0}},m=(e,t,r)=>{let i=D.bind(null,e,t),{isDeprecated:a,inputSchema:o,tags:s}=r,c=`${e} ${t}`,u=this.api.makeType(i(`input`),pr(o,f),{comment:c});this.#e.push(u);let d=H.reduce((t,a)=>{let o=r.getResponses(a),s=n.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=xe(e,r),u=this.api.makeType(i(a,`variant`,`${t+1}`),pr(s?n:l,p),{comment:c});return this.#e.push(u),o.map(e=>this.api.makeInterfaceProp(e,u.name))},Array.from(o.entries())),u=this.api.makeInterface(i(a,`response`,`variants`),s,{comment:c});return this.#e.push(u),Object.assign(t,{[a]:u})},{});this.paths.add(t);let m=this.api.makeLiteralType(c),h={input:this.api.ensureTypeNode(u.name),positive:this.someOf(d.positive),negative:this.someOf(d.negative),response:this.api.makeUnion([this.api.makeIndexed(this.interfaces.positive,m),this.api.makeIndexed(this.interfaces.negative,m)]),encoded:this.api.f.createIntersectionTypeNode([this.api.ensureTypeNode(d.positive.name),this.api.ensureTypeNode(d.negative.name)])};this.registry.set(c,{isDeprecated:a,store:h}),this.tags.set(c,s)};Ct({routing:e,config:t,onEndpoint:u?gt(m):m}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),a!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(o),this.makeSubscriptionClass(s)),this.#n.push(...this.makeUsageStatements(o,s)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:this.api.printNode(t,e)).join(`
|
|
17
|
+
`))},qt=e=>{e.startupLogo!==!1&&Kt(process.stdout);let t=e.errorHandler||W,n=rt(e.logger)?e.logger:new st(e.logger);n.debug(`Running`,{build:`v26.3.2`,env:process.env.NODE_ENV||`development`}),Wt(n);let r=Ht({logger:n,config:e}),i={getLogger:Ut(n),errorHandler:t},a=Lt(i),o=It(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},Jt=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=qt(e);return Ot({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},Yt=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=qt(e),s=v().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.compression){let t=await lt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r}),Ot({app:s,routing:t,getLogger:r,config:e,parsers:{json:[e.jsonParser||v.json()],raw:[e.rawParser||v.raw(),Vt],form:[e.formParser||v.urlencoded()],upload:e.upload?await Bt({config:e,getLogger:r}):[]}}),await e.afterRouting?.({app:s,getLogger:r}),s.use(a,i);let c=[],l=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),u=[];if(e.http){let t=y.createServer(s);c.push(t),u.push(l(t,e.http.listen))}if(e.https){let t=ee.createServer(e.https.options,s);c.push(t),u.push(l(t,e.https.listen))}return c.length||n.warn(`No servers configured.`),e.gracefulShutdown&&Gt({logger:n,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:u.map(e=>e())}},Xt=e=>O(e)&&`or`in e,Zt=e=>O(e)&&`and`in e,Qt=e=>!Zt(e)&&!Xt(e),$t=e=>{let t=n.filter(Qt,e),r=n.chain(n.prop(`and`),n.filter(Zt,e)),[i,a]=n.partition(Qt,r),o=n.concat(t,i),s=n.filter(Xt,e);return n.map(n.prop(`or`),n.concat(s,a)).reduce((e,t)=>E(e,n.map(e=>Qt(e)?[e]:e.and,t),([e,t])=>n.concat(e,t)),n.reject(n.isEmpty,[o]))};var en=`a-im.accept.accept-additions.accept-ch.accept-charset.accept-datetime.accept-encoding.accept-features.accept-language.accept-signature.access-control.access-control-request-headers.access-control-request-method.alpn.alt-used.alternates.amp-cache-transform.apply-to-redirect-ref.authentication-control.authentication-info.authorization.available-dictionary.c-ext.c-man.c-opt.c-pep.c-pep-info.cache-control.cal-managed-id.caldav-timezones.capsule-protocol.cert-not-after.cert-not-before.client-cert.client-cert-chain.close.cmcd-object.cmcd-request.cmcd-session.cmcd-status.cmsd-dynamic.cmsd-static.concealed-auth-export.configuration-context.connection.content-digest.content-disposition.content-encoding.content-id.content-language.content-length.content-location.content-md5.content-range.content-script-type.content-type.cookie.cookie2.cross-origin-embedder-policy.cross-origin-embedder-policy-report-only.cross-origin-opener-policy.cross-origin-opener-policy-report-only.cross-origin-resource-policy.cta-common-access-token.dasl.date.dav.default-style.delta-base.deprecation.depth.derived-from.destination.detached-jws.differential-id.dictionary-id.digest.dpop.dpop-nonce.early-data.ediint-features.expect.expect-ct.ext.forwarded.from.getprofile.hobareg.host.http2-settings.if.if-match.if-modified-since.if-none-match.if-range.if-schedule-tag-match.if-unmodified-since.im.include-referred-token-binding-id.isolation.keep-alive.label.last-event-id.link.link-template.lock-token.man.max-forwards.memento-datetime.meter.method-check.method-check-expires.mime-version.negotiate.nel.odata-entityid.odata-isolation.odata-maxversion.odata-version.opt.ordering-type.origin.origin-agent-cluster.oscore.oslc-core-version.overwrite.p3p.pep.pep-info.permissions-policy.pics-label.ping-from.ping-to.position.pragma.prefer.preference-applied.priority.profileobject.protocol.protocol-info.protocol-query.protocol-request.proxy-authorization.proxy-features.proxy-instruction.public.public-key-pins.public-key-pins-report-only.range.redirect-ref.referer.referer-root.referrer-policy.repeatability-client-id.repeatability-first-sent.repeatability-request-id.repeatability-result.replay-nonce.reporting-endpoints.repr-digest.safe.schedule-reply.schedule-tag.sec-fetch-storage-access.sec-gpc.sec-purpose.sec-token-binding.sec-websocket-extensions.sec-websocket-key.sec-websocket-protocol.sec-websocket-version.security-scheme.setprofile.signature.signature-input.slug.soapaction.status-uri.sunset.surrogate-capability.tcn.te.timeout.topic.traceparent.tracestate.trailer.transfer-encoding.ttl.upgrade.urgency.uri.use-as-dictionary.user-agent.variant-vary.via.want-content-digest.want-digest.want-repr-digest.warning.x-content-type-options.x-frame-options`.split(`.`);const tn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,nn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},rn=e=>e.replace(ue,e=>`{${e.slice(1)}}`),an=({},e)=>{if(e.isResponse)throw new N(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},on=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),sn=({zodSchema:e,jsonSchema:t})=>{if(!T(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},cn=n.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return J(e,`throw`)},(e,{jsonSchema:t})=>t),ln=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:hn(t.type)})},Y=e=>e,un=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new N(`Please use ez.dateOut() for output.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,pattern:`^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?)?Z?$`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},dn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new N(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},fn=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),pn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,mn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return nn?.[t]},hn=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],gn=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!T(r,`transform`))return t;let a=Y(Cn(i,{ctx:n}));if(b(a))if(n.isResponse){let e=ye(r,mn(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},_n=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!O(t.properties.raw)?e:t.properties.raw},vn=e=>e.length?n.fromPairs(n.zip(n.times(e=>`example${e+1}`,e.length),n.map(n.objOf(`value`),e))):void 0,yn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||en.includes(e),bn=({path:e,method:t,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let u=J(r),d=de(e),f=i.includes(`query`),p=i.includes(`params`),m=i.includes(`headers`),h=e=>p&&d.includes(e),g=n.chain(n.filter(e=>e.type===`header`),c??[]).map(({name:e})=>e),_=n=>m&&(s?.(n,t,e)??yn(n,g));return Object.entries(u.properties).reduce((e,[t,r])=>{if(!O(r))return e;let i=h(t)?`path`:_(t)?`header`:f?`query`:void 0;if(!i)return e;let s=Y(r),c=o===`components`?a(r.id||JSON.stringify(r),s,r.id||D(l,t)):s;return e.concat({name:t,in:i,deprecated:r.deprecated,required:u.required?.includes(t)||!1,description:s.description||l,schema:c,examples:vn(b(s)&&s.examples?.length?s.examples:n.pluck(t,u.examples?.filter(n.both(O,n.has(t)))||[]))})},[])},xn={nullable:ln,union:sn,bigint:fn,intersection:cn,tuple:pn,pipe:gn,[A]:un,[j]:dn,[F]:an,[I]:_n,[k]:on},Sn=(e,t,r)=>{let i=[e,t];for(;i.length;){let e=i.shift();if(n.is(Object,e)){if(re(e)&&!e.$ref.startsWith(`#/components`)){let n=t[e.$ref.split(`/`).pop()];n&&(e.$ref=r.makeRef(n.id||n,Y(n),n.id).$ref);continue}i.push(...n.values(e))}n.is(Array,e)&&i.push(...n.values(e))}return e},Cn=(e,{ctx:n,rules:r=xn})=>{let{$defs:a={},properties:o={}}=i.toJSONSchema(i.object({subject:e}),{unrepresentable:`any`,io:n.isResponse?`output`:`input`,override:e=>{let i=t(e.zodSchema),a=r[i&&i in r?i:e.zodSchema._zod.def.type];if(a){let t={...a(e,n)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,t)}}});return Sn(O(o.subject)?o.subject:{},a,n)},wn=(e,t)=>{if(re(e))return[e,!1];let r=!1,i=n.map(e=>{let[n,i]=wn(e,t);return r||=i,n}),a=n.omit(t),o={properties:a,examples:n.map(a),required:n.without(t),allOf:i,oneOf:i,anyOf:i},s=n.evolve(o,e);return[s,r||!!s.required?.length]},Tn=({method:e,path:t,schema:r,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${t} ${ve(a)} response ${c?l:``}`.trim()})=>{if(!xe(e,i))return{description:d};let f=Y(Cn(r,{rules:{...u,...xn},ctx:{isResponse:!0,makeRef:o,path:t,method:e}})),p=[];b(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(r,f,D(d)):f,examples:vn(p)};return{description:d,content:n.fromPairs(n.xprod(i,[m]))}},En=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Dn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},On=({name:e})=>({type:`apiKey`,in:`header`,name:e}),kn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),An=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),jn=({flows:e={}})=>({type:`oauth2`,flows:n.map(e=>({...e,scopes:e.scopes||{}}),n.reject(n.isNil,e))}),Mn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?En(e):e.type===`input`?Dn(e,t):e.type===`header`?On(e):e.type===`cookie`?kn(e):e.type===`openid`?An(e):jn(e);return e.map(e=>e.map(n))},Nn=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),Pn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Cn(e,{rules:{...t,...xn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Fn=({method:e,path:t,schema:r,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let[u,d]=wn(Y(i),c),f=[];b(u)&&u.examples&&(f.push(...u.examples),delete u.examples);let p={schema:s===`components`?o(r,u,D(l)):u,examples:vn(f.length?f:J(i).examples?.filter(e=>O(e)&&!Array.isArray(e)).map(n.omit(c))||[])},m={description:l,content:{[a]:p}};return(d||a===x.raw)&&(m.required=!0),m},In=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;let r={name:t,description:typeof n==`string`?n:n.description};return typeof n==`object`&&n.url&&(r.externalDocs={url:n.url}),e.concat(r)},[]),Ln=e=>e.length<=50?e:e.slice(0,49)+`…`,X=e=>e.length?e.slice():void 0;var Rn=class extends ne{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n){let r=this.#n.get(e);if(!r){let t=n?0:1;do r=`${n??`Schema`}${t?this.#n.size+t:``}`,t++;while(this.rootDoc.components?.schemas?.[r]);this.#n.set(e,r)}return this.addSchema(r,t),{$ref:`#/components/schemas/${r}`}}#i(e,t,n){let r=n||D(t,e),i=this.#t.get(r);if(i===void 0)return this.#t.set(r,1),r;if(n)throw new N(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#t.set(r,i),`${r}${i}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}constructor({routing:e,config:t,title:r,version:i,serverUrl:a,descriptions:o,brandHandling:s,tags:c,isHeader:l,hasSummaryFromDescription:u=!0,hasHeadMethod:d=!0,composition:f=`inline`}){super(),this.addInfo({title:r,version:i});for(let e of typeof a==`string`?[a]:a)this.addServer({url:e});let p=(e,r,i)=>{let a={path:r,method:e,endpoint:i,composition:f,brandHandling:s,makeRef:this.#r.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,h=d?Ln(d):u&&c?Ln(c):void 0,g=ge(e,t.inputSources),_=this.#i(r,e,i.getOperationId(e)),v=Pn({...a,schema:m}),y=$t(i.security),ee=bn({...a,inputSources:g,isHeader:l,security:y,request:v,description:o?.requestParameter?.call(null,{method:e,path:r,operationId:_})}),te={};for(let t of H){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)te[l]=Tn({...a,variant:t,schema:s,mimeTypes:i,statusCode:l,hasMultipleStatusCodes:n.length>1||c.length>1,description:o?.[`${t}Response`]?.call(null,{method:e,path:r,operationId:_,statusCode:l})})}let ne=g.includes(`body`)?Fn({...a,request:v,paramNames:n.pluck(`name`,ee),schema:m,mimeType:x[i.requestType],description:o?.requestBody?.call(null,{method:e,path:r,operationId:_})}):void 0,re=Nn(Mn(y,g),p,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),b={operationId:_,summary:h,description:c,deprecated:i.isDeprecated||void 0,tags:X(i.tags),parameters:X(ee),requestBody:ne,security:X(re),responses:te};this.addPath(rn(r),{[e]:b})};Ct({routing:e,config:t,onEndpoint:d?gt(p):p}),c&&(this.rootDoc.tags=In(c))}};const zn=e=>ie({...e,headers:{"content-type":x.json,...e?.headers}}),Bn=e=>ae(e),Vn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:it(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},Hn=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=zn(e),a=Bn({req:i,...t});a.req=t?.req||i,i.res=a;let o=Vn(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},Un=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=Hn(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},Wn=async({middleware:e,ctx:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=W}}=Hn(n),c={request:r,response:i,logger:a,input:_e(r,o),ctx:t};try{return{requestMock:r,responseMock:i,loggerMock:a,output:await e.execute(c)}}catch(e){return await s.execute({...c,error:C(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}};var Gn=class t{ts;f;exportModifier;asyncModifier;accessModifiers;#e;static#t=/^[A-Za-z_$][A-Za-z0-9_$]*$/;constructor(){this.ts=e(import.meta.url)(`typescript`),this.f=this.ts.factory,this.exportModifier=[this.f.createModifier(this.ts.SyntaxKind.ExportKeyword)],this.asyncModifier=[this.f.createModifier(this.ts.SyntaxKind.AsyncKeyword)],this.accessModifiers={public:[this.f.createModifier(this.ts.SyntaxKind.PublicKeyword)],protectedReadonly:[this.f.createModifier(this.ts.SyntaxKind.ProtectedKeyword),this.f.createModifier(this.ts.SyntaxKind.ReadonlyKeyword)]},this.#e=[this.ts.SyntaxKind.AnyKeyword,this.ts.SyntaxKind.BigIntKeyword,this.ts.SyntaxKind.BooleanKeyword,this.ts.SyntaxKind.NeverKeyword,this.ts.SyntaxKind.NumberKeyword,this.ts.SyntaxKind.ObjectKeyword,this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.SymbolKeyword,this.ts.SyntaxKind.UndefinedKeyword,this.ts.SyntaxKind.UnknownKeyword,this.ts.SyntaxKind.VoidKeyword]}addJsDoc=(e,t)=>this.ts.addSyntheticLeadingComment(e,this.ts.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0);printNode=(e,t)=>{let n=this.ts.createSourceFile(`print.ts`,``,this.ts.ScriptTarget.Latest,!1,this.ts.ScriptKind.TS);return this.ts.createPrinter(t).printNode(this.ts.EmitHint.Unspecified,e,n)};makePropertyIdentifier=e=>typeof e==`string`&&t.#t.test(e)?this.f.createIdentifier(e):this.literally(e);makeTemplate=(e,...t)=>this.f.createTemplateExpression(this.f.createTemplateHead(e),t.map(([e,n=``],r)=>this.f.createTemplateSpan(e,r===t.length-1?this.f.createTemplateTail(n):this.f.createTemplateMiddle(n))));makeParam=(e,{type:t,mod:n,init:r,optional:i}={})=>this.f.createParameterDeclaration(n,void 0,e,i?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,t?this.ensureTypeNode(t):void 0,r);makeParams=e=>Object.entries(e).map(([e,t])=>this.makeParam(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t));makePublicConstructor=(e,t=[])=>this.f.createConstructorDeclaration(this.accessModifiers.public,e,this.f.createBlock(t));ensureTypeNode=(e,t)=>typeof e==`number`?this.f.createKeywordTypeNode(e):typeof e==`string`||this.ts.isIdentifier(e)?this.f.createTypeReferenceNode(e,t&&n.map(this.ensureTypeNode.bind(this),t)):e;makeRecordStringAny=()=>this.ensureTypeNode(`Record`,[this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.AnyKeyword]);makeUnion=e=>{let t=new Map;for(let n of e)t.set(this.isPrimitive(n)?n.kind:n,n);return this.f.createUnionTypeNode(Array.from(t.values()))};makeInterfaceProp=(e,t,{isOptional:r,hasUndefined:i=r,isDeprecated:a,comment:o}={})=>{let s=this.ensureTypeNode(t),c=this.f.createPropertySignature(void 0,this.makePropertyIdentifier(e),r?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,i?this.makeUnion([s,this.ensureTypeNode(this.ts.SyntaxKind.UndefinedKeyword)]):s),l=n.reject(n.isNil,[a?`@deprecated`:void 0,o]);return l.length?this.addJsDoc(c,l.join(` `)):c};makeOneLine=e=>this.ts.setEmitFlags(e,this.ts.EmitFlags.SingleLine);makeDeconstruction=(...e)=>this.f.createArrayBindingPattern(e.map(e=>this.f.createBindingElement(void 0,void 0,e)));makeConst=(e,t,{type:n,expose:r}={})=>this.f.createVariableStatement(r&&this.exportModifier,this.f.createVariableDeclarationList([this.f.createVariableDeclaration(e,void 0,n?this.ensureTypeNode(n):void 0,t)],this.ts.NodeFlags.Const));makePublicLiteralType=(e,t)=>this.makeType(e,this.makeUnion(n.map(this.makeLiteralType.bind(this),t)),{expose:!0});makeType=(e,t,{expose:n,comment:r,params:i}={})=>{let a=this.f.createTypeAliasDeclaration(n?this.exportModifier:void 0,e,i&&this.makeTypeParams(i),t);return r?this.addJsDoc(a,r):a};makePublicProperty=(e,t)=>this.f.createPropertyDeclaration(this.accessModifiers.public,e,void 0,this.ensureTypeNode(t),void 0);makePublicMethod=(e,t,n,{typeParams:r,returns:i}={})=>this.f.createMethodDeclaration(this.accessModifiers.public,void 0,e,void 0,r&&this.makeTypeParams(r),t,i,this.f.createBlock(n));makePublicClass=(e,t,{typeParams:n}={})=>this.f.createClassDeclaration(this.exportModifier,e,n&&this.makeTypeParams(n),void 0,t);makeKeyOf=e=>this.f.createTypeOperatorNode(this.ts.SyntaxKind.KeyOfKeyword,this.ensureTypeNode(e));makePromise=e=>this.ensureTypeNode(Promise.name,[e]);makeInterface=(e,t,{expose:n,comment:r}={})=>{let i=this.f.createInterfaceDeclaration(n?this.exportModifier:void 0,e,void 0,void 0,t);return r?this.addJsDoc(i,r):i};makeTypeParams=e=>(Array.isArray(e)?e.map(e=>n.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return this.f.createTypeParameterDeclaration([],e,n?this.ensureTypeNode(n):void 0,r?this.ensureTypeNode(r):void 0)});makeArrowFn=(e,t,{isAsync:r}={})=>this.f.createArrowFunction(r?this.asyncModifier:void 0,void 0,Array.isArray(e)?n.map(this.makeParam.bind(this),e):this.makeParams(e),void 0,void 0,t);makeTernary=(e,t,n)=>this.f.createConditionalExpression(e,this.f.createToken(this.ts.SyntaxKind.QuestionToken),t,this.f.createToken(this.ts.SyntaxKind.ColonToken),n);makeCall=(e,...t)=>(...n)=>this.f.createCallExpression(t.reduce((e,t)=>typeof t==`string`||this.ts.isIdentifier(t)?this.f.createPropertyAccessExpression(e,t):this.f.createElementAccessExpression(e,t),typeof e==`string`?this.f.createIdentifier(e):e),void 0,n);makeNew=(e,...t)=>this.f.createNewExpression(this.f.createIdentifier(e),void 0,t);makeExtract=(e,t)=>this.ensureTypeNode(`Extract`,[e,t]);makeAssignment=(e,t)=>this.f.createExpressionStatement(this.f.createBinaryExpression(e,this.f.createToken(this.ts.SyntaxKind.EqualsToken),t));makeIndexed=(e,t)=>this.f.createIndexedAccessTypeNode(this.ensureTypeNode(e),this.ensureTypeNode(t));makeMaybeAsync=e=>this.makeUnion([this.ensureTypeNode(e),this.makePromise(e)]);makeFnType=(e,t)=>this.f.createFunctionTypeNode(void 0,this.makeParams(e),this.ensureTypeNode(t));literally=e=>typeof e==`number`?this.f.createNumericLiteral(e):typeof e==`bigint`?this.f.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?this.f.createTrue():this.f.createFalse():e===null?this.f.createNull():this.f.createStringLiteral(e);makeLiteralType=e=>this.f.createLiteralTypeNode(this.literally(e));isPrimitive=e=>this.#e.includes(e.kind)};const Z=e=>e;var Kn=class{api=new Gn;paths=new Set;tags=new Map;registry=new Map;#e={pathType:this.api.f.createIdentifier(`Path`),implementationType:this.api.f.createIdentifier(`Implementation`),keyParameter:this.api.f.createIdentifier(`key`),pathParameter:this.api.f.createIdentifier(`path`),paramsArgument:this.api.f.createIdentifier(`params`),ctxArgument:this.api.f.createIdentifier(`ctx`),methodParameter:this.api.f.createIdentifier(`method`),requestParameter:this.api.f.createIdentifier(`request`),eventParameter:this.api.f.createIdentifier(`event`),dataParameter:this.api.f.createIdentifier(`data`),handlerParameter:this.api.f.createIdentifier(`handler`),msgParameter:this.api.f.createIdentifier(`msg`),parseRequestFn:this.api.f.createIdentifier(`parseRequest`),substituteFn:this.api.f.createIdentifier(`substitute`),provideMethod:this.api.f.createIdentifier(`provide`),onMethod:this.api.f.createIdentifier(`on`),implementationArgument:this.api.f.createIdentifier(`implementation`),hasBodyConst:this.api.f.createIdentifier(`hasBody`),undefinedValue:this.api.f.createIdentifier(`undefined`),responseConst:this.api.f.createIdentifier(`response`),restConst:this.api.f.createIdentifier(`rest`),searchParamsConst:this.api.f.createIdentifier(`searchParams`),defaultImplementationConst:this.api.f.createIdentifier(`defaultImplementation`),clientConst:this.api.f.createIdentifier(`client`),contentTypeConst:this.api.f.createIdentifier(`contentType`),isJsonConst:this.api.f.createIdentifier(`isJSON`),sourceProp:this.api.f.createIdentifier(`source`)};interfaces={input:this.api.f.createIdentifier(`Input`),positive:this.api.f.createIdentifier(`PositiveResponse`),negative:this.api.f.createIdentifier(`NegativeResponse`),encoded:this.api.f.createIdentifier(`EncodedResponse`),response:this.api.f.createIdentifier(`Response`)};methodType=this.api.makePublicLiteralType(`Method`,ce);someOfType=this.api.makeType(`SomeOf`,this.api.makeIndexed(`T`,this.api.makeKeyOf(`T`)),{params:[`T`]});requestType=this.api.makeType(`Request`,this.api.makeKeyOf(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>this.api.ensureTypeNode(this.someOfType.name,[e]);makePathType=()=>this.api.makePublicLiteralType(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>this.api.makeInterface(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>this.api.makeInterfaceProp(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>this.api.makeConst(`endpointTags`,this.api.f.createObjectLiteralExpression(Array.from(this.tags).map(([e,t])=>this.api.f.createPropertyAssignment(this.api.makePropertyIdentifier(e),this.api.f.createArrayLiteralExpression(n.map(this.api.literally.bind(this.api),t))))),{expose:!0});makeImplementationType=()=>this.api.makeType(this.#e.implementationType,this.api.makeFnType({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.api.makeRecordStringAny(),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}},this.api.makePromise(this.api.ts.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:this.api.ts.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>this.api.makeConst(this.#e.parseRequestFn,this.api.makeArrowFn({[this.#e.requestParameter.text]:this.api.ts.SyntaxKind.StringKeyword},this.api.f.createAsExpression(this.api.makeCall(this.#e.requestParameter,Z(`split`))(this.api.f.createRegularExpressionLiteral(`/ (.+)/`),this.api.literally(2)),this.api.f.createTupleTypeNode([this.api.ensureTypeNode(this.methodType.name),this.api.ensureTypeNode(this.#e.pathType)]))));makeSubstituteFn=()=>this.api.makeConst(this.#e.substituteFn,this.api.makeArrowFn({[this.#e.pathParameter.text]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.api.makeRecordStringAny()},this.api.f.createBlock([this.api.makeConst(this.#e.restConst,this.api.f.createObjectLiteralExpression([this.api.f.createSpreadAssignment(this.#e.paramsArgument)])),this.api.f.createForInStatement(this.api.f.createVariableDeclarationList([this.api.f.createVariableDeclaration(this.#e.keyParameter)],this.api.ts.NodeFlags.Const),this.#e.paramsArgument,this.api.f.createBlock([this.api.makeAssignment(this.#e.pathParameter,this.api.makeCall(this.#e.pathParameter,Z(`replace`))(this.api.makeTemplate(`:`,[this.#e.keyParameter]),this.api.makeArrowFn([],this.api.f.createBlock([this.api.f.createExpressionStatement(this.api.f.createDeleteExpression(this.api.f.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),this.api.f.createReturnStatement(this.api.f.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),this.api.f.createReturnStatement(this.api.f.createAsExpression(this.api.f.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),this.api.ensureTypeNode(`const`)))])));#t=()=>this.api.makePublicMethod(this.#e.provideMethod,this.api.makeParams({[this.#e.requestParameter.text]:`K`,[this.#e.paramsArgument.text]:this.api.makeIndexed(this.interfaces.input,`K`),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.methodParameter,this.#e.pathParameter),this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter)),this.api.f.createReturnStatement(this.api.makeCall(this.api.f.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,this.api.f.createSpreadElement(this.api.makeCall(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:this.api.makePromise(this.api.makeIndexed(this.interfaces.response,`K`))});makeClientClass=e=>this.api.makePublicClass(e,[this.api.makePublicConstructor([this.api.makeParam(this.#e.implementationArgument,{type:this.api.ensureTypeNode(this.#e.implementationType,[`T`]),mod:this.api.accessModifiers.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:[`T`]});#n=e=>this.api.makeTemplate(`?`,[this.api.makeNew(URLSearchParams.name,e)]);#r=()=>this.api.makeNew(URL.name,this.api.makeTemplate(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),this.api.literally(this.serverUrl));makeDefaultImplementation=()=>{let e=this.api.f.createPropertyAssignment(Z(`method`),this.api.makeCall(this.#e.methodParameter,Z(`toUpperCase`))()),t=this.api.f.createPropertyAssignment(Z(`headers`),this.api.makeTernary(this.#e.hasBodyConst,this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(this.api.literally(`Content-Type`),this.api.literally(x.json))]),this.#e.undefinedValue)),n=this.api.f.createPropertyAssignment(Z(`body`),this.api.makeTernary(this.#e.hasBodyConst,this.api.makeCall(JSON[Symbol.toStringTag],Z(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=this.api.makeConst(this.#e.responseConst,this.api.f.createAwaitExpression(this.api.makeCall(fetch.name)(this.#r(),this.api.f.createObjectLiteralExpression([e,t,n])))),i=this.api.makeConst(this.#e.hasBodyConst,this.api.f.createLogicalNot(this.api.makeCall(this.api.f.createArrayLiteralExpression([this.api.literally(`get`),this.api.literally(`head`),this.api.literally(`delete`)]),Z(`includes`))(this.#e.methodParameter))),a=this.api.makeConst(this.#e.searchParamsConst,this.api.makeTernary(this.#e.hasBodyConst,this.api.literally(``),this.#n(this.#e.paramsArgument))),o=this.api.makeConst(this.#e.contentTypeConst,this.api.makeCall(this.#e.responseConst,Z(`headers`),Z(`get`))(this.api.literally(`content-type`))),s=this.api.f.createIfStatement(this.api.f.createPrefixUnaryExpression(this.api.ts.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),this.api.f.createReturnStatement()),c=this.api.makeConst(this.#e.isJsonConst,this.api.makeCall(this.#e.contentTypeConst,Z(`startsWith`))(this.api.literally(x.json))),l=this.api.f.createReturnStatement(this.api.makeCall(this.#e.responseConst,this.api.makeTernary(this.#e.isJsonConst,this.api.literally(Z(`json`)),this.api.literally(Z(`text`))))());return this.api.makeConst(this.#e.defaultImplementationConst,this.api.makeArrowFn([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],this.api.f.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#e.implementationType})};#i=()=>this.api.makePublicConstructor(this.api.makeParams({request:`K`,params:this.api.makeIndexed(this.interfaces.input,`K`)}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.pathParameter,this.#e.restConst),this.api.makeCall(this.#e.substituteFn)(this.api.f.createElementAccessExpression(this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter),this.api.literally(1)),this.#e.paramsArgument)),this.api.makeConst(this.#e.searchParamsConst,this.#n(this.#e.restConst)),this.api.makeAssignment(this.api.f.createPropertyAccessExpression(this.api.f.createThis(),this.#e.sourceProp),this.api.makeNew(`EventSource`,this.#r()))]);#a=e=>this.api.f.createTypeLiteralNode([this.api.makeInterfaceProp(Z(`event`),e)]);#o=()=>this.api.makePublicMethod(this.#e.onMethod,this.api.makeParams({[this.#e.eventParameter.text]:`E`,[this.#e.handlerParameter.text]:this.api.makeFnType({[this.#e.dataParameter.text]:this.api.makeIndexed(this.api.makeExtract(`R`,this.api.makeOneLine(this.#a(`E`))),this.api.makeLiteralType(Z(`data`)))},this.api.makeMaybeAsync(this.api.ts.SyntaxKind.VoidKeyword))}),[this.api.f.createExpressionStatement(this.api.makeCall(this.api.f.createThis(),this.#e.sourceProp,Z(`addEventListener`))(this.#e.eventParameter,this.api.makeArrowFn([this.#e.msgParameter],this.api.makeCall(this.#e.handlerParameter)(this.api.makeCall(JSON[Symbol.toStringTag],Z(`parse`))(this.api.f.createPropertyAccessExpression(this.api.f.createParenthesizedExpression(this.api.f.createAsExpression(this.#e.msgParameter,this.api.ensureTypeNode(MessageEvent.name))),Z(`data`))))))),this.api.f.createReturnStatement(this.api.f.createThis())],{typeParams:{E:this.api.makeIndexed(`R`,this.api.makeLiteralType(Z(`event`)))}});makeSubscriptionClass=e=>this.api.makePublicClass(e,[this.api.makePublicProperty(this.#e.sourceProp,`EventSource`),this.#i(),this.#o()],{typeParams:{K:this.api.makeExtract(this.requestType.name,this.api.f.createTemplateLiteralType(this.api.f.createTemplateHead(`get `),[this.api.f.createTemplateLiteralTypeSpan(this.api.ensureTypeNode(this.api.ts.SyntaxKind.StringKeyword),this.api.f.createTemplateTail(``))])),R:this.api.makeExtract(this.api.makeIndexed(this.interfaces.positive,`K`),this.api.makeOneLine(this.#a(this.api.ts.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[this.api.makeConst(this.#e.clientConst,this.api.makeNew(e)),this.api.makeCall(this.#e.clientConst,this.#e.provideMethod)(this.api.literally(`get /v1/user/retrieve`),this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(`id`,this.api.literally(`10`))])),this.api.makeCall(this.api.makeNew(t,this.api.literally(`get /v1/events/stream`),this.api.f.createObjectLiteralExpression()),this.#e.onMethod)(this.api.literally(`time`),this.api.makeArrowFn([`time`],this.api.f.createBlock([])))]};const qn=(e,{onEach:n,rules:r,onMissing:i,ctx:a={}})=>{let o=t(e),s=o&&o in r?r[o]:r[e._zod.def.type],c=e=>qn(e,{ctx:a,onEach:n,rules:r,onMissing:i}),l=s?s(e,{...a,next:c}):i(e,a),u=n&&n(e,{prev:l,...a});return u?{...l,...u}:l},Jn={name:n.path([`name`,`text`]),type:n.path([`type`]),optional:n.path([`questionToken`])},Yn=({_zod:{def:e}},{api:t})=>{let n=e.values.map(e=>e===void 0?t.ensureTypeNode(t.ts.SyntaxKind.UndefinedKeyword):t.makeLiteralType(e));return n.length===1?n[0]:t.makeUnion(n)},Xn=({_zod:{def:e}},{next:t,api:n})=>{let r=[...e.parts],i=()=>{let e=``;for(;r.length;){let t=r.shift();if(T(t)){r.unshift(t);break}e+=t??``}return e},a=n.f.createTemplateHead(i()),o=[];for(;r.length;){let e=t(r.shift()),a=i(),s=r.length?n.f.createTemplateMiddle:n.f.createTemplateTail;o.push(n.f.createTemplateLiteralTypeSpan(e,s(a)))}return o.length?n.f.createTemplateLiteralType(a,o):n.makeLiteralType(a.text)},Zn=(e,{isResponse:t,next:n,makeAlias:a,api:o})=>{let s=()=>{let a=Object.entries(e._zod.def.shape).map(([e,a])=>{let{description:s,deprecated:c}=r.get(a)||{},l=(t?a._zod.optout:a._zod.optin)===`optional`,u=l&&!(a instanceof i.core.$ZodExactOptional);return o.makeInterfaceProp(e,n(a),{comment:s,isDeprecated:c,isOptional:l,hasUndefined:u})});return o.f.createTypeLiteralNode(a)};return Le(e,{io:t?`output`:`input`})?a(e,s):s()},Qn=({_zod:{def:e}},{next:t,api:n})=>n.f.createArrayTypeNode(t(e.element)),$n=({_zod:{def:e}},{api:t})=>t.makeUnion(Object.values(e.entries).map(t.makeLiteralType.bind(t))),er=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion(e.options.map(t)),tr=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion([t(e.innerType),n.makeLiteralType(null)]),nr=({_zod:{def:e}},{next:t,api:n})=>n.f.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:n.f.createRestTypeNode(t(e.rest)))),rr=({_zod:{def:e}},{next:t,api:n})=>{let[r,i]=[e.keyType,e.valueType].map(t),a=n.ensureTypeNode(`Record`,[r,i]);return e.mode===`loose`?n.f.createIntersectionTypeNode([a,n.ensureTypeNode(`Record`,[`PropertyKey`,i])]):a},ir=n.tryCatch((e,t)=>{if(!t.every(e.ts.isTypeLiteralNode))throw Error(`Not objects`);let r=n.chain(n.prop(`members`),t),i=n.uniqWith((...e)=>{if(!n.eqBy(Jn.name,...e))return!1;if(n.both(n.eqBy(Jn.type),n.eqBy(Jn.optional))(...e))return!0;throw Error(`Has conflicting prop`)},r);return e.f.createTypeLiteralNode(i)},(e,t,n)=>t.f.createIntersectionTypeNode(n)),ar=({_zod:{def:e}},{next:t,api:n})=>ir(n,[e.left,e.right].map(t)),Q=e=>({},{api:t})=>t.ensureTypeNode(t.ts.SyntaxKind[e]),$=({_zod:{def:e}},{next:t})=>t(e.innerType),or=(e,t)=>e.ensureTypeNode(t?e.ts.SyntaxKind.UnknownKeyword:e.ts.SyntaxKind.AnyKeyword),sr=({_zod:{def:e}},{next:t,isResponse:n,api:r})=>{let i=e[n?`out`:`in`],a=e[n?`in`:`out`];if(!T(i,`transform`))return t(i);let o=t(a),s={[r.ts.SyntaxKind.AnyKeyword]:``,[r.ts.SyntaxKind.BigIntKeyword]:BigInt(0),[r.ts.SyntaxKind.BooleanKeyword]:!1,[r.ts.SyntaxKind.NumberKeyword]:0,[r.ts.SyntaxKind.ObjectKeyword]:{},[r.ts.SyntaxKind.StringKeyword]:``,[r.ts.SyntaxKind.UndefinedKeyword]:void 0}[o.kind],c=ye(i,s),l={number:r.ts.SyntaxKind.NumberKeyword,bigint:r.ts.SyntaxKind.BigIntKeyword,boolean:r.ts.SyntaxKind.BooleanKeyword,string:r.ts.SyntaxKind.StringKeyword,undefined:r.ts.SyntaxKind.UndefinedKeyword,object:r.ts.SyntaxKind.ObjectKeyword};return r.ensureTypeNode(c&&l[c]||or(r,n))},cr=({},{api:e})=>e.makeLiteralType(null),lr=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ur=({},{api:e})=>e.ensureTypeNode(`Buffer`),dr=(e,{next:t})=>t(e._zod.def.shape.raw),fr={string:Q(`StringKeyword`),number:Q(`NumberKeyword`),bigint:Q(`BigIntKeyword`),boolean:Q(`BooleanKeyword`),any:Q(`AnyKeyword`),undefined:Q(`UndefinedKeyword`),[A]:Q(`StringKeyword`),[j]:Q(`StringKeyword`),never:Q(`NeverKeyword`),void:Q(`UndefinedKeyword`),unknown:Q(`UnknownKeyword`),null:cr,array:Qn,tuple:nr,record:rr,object:Zn,literal:Yn,template_literal:Xn,intersection:ar,union:er,default:$,enum:$n,optional:$,nonoptional:$,nullable:tr,catch:$,pipe:sr,lazy:lr,readonly:$,[k]:ur,[I]:dr},pr=(e,{brandHandling:t,ctx:n})=>qn(e,{rules:{...t,...fr},onMissing:({},{isResponse:e,api:t})=>or(t,e),ctx:n});var mr=class extends Kn{#e=[this.someOfType];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=this.api.makeLiteralType(null);this.#t.set(e,this.api.makeType(n,r)),this.#t.set(e,this.api.makeType(n,t()))}return this.api.ensureTypeNode(n)}constructor({routing:e,config:t,brandHandling:r,variant:a=`client`,clientClassName:o=`Client`,subscriptionClassName:s=`Subscription`,serverUrl:c=`https://example.com`,noContent:l=i.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this),api:this.api},f={brandHandling:r,ctx:{...d,isResponse:!1}},p={brandHandling:r,ctx:{...d,isResponse:!0}},m=(e,t,r)=>{let i=D.bind(null,e,t),{isDeprecated:a,inputSchema:o,tags:s}=r,c=`${e} ${t}`,u=this.api.makeType(i(`input`),pr(o,f),{comment:c});this.#e.push(u);let d=H.reduce((t,a)=>{let o=r.getResponses(a),s=n.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=xe(e,r),u=this.api.makeType(i(a,`variant`,`${t+1}`),pr(s?n:l,p),{comment:c});return this.#e.push(u),o.map(e=>this.api.makeInterfaceProp(e,u.name))},Array.from(o.entries())),u=this.api.makeInterface(i(a,`response`,`variants`),s,{comment:c});return this.#e.push(u),Object.assign(t,{[a]:u})},{});this.paths.add(t);let m=this.api.makeLiteralType(c),h={input:this.api.ensureTypeNode(u.name),positive:this.someOf(d.positive),negative:this.someOf(d.negative),response:this.api.makeUnion([this.api.makeIndexed(this.interfaces.positive,m),this.api.makeIndexed(this.interfaces.negative,m)]),encoded:this.api.f.createIntersectionTypeNode([this.api.ensureTypeNode(d.positive.name),this.api.ensureTypeNode(d.negative.name)])};this.registry.set(c,{isDeprecated:a,store:h}),this.tags.set(c,s)};Ct({routing:e,config:t,onEndpoint:u?gt(m):m}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),a!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(o),this.makeSubscriptionClass(s)),this.#n.push(...this.makeUsageStatements(o,s)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:this.api.printNode(t,e)).join(`
|
|
18
18
|
`):void 0}print(e){let t=this.#i(e),n=t&&this.api.ts.addSyntheticLeadingComment(this.api.ts.addSyntheticLeadingComment(this.api.f.createEmptyStatement(),this.api.ts.SyntaxKind.SingleLineCommentTrivia,` Usage example:`),this.api.ts.SyntaxKind.MultiLineCommentTrivia,`\n${t}`);return this.#e.concat(n||[]).map((t,n)=>this.api.printNode(t,n<this.#e.length?e:{...e,omitTrailingSemicolon:!0})).join(`
|
|
19
19
|
|
|
20
20
|
`)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=(await lt(`prettier`)).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#i(e);this.#n=r&&n?[await n(r)]:this.#n;let i=this.print(e);return n?n(i):i}};const hr=(e,t)=>i.object({data:t,event:i.literal(e),id:i.string().optional(),retry:i.int().positive().optional()}),gr=(e,t,n)=>hr(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "26.3.
|
|
3
|
+
"version": "26.3.2",
|
|
4
4
|
"description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"node-mocks-http": "^1.17.2",
|
|
39
39
|
"openapi3-ts": "^4.5.0",
|
|
40
40
|
"ramda": "^0.32.0",
|
|
41
|
-
"@express-zod-api/zod-plugin": "^3.0.
|
|
41
|
+
"@express-zod-api/zod-plugin": "^3.0.1"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@types/compression": "^1.7.5",
|
|
@@ -92,7 +92,8 @@
|
|
|
92
92
|
"snakify-ts": "^2.3.0",
|
|
93
93
|
"typescript": "^5.9.3",
|
|
94
94
|
"undici": "^7.16.0",
|
|
95
|
-
"zod": "^4.3.4"
|
|
95
|
+
"zod": "^4.3.4",
|
|
96
|
+
"dts-plugin": "^0.1.0"
|
|
96
97
|
},
|
|
97
98
|
"keywords": [
|
|
98
99
|
"nodejs",
|