@tahminator/sapling 2.0.5 → 2.1.0-beta.0e8a97e8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -23,6 +23,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  //#endregion
24
24
  let express = require("express");
25
25
  express = __toESM(express);
26
+ let swagger_ui_express = require("swagger-ui-express");
27
+ swagger_ui_express = __toESM(swagger_ui_express);
26
28
  //#region src/html/404.ts
27
29
  /**
28
30
  * Default Express.js 404 error page, as a string.
@@ -46,6 +48,7 @@ const Html404ErrorPage = (error) => `<!DOCTYPE html>
46
48
  * You can either return `new RedirectView(url)` or `RedirectView.redirect(url)` inside of a controller method.
47
49
  */
48
50
  var RedirectView = class RedirectView {
51
+ _url;
49
52
  constructor(url) {
50
53
  this._url = url;
51
54
  }
@@ -141,8 +144,10 @@ let HttpStatus = /* @__PURE__ */ function(HttpStatus) {
141
144
  * @typeParam T - the type of the response body
142
145
  */
143
146
  var ResponseEntity = class {
147
+ _statusCode;
148
+ _headers = {};
149
+ _body;
144
150
  constructor(body, headers = {}, statusCode = 200) {
145
- this._headers = {};
146
151
  this._body = body;
147
152
  this._headers = headers;
148
153
  this._statusCode = statusCode;
@@ -195,8 +200,9 @@ var ResponseEntity = class {
195
200
  * ensuring type safety when constructing the response.
196
201
  */
197
202
  var ResponseEntityBuilder = class {
203
+ _statusCode;
204
+ _headers = {};
198
205
  constructor(statusCode) {
199
- this._headers = {};
200
206
  this._statusCode = statusCode;
201
207
  }
202
208
  /**
@@ -228,6 +234,7 @@ var ResponseEntityBuilder = class {
228
234
  * @see {@link Sapling.loadResponseStatusErrorMiddleware}
229
235
  */
230
236
  var ResponseStatusError = class ResponseStatusError extends Error {
237
+ status;
231
238
  constructor(status, message) {
232
239
  super(message ?? "Something went wrong.");
233
240
  this.status = status;
@@ -239,150 +246,30 @@ var ResponseStatusError = class ResponseStatusError extends Error {
239
246
  //#endregion
240
247
  //#region src/helper/error/parse.ts
241
248
  /**
242
- * This error should be thrown when some data cannot be parsed by a given schema.
249
+ * This error should be thrown when some data cannot be parsed by a given Standard Schema compatible schema.
243
250
  */
244
251
  var ParserError = class ParserError extends ResponseStatusError {
245
- constructor(location, issues, vendor) {
246
- super(400, ParserError.formatMessage(location, issues, vendor));
252
+ constructor(location, issues, vendor, functionName) {
253
+ super(400, ParserError.formatMessage(location, issues, vendor, functionName));
247
254
  Object.setPrototypeOf(this, new.target.prototype);
248
255
  }
249
- static formatMessage(location, issues, vendor) {
256
+ static formatMessage(location, issues, vendor, functionName) {
250
257
  const formatted = issues.map((i) => {
251
258
  const path = Array.isArray(i.path) ? i.path.map((seg) => typeof seg === "object" && seg ? String(seg.key) : String(seg)).join(".") : "";
252
259
  return path ? `${path}: ${i.message}` : i.message;
253
260
  }).join("; ");
254
- return `${vendor} failed to parse ${(() => {
255
- switch (location) {
256
- case "reqbody": return "request body";
257
- case "reqparams": return "request params";
258
- case "reqquery": return "request query";
259
- }
260
- })()}: ${formatted}`;
261
- }
262
- };
263
- //#endregion
264
- //#region src/helper/sapling.ts
265
- const settings = {
266
- serialize: JSON.stringify,
267
- deserialize: JSON.parse
268
- };
269
- /**
270
- * Collection of utility functions which are essential for Sapling to function.
271
- */
272
- var Sapling = class Sapling {
273
- /**
274
- * If you would prefer to manually resolve your controllers instead, call resolve
275
- * on the controller class.
276
- *
277
- * @example```ts
278
- * import { Sapling } from "@tahminator/sapling";
279
- * import TestController from "./path/to/test.controller";
280
- *
281
- * const app = express();
282
- *
283
- * const router = Sapling.resolve(TestController);
284
- * app.use(router);
285
- * ```
286
- */
287
- static resolve(clazz) {
288
- const router = _ControllerRegistry.get(clazz);
289
- if (!router) throw new Error("Controller cannot be found");
290
- return router;
261
+ return `Failed to parse ${this.getPrettyLocationString(location)} with ${vendor} on ${functionName}: ${formatted}`;
291
262
  }
292
- /**
293
- * Register this function as a middleware in order to utilize Sapling's `deserialize` function.
294
- *
295
- * @example```ts
296
- * import { Sapling } from "@tahminator/sapling";
297
- * import express from "express";
298
- *
299
- * const app = express();
300
- *
301
- * app.use(Sapling.json());
302
- * ```
303
- */
304
- static json() {
305
- return (request, _response, next) => {
306
- try {
307
- if (!request.body) return next();
308
- if (request.headers["content-type"] !== "application/json") return next();
309
- if (typeof request.body === "string") request.body = Sapling.deserialize(request.body);
310
- else if (typeof request.body === "object") {
311
- const raw = JSON.stringify(request.body);
312
- request.body = Sapling.deserialize(raw);
313
- }
314
- next();
315
- } catch (err) {
316
- next(err);
317
- }
318
- };
319
- }
320
- /**
321
- * Register your application with all the necessary middlewares and logics for Sapling to function.
322
- *
323
- * @example```ts
324
- * import { Sapling } from "@tahminator/sapling";
325
- * import express from "express";
326
- *
327
- * const app = express();
328
- *
329
- * app.registerApp(app);
330
- * ```
331
- */
332
- static registerApp(app) {
333
- app.use(express.default.text({ type: "application/json" }));
334
- app.use(Sapling.json());
335
- }
336
- /**
337
- * Serialize a value into a JSON string.
338
- *
339
- * This function is used in {@link ResponseEntity} to serialize the `body`.
340
- *
341
- * Use `setSerializeFn` to override underlying implementation.
342
- *
343
- * @defaultValue `JSON.stringify`
344
- */
345
- static serialize(value) {
346
- return settings.serialize(value);
347
- }
348
- /**
349
- * Replace the function used for `serialize`.
350
- */
351
- static setSerializeFn(fn) {
352
- settings.serialize = fn;
353
- }
354
- /**
355
- * De-serialize a JSON string back to a JavaScript object.
356
- *
357
- * This function is used to de-serialize a string into a `body`.
358
- *
359
- * Use `setDeserializeFn` to override underlying implementation.
360
- *
361
- * @defaultValue `JSON.parse`
362
- */
363
- static deserialize(value) {
364
- return settings.deserialize(value);
365
- }
366
- /**
367
- * Replace the function used for `deserialize`
368
- */
369
- static setDeserializeFn(fn) {
370
- settings.deserialize = fn;
263
+ static getPrettyLocationString(location) {
264
+ switch (location) {
265
+ case "reqbody": return "request body";
266
+ case "reqparams": return "request params";
267
+ case "reqquery": return "request query";
268
+ case "resbody": return "response body";
269
+ }
371
270
  }
372
271
  };
373
272
  //#endregion
374
- //#region src/types.ts
375
- const methodResolve = {
376
- GET: "get",
377
- PUT: "put",
378
- POST: "post",
379
- DELETE: "delete",
380
- OPTIONS: "options",
381
- PATCH: "patch",
382
- HEAD: "head",
383
- USE: "use"
384
- };
385
- //#endregion
386
273
  //#region lib/weakmap.ts
387
274
  /**
388
275
  * WeakMap that is iterable.
@@ -503,132 +390,220 @@ function _resolve(ctor) {
503
390
  return _InjectableRegistry.get(ctor);
504
391
  }
505
392
  //#endregion
506
- //#region src/annotation/request.ts
507
- const _requestSchemaStore = /* @__PURE__ */ new WeakMap();
508
- /**
509
- * Apply to a route method to have `request.body` be parsed by `schema`.
510
- *
511
- * This annotation will parse `request.body` & then override `request.body`.
512
- * You can then just simply cast `request.body` for your use
513
- *
514
- * @example
515
- * ```ts
516
- * const CREATE_BOOK_REQUEST_BODY_SCHEMA = z.object({
517
- * name: z.string(),
518
- * description: z.string().optional(),
519
- * });
520
- *
521
- * ⠀@Controller({ prefix: "/api/book" })
522
- * class BookController {
523
- * ⠀@RequestBody(CREATE_BOOK_REQUEST_BODY_SCHEMA)
524
- * ⠀@POST()
525
- * public createBook(request: e.Request) {
526
- * const { name, description } = request.body as unknown as z.infer<
527
- * typeof CREATE_BOOK_REQUEST_BODY_SCHEMA
528
- * >;
529
- * }
530
- * }
531
- * ```
532
- */
533
- function RequestBody(schema) {
534
- return (target, propertyKey) => {
535
- const ctor = target.constructor;
536
- const fnName = String(propertyKey);
537
- _setOnce(_getOrCreateRequestSchemaDefinition(ctor, fnName), "body", schema, fnName);
538
- };
539
- }
540
- /**
541
- * Apply to a route method to have `request.param` be parsed by `schema`.
542
- *
543
- * This annotation will parse `request.param` & then override `request.param`.
544
- * You can then just simply cast `request.param` for your use
545
- *
546
- * @example
547
- * ```ts
548
- * const GET_BOOK_REQUEST_PARAM_SCHEMA = z.object({
549
- * bookId: z.string(),
550
- * });
551
- *
552
- * ⠀@Controller({ prefix: "/api/book" })
553
- * class BookController {
554
- * ⠀@RequestParam(GET_BOOK_REQUEST_PARAM_SCHEMA)
555
- * ⠀@GET("/:bookId")
556
- * public getBook(request: e.Request) {
557
- * const { bookId } = request.param as unknown as z.infer<
558
- * typeof GET_BOOK_REQUEST_PARAM_SCHEMA
559
- * >;
560
- * }
561
- * }
562
- * ```
563
- */
564
- function RequestParam(schema) {
565
- return (target, propertyKey) => {
566
- const ctor = target.constructor;
567
- const fnName = String(propertyKey);
568
- _setOnce(_getOrCreateRequestSchemaDefinition(ctor, fnName), "param", schema, fnName);
569
- };
393
+ //#region \0@oxc-project+runtime@0.127.0/helpers/decorate.js
394
+ function __decorate(decorators, target, key, desc) {
395
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
396
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
397
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
398
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
570
399
  }
400
+ //#endregion
401
+ //#region src/middleware/health/registrar.ts
402
+ let HealthRegistrar = class HealthRegistrar {
403
+ _checks;
404
+ _sealed;
405
+ constructor() {
406
+ this._checks = [];
407
+ this._sealed = false;
408
+ }
409
+ add(healthCheck) {
410
+ this._checks.push(healthCheck);
411
+ }
412
+ seal() {
413
+ this._sealed = true;
414
+ }
415
+ async check() {
416
+ if (!this._sealed) return false;
417
+ return (await Promise.all(this._checks.map((c) => c()))).every((c) => c === true);
418
+ }
419
+ };
420
+ HealthRegistrar = __decorate([Injectable()], HealthRegistrar);
421
+ //#endregion
422
+ //#region src/helper/sapling.ts
423
+ const _settings = {
424
+ serialize: JSON.stringify,
425
+ deserialize: JSON.parse,
426
+ health: { path: "/up" },
427
+ doc: {
428
+ openApiPath: "/openapi.json",
429
+ swaggerPath: "/swagger.html",
430
+ metadata: {
431
+ title: "API",
432
+ version: "1.0.0"
433
+ }
434
+ }
435
+ };
571
436
  /**
572
- * Apply to a route method to have `request.query` be parsed by `schema`.
573
- *
574
- * This annotation will parse `request.query` & then override `request.query`.
575
- * You can then just simply cast `request.query` for your use
576
- *
577
- * @example
578
- * ```ts
579
- * const LIST_BOOKS_REQUEST_QUERY_SCHEMA = z.object({
580
- * sort: z.enum(["name", "createdAt"]).optional(),
581
- * q: z.string().optional(),
582
- * });
583
- *
584
- * ⠀@Controller({ prefix: "/api/book" })
585
- * class BookController {
586
- * ⠀@RequestQuery(LIST_BOOKS_REQUEST_QUERY_SCHEMA)
587
- * ⠀@GET()
588
- * public listBooks(request: e.Request) {
589
- * const { sort, q } = request.query as unknown as z.infer<
590
- * typeof LIST_BOOKS_REQUEST_QUERY_SCHEMA
591
- * >;
592
- * }
593
- * }
594
- * ```
437
+ * Collection of utility functions which are essential for Sapling to function.
595
438
  */
596
- function RequestQuery(schema) {
597
- return (target, propertyKey) => {
598
- const ctor = target.constructor;
599
- const fnName = String(propertyKey);
600
- _setOnce(_getOrCreateRequestSchemaDefinition(ctor, fnName), "query", schema, fnName);
601
- };
602
- }
603
- function _getOrCreateRequestSchemaDefinition(ctor, fnName) {
604
- const byFn = (() => {
605
- const fn = _requestSchemaStore.get(ctor);
606
- if (fn) return fn;
607
- const newFn = /* @__PURE__ */ new Map();
608
- _requestSchemaStore.set(ctor, newFn);
609
- return newFn;
610
- })();
611
- const existing = byFn.get(fnName);
612
- if (existing) return existing;
613
- const created = {};
614
- byFn.set(fnName, created);
615
- return created;
616
- }
617
- function _setOnce(def, key, schema, fnName) {
618
- if (def[key]) throw new Error(`Duplicate request schema for "${String(key)}" on method "${fnName}"`);
619
- def[key] = schema;
620
- }
621
- function _getRequestSchemas(ctor, fnName) {
622
- return _requestSchemaStore.get(ctor)?.get(fnName);
623
- }
624
- async function _parseOrThrow(schema, input, kind) {
625
- const result = await schema["~standard"].validate(input);
626
- if (result.issues) {
627
- console.debug(`Failed to parse a schema`);
628
- throw new ParserError(kind, result.issues, schema["~standard"].vendor);
439
+ var Sapling = class Sapling {
440
+ /**
441
+ * If you would prefer to manually resolve your controllers instead, call resolve
442
+ * on the controller class.
443
+ *
444
+ * @example```ts
445
+ * import { Sapling } from "@tahminator/sapling";
446
+ * import TestController from "./path/to/test.controller";
447
+ *
448
+ * const app = express();
449
+ *
450
+ * const router = Sapling.resolve(TestController);
451
+ * app.use(router);
452
+ * ```
453
+ */
454
+ static resolve(clazz) {
455
+ const router = _ControllerRegistry.get(clazz);
456
+ if (!router) throw new Error("Controller cannot be found");
457
+ return router;
629
458
  }
630
- return result.value;
631
- }
459
+ /**
460
+ * Register this function as a middleware in order to utilize Sapling's `deserialize` function.
461
+ *
462
+ * @example```ts
463
+ * import { Sapling } from "@tahminator/sapling";
464
+ * import express from "express";
465
+ *
466
+ * const app = express();
467
+ *
468
+ * app.use(Sapling.json());
469
+ * ```
470
+ */
471
+ static json() {
472
+ return (request, _response, next) => {
473
+ try {
474
+ if (!request.body) return next();
475
+ if (request.headers["content-type"] !== "application/json") return next();
476
+ if (typeof request.body === "string") request.body = Sapling.deserialize(request.body);
477
+ else if (typeof request.body === "object") {
478
+ const raw = JSON.stringify(request.body);
479
+ request.body = Sapling.deserialize(raw);
480
+ }
481
+ next();
482
+ } catch (err) {
483
+ next(err);
484
+ }
485
+ };
486
+ }
487
+ /**
488
+ * Register your application with all the necessary middlewares and logics for Sapling to function.
489
+ *
490
+ * @example```ts
491
+ * import { Sapling } from "@tahminator/sapling";
492
+ * import express from "express";
493
+ *
494
+ * const app = express();
495
+ *
496
+ * app.registerApp(app);
497
+ * ```
498
+ */
499
+ static registerApp(app) {
500
+ app.use(express.default.text({ type: "application/json" }));
501
+ app.use(Sapling.json());
502
+ _InjectableRegistry.get(HealthRegistrar)?.seal();
503
+ }
504
+ /**
505
+ * Serialize a value into a JSON string.
506
+ *
507
+ * This function is used in {@link ResponseEntity} to serialize the `body`.
508
+ *
509
+ * Use `setSerializeFn` to override underlying implementation.
510
+ *
511
+ * @defaultValue `JSON.stringify`
512
+ */
513
+ static serialize(value) {
514
+ return _settings.serialize(value);
515
+ }
516
+ /**
517
+ * Replace the function used for `serialize`.
518
+ */
519
+ static setSerializeFn(fn) {
520
+ _settings.serialize = fn;
521
+ }
522
+ /**
523
+ * De-serialize a JSON string back to a JavaScript object.
524
+ *
525
+ * This function is used to de-serialize a string into a `body`.
526
+ *
527
+ * Use `setDeserializeFn` to override underlying implementation.
528
+ *
529
+ * @defaultValue `JSON.parse`
530
+ */
531
+ static deserialize(value) {
532
+ return _settings.deserialize(value);
533
+ }
534
+ /**
535
+ * Replace the function used for `deserialize`
536
+ */
537
+ static setDeserializeFn(fn) {
538
+ _settings.deserialize = fn;
539
+ }
540
+ /**
541
+ * Modify extra settings
542
+ */
543
+ static Extras = {
544
+ /**
545
+ * Modify default settings applied to OpenAPI & Swagger
546
+ */
547
+ swaggerAndOpenApi: {
548
+ /**
549
+ * Set base OpenAPI metadata values.
550
+ *
551
+ * @default { title: "API", version: "1.0.0" }
552
+ */
553
+ setMetadata(metadata) {
554
+ _settings.doc.metadata = metadata;
555
+ },
556
+ /**
557
+ * change default endpoint that will serve OpenAPI spec.
558
+ * Swagger will also load this endpoint on load.
559
+ *
560
+ * @default `/openapi.json`
561
+ */
562
+ setOpenApiPath(path) {
563
+ _settings.doc.openApiPath = path;
564
+ },
565
+ /**
566
+ * change Swagger endpoint.
567
+ *
568
+ * @default `/swagger.html`
569
+ */
570
+ setSwaggerPath(path) {
571
+ _settings.doc.swaggerPath = path;
572
+ }
573
+ } };
574
+ /**
575
+ * This method can be used in a `@MiddlewareClass` to register any libraries
576
+ * that expect you to register multiple registers at once. An example is `swagger-ui-express`
577
+ *
578
+ * @example
579
+ * ```ts
580
+ * ⠀@MiddlewareClass()
581
+ * class Serve {
582
+ * // `swagger.serve` returns multiple Express handlers for all the assets and routes
583
+ * // that will be served
584
+ * private readonly handlers: RequestHandler[] = swagger.serve;
585
+ *
586
+ * ⠀@Middleware(_settings.doc.swaggerPath)
587
+ * handle(request: Request, response: Response, next: NextFunction) {
588
+ * return Sapling.chainHandlers(this.handlers, request, response, next);
589
+ * }
590
+ * }
591
+ * ```
592
+ */
593
+ static chainHandlers(handlers, request, response, next, index = 0) {
594
+ if (index >= handlers.length) {
595
+ next();
596
+ return;
597
+ }
598
+ handlers[index]?.(request, response, (err) => {
599
+ if (err) {
600
+ next(err);
601
+ return;
602
+ }
603
+ Sapling.chainHandlers(handlers, request, response, next, index + 1);
604
+ });
605
+ }
606
+ };
632
607
  //#endregion
633
608
  //#region src/annotation/route.ts
634
609
  const _routeStore = /* @__PURE__ */ new WeakMap();
@@ -711,6 +686,245 @@ function _getRoutes(ctor) {
711
686
  return _routeStore.get(ctor) ?? [];
712
687
  }
713
688
  //#endregion
689
+ //#region src/annotation/schema.ts
690
+ function ControllerSchema(options) {
691
+ return (target) => {
692
+ _setControllerSchema(target, options);
693
+ };
694
+ }
695
+ function RouteSchema(options) {
696
+ return (target, propertyKey) => {
697
+ const ctor = target.constructor;
698
+ _setRouteSchema(ctor, String(propertyKey), options);
699
+ };
700
+ }
701
+ const _routeSchemaStore = /* @__PURE__ */ new WeakMap();
702
+ const _controllerSchemaStore = /* @__PURE__ */ new WeakMap();
703
+ function getOrCreateRouteSchemaStore(store, ctor) {
704
+ const existing = store.get(ctor);
705
+ if (existing) return existing;
706
+ const created = /* @__PURE__ */ new Map();
707
+ store.set(ctor, created);
708
+ return created;
709
+ }
710
+ function _setRouteSchema(ctor, fnName, options) {
711
+ getOrCreateRouteSchemaStore(_routeSchemaStore, ctor).set(fnName, options);
712
+ }
713
+ function _setControllerSchema(ctor, options) {
714
+ _controllerSchemaStore.set(ctor, options);
715
+ }
716
+ function _getRouteSchema(ctor, fnName) {
717
+ return _routeSchemaStore.get(ctor)?.get(fnName);
718
+ }
719
+ function _getControllerSchema(ctor) {
720
+ return _controllerSchemaStore.get(ctor);
721
+ }
722
+ //#endregion
723
+ //#region src/annotation/validator.ts
724
+ const _validatorSchemaStore = /* @__PURE__ */ new WeakMap();
725
+ function ResponseBody(schema) {
726
+ return (target, propertyKey) => {
727
+ const ctor = target.constructor;
728
+ const fnName = String(propertyKey);
729
+ _saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "responseBody", schema, fnName);
730
+ };
731
+ }
732
+ function RequestBody(schema) {
733
+ return (target, propertyKey) => {
734
+ const ctor = target.constructor;
735
+ const fnName = String(propertyKey);
736
+ _saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestBody", schema, fnName);
737
+ };
738
+ }
739
+ function RequestParam(schema) {
740
+ return (target, propertyKey) => {
741
+ const ctor = target.constructor;
742
+ const fnName = String(propertyKey);
743
+ _saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestParam", schema, fnName);
744
+ };
745
+ }
746
+ function RequestQuery(schema) {
747
+ return (target, propertyKey) => {
748
+ const ctor = target.constructor;
749
+ const fnName = String(propertyKey);
750
+ _saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestQuery", schema, fnName);
751
+ };
752
+ }
753
+ function getOrCreateValidatorSchemaStore(store, ctor) {
754
+ const existing = store.get(ctor);
755
+ if (existing) return existing;
756
+ const created = /* @__PURE__ */ new Map();
757
+ store.set(ctor, created);
758
+ return created;
759
+ }
760
+ function _getOrCreateSchemaDefinition(ctor, fnName) {
761
+ const byFn = getOrCreateValidatorSchemaStore(_validatorSchemaStore, ctor);
762
+ const existing = byFn.get(fnName);
763
+ if (existing) return existing;
764
+ const created = {};
765
+ byFn.set(fnName, created);
766
+ return created;
767
+ }
768
+ async function _parseOrThrow(schema, input, location, fnName) {
769
+ const result = await schema["~standard"].validate(input);
770
+ if (result.issues) throw new ParserError(location, result.issues, schema["~standard"].vendor, fnName);
771
+ return result.value;
772
+ }
773
+ function _saveValidatorSchema(def, key, schema, fnName) {
774
+ if (def[key]) throw new Error(`Duplicate schema for "${String(key)}" on method "${fnName}"`);
775
+ def[key] = schema;
776
+ }
777
+ function _getValidatorSchema(ctor, fnName) {
778
+ return _validatorSchemaStore.get(ctor)?.get(fnName);
779
+ }
780
+ //#endregion
781
+ //#region src/helper/openapi.ts
782
+ var OpenAPIGenerator = class {
783
+ OPENAPI_VERSION = "3.0.0";
784
+ controllers = /* @__PURE__ */ new Set();
785
+ registerController(controllerClass, prefix) {
786
+ this.controllers.add({
787
+ class: controllerClass,
788
+ prefix
789
+ });
790
+ }
791
+ /**
792
+ * visible for testing
793
+ */
794
+ _clearControllers() {
795
+ this.controllers.clear();
796
+ }
797
+ get metadata() {
798
+ return _settings.doc.metadata;
799
+ }
800
+ generateSpec() {
801
+ const metadata = this.metadata;
802
+ const paths = {};
803
+ const tags = [];
804
+ for (const { class: controllerClass, prefix } of this.controllers) {
805
+ const routes = _getRoutes(controllerClass);
806
+ const controllerSchema = _getControllerSchema(controllerClass);
807
+ if (controllerSchema?.title) tags.push({
808
+ name: controllerSchema.title,
809
+ description: controllerSchema.description
810
+ });
811
+ for (const route of routes) {
812
+ if (route.method === "USE") continue;
813
+ const schemas = _getValidatorSchema(controllerClass, route.fnName);
814
+ const routeSchema = _getRouteSchema(controllerClass, route.fnName);
815
+ if (route.path instanceof RegExp) throw new Error(`You have a route with a regex path of ${route.path.source}. This is not compatible with OpenAPI.`);
816
+ const openApiPath = (prefix + route.path).replace(/:([A-Za-z0-9_]+)/g, "{$1}");
817
+ if (!paths[openApiPath]) paths[openApiPath] = {};
818
+ const responses = {};
819
+ if (schemas?.responseBody) {
820
+ const responseSchema = this.toJsonSchema(schemas.responseBody, "output");
821
+ responses["200"] = {
822
+ description: responseSchema.description ?? "Successful response",
823
+ content: { "application/json": { schema: responseSchema } }
824
+ };
825
+ } else responses["200"] = { description: "Successful response" };
826
+ if (routeSchema?.responses) for (const resp of routeSchema.responses) {
827
+ const statusCode = String(resp.statusCode);
828
+ const existingResponse = responses[statusCode];
829
+ const existingSchema = existingResponse && "content" in existingResponse ? existingResponse.content?.["application/json"]?.schema : void 0;
830
+ const responseSchema = resp.schema ? this.toJsonSchema(resp.schema, "output") : statusCode === "200" ? existingSchema : void 0;
831
+ responses[statusCode] = {
832
+ ...existingResponse,
833
+ description: resp.description ?? responseSchema?.description ?? existingResponse?.description ?? `Response ${resp.statusCode}`,
834
+ ...responseSchema ? { content: { "application/json": { schema: responseSchema } } } : {}
835
+ };
836
+ }
837
+ const operation = {
838
+ responses,
839
+ summary: routeSchema?.summary,
840
+ description: routeSchema?.description,
841
+ tags: controllerSchema?.title ? [controllerSchema.title] : void 0
842
+ };
843
+ const parameters = [];
844
+ if (schemas?.requestParam) {
845
+ const paramSchema = this.toJsonSchema(schemas.requestParam, "input");
846
+ if (paramSchema.type === "object" && paramSchema.properties) for (const [name, schema] of Object.entries(paramSchema.properties)) {
847
+ const parameterSchema = schema;
848
+ parameters.push({
849
+ name,
850
+ in: "path",
851
+ required: true,
852
+ description: parameterSchema.description,
853
+ schema: parameterSchema
854
+ });
855
+ }
856
+ }
857
+ if (schemas?.requestQuery) {
858
+ const querySchema = this.toJsonSchema(schemas.requestQuery, "input");
859
+ if (querySchema.type === "object" && querySchema.properties) for (const [name, schema] of Object.entries(querySchema.properties)) {
860
+ const isRequired = Array.isArray(querySchema.required) && querySchema.required.includes(name);
861
+ const parameterSchema = schema;
862
+ parameters.push({
863
+ name,
864
+ in: "query",
865
+ required: isRequired,
866
+ description: parameterSchema.description,
867
+ schema: parameterSchema
868
+ });
869
+ }
870
+ }
871
+ if (parameters.length > 0) operation.parameters = parameters;
872
+ if (schemas?.requestBody) {
873
+ const requestSchema = this.toJsonSchema(schemas.requestBody, "input");
874
+ operation.requestBody = {
875
+ required: true,
876
+ description: requestSchema.description,
877
+ content: { "application/json": { schema: requestSchema } }
878
+ };
879
+ }
880
+ const method = route.method.toLowerCase();
881
+ paths[openApiPath][method] = operation;
882
+ }
883
+ }
884
+ return {
885
+ openapi: this.OPENAPI_VERSION,
886
+ info: {
887
+ title: metadata.title,
888
+ version: metadata.version,
889
+ description: metadata.description
890
+ },
891
+ tags: tags.length > 0 ? tags : void 0,
892
+ paths
893
+ };
894
+ }
895
+ toJsonSchema(schema, direction = "output") {
896
+ try {
897
+ const jsonSchema = schema["~standard"].jsonSchema;
898
+ return direction === "input" ? jsonSchema.input({ target: "openapi-3.0" }) : jsonSchema.output({ target: "openapi-3.0" });
899
+ } catch (e) {
900
+ if (e instanceof Error && e.message.includes("Transforms cannot be represented in JSON Schema")) throw new Error(`${e.message}.\nIt appears that you are using z.transform() - it is highly recommended that you use z.codec instead - https://zod.dev/codecs`, { cause: e });
901
+ throw e;
902
+ }
903
+ }
904
+ };
905
+ const openApiGenerator = new OpenAPIGenerator();
906
+ function _registerController(controllerClass, prefix) {
907
+ openApiGenerator.registerController(controllerClass, prefix);
908
+ }
909
+ function generateOpenApiSpec() {
910
+ return openApiGenerator.generateSpec();
911
+ }
912
+ function _clearOpenApiRegistry() {
913
+ openApiGenerator._clearControllers();
914
+ }
915
+ //#endregion
916
+ //#region src/types.ts
917
+ const methodResolve = {
918
+ GET: "get",
919
+ PUT: "put",
920
+ POST: "post",
921
+ DELETE: "delete",
922
+ OPTIONS: "options",
923
+ PATCH: "patch",
924
+ HEAD: "head",
925
+ USE: "use"
926
+ };
927
+ //#endregion
714
928
  //#region src/annotation/controller.ts
715
929
  const _ControllerRegistry = /* @__PURE__ */ new WeakMap();
716
930
  /**
@@ -722,6 +936,7 @@ const _ControllerRegistry = /* @__PURE__ */ new WeakMap();
722
936
  function Controller({ prefix = "", deps = [] } = {}) {
723
937
  return (target) => {
724
938
  const targetClass = target;
939
+ _registerController(target, prefix);
725
940
  const router = (0, express.Router)();
726
941
  const routes = _getRoutes(target);
727
942
  const usedRoutes = /* @__PURE__ */ new Set();
@@ -746,15 +961,20 @@ Split these into separate @MiddlewareClass classes, or merge the logic into a si
746
961
  if (method === "USE" && fn.length >= 4) {
747
962
  const middlewareFn = async (err, request, response, next) => {
748
963
  try {
749
- const result = fn.bind(controllerInstance)(err, request, response, next);
750
- if (result instanceof ResponseEntity) {
751
- response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(result.getBody()));
752
- return;
753
- }
754
- if (result instanceof RedirectView) {
755
- response.redirect(result.getUrl());
756
- return;
757
- }
964
+ await validate({
965
+ target,
966
+ fnName,
967
+ request
968
+ });
969
+ await handleResult({
970
+ result: fn.bind(controllerInstance)(err, request, response, next),
971
+ response,
972
+ target,
973
+ fnName,
974
+ method,
975
+ path: path instanceof RegExp ? path.source : fp,
976
+ isErrorMiddleware: true
977
+ });
758
978
  } catch (e) {
759
979
  console.error(e);
760
980
  next(e);
@@ -764,34 +984,52 @@ Split these into separate @MiddlewareClass classes, or merge the logic into a si
764
984
  return;
765
985
  }
766
986
  router[methodName](fp, async (request, response, next) => {
767
- const schemas = _getRequestSchemas(target, fnName);
768
- if (schemas) {
769
- if (schemas.body) request.body = await _parseOrThrow(schemas.body, request.body, "reqbody");
770
- if (schemas.param) request.params = await _parseOrThrow(schemas.param, request.params, "reqparams");
771
- if (schemas.query) {
772
- const parsedQuery = await _parseOrThrow(schemas.query, request.query, "reqquery");
773
- Object.defineProperty(request, "query", {
774
- value: parsedQuery,
775
- writable: true,
776
- configurable: true
777
- });
778
- }
779
- }
780
- const result = await fn.bind(controllerInstance)(request, response, next);
781
- if (result instanceof ResponseEntity) {
782
- response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(result.getBody()));
783
- return;
784
- }
785
- if (result instanceof RedirectView) {
786
- response.redirect(result.getUrl());
787
- return;
788
- }
789
- if (method !== "USE" && !response.writableEnded) response.status(404).send(Html404ErrorPage(`Cannot ${methodName.toUpperCase()} ${path instanceof RegExp ? path.source : fp}`));
987
+ await validate({
988
+ target,
989
+ fnName,
990
+ request
991
+ });
992
+ await handleResult({
993
+ result: await fn.bind(controllerInstance)(request, response, next),
994
+ response,
995
+ target,
996
+ fnName,
997
+ method,
998
+ path: path instanceof RegExp ? path.source : fp
999
+ });
790
1000
  });
791
1001
  }
792
1002
  _ControllerRegistry.set(targetClass, router);
793
1003
  };
794
1004
  }
1005
+ async function handleResult({ result, target, fnName, response, method, path, isErrorMiddleware = false }) {
1006
+ const schemas = _getValidatorSchema(target, fnName);
1007
+ if (result instanceof ResponseEntity) {
1008
+ const body = schemas && schemas.responseBody ? await _parseOrThrow(schemas.responseBody, result.getBody(), "resbody", fnName) : result.getBody();
1009
+ response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(body));
1010
+ return;
1011
+ }
1012
+ if (result instanceof RedirectView) {
1013
+ response.redirect(result.getUrl());
1014
+ return;
1015
+ }
1016
+ if (!isErrorMiddleware && method !== "USE" && !response.writableEnded) response.status(404).send(Html404ErrorPage(`Cannot ${method} ${path}`));
1017
+ }
1018
+ async function validate({ target, fnName, request }) {
1019
+ const schemas = _getValidatorSchema(target, fnName);
1020
+ if (schemas) {
1021
+ if (schemas.requestBody) request.body = await _parseOrThrow(schemas.requestBody, request.body, "reqbody", fnName);
1022
+ if (schemas.requestParam) request.params = await _parseOrThrow(schemas.requestParam, request.params, "reqparams", fnName);
1023
+ if (schemas.requestQuery) {
1024
+ const parsedQuery = await _parseOrThrow(schemas.requestQuery, request.query, "reqquery", fnName);
1025
+ Object.defineProperty(request, "query", {
1026
+ value: parsedQuery,
1027
+ writable: true,
1028
+ configurable: true
1029
+ });
1030
+ }
1031
+ }
1032
+ }
795
1033
  //#endregion
796
1034
  //#region src/annotation/middleware.ts
797
1035
  /**
@@ -805,15 +1043,7 @@ function MiddlewareClass(...args) {
805
1043
  return Controller(...args);
806
1044
  }
807
1045
  //#endregion
808
- //#region \0@oxc-project+runtime@0.127.0/helpers/decorate.js
809
- function __decorate(decorators, target, key, desc) {
810
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
811
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
812
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
813
- return c > 3 && r && Object.defineProperty(target, key, r), r;
814
- }
815
- //#endregion
816
- //#region src/middleware/default/base.ts
1046
+ //#region src/middleware/default/error/base.ts
817
1047
  let DefaultBaseErrorMiddleware = class DefaultBaseErrorMiddleware {
818
1048
  handle(err, _request, _response, _next) {
819
1049
  console.error("[Error]", err);
@@ -823,7 +1053,20 @@ let DefaultBaseErrorMiddleware = class DefaultBaseErrorMiddleware {
823
1053
  __decorate([Middleware()], DefaultBaseErrorMiddleware.prototype, "handle", null);
824
1054
  DefaultBaseErrorMiddleware = __decorate([MiddlewareClass()], DefaultBaseErrorMiddleware);
825
1055
  //#endregion
826
- //#region src/middleware/default/responsestatus.ts
1056
+ //#region src/middleware/default/error/parse.ts
1057
+ let DefaultParserErrorMiddleware = class DefaultParserErrorMiddleware {
1058
+ handle(err, _request, _response, next) {
1059
+ if (err instanceof ParserError) {
1060
+ console.warn(err);
1061
+ return ResponseEntity.status(err.status).body({ message: err.message });
1062
+ }
1063
+ next(err);
1064
+ }
1065
+ };
1066
+ __decorate([Middleware()], DefaultParserErrorMiddleware.prototype, "handle", null);
1067
+ DefaultParserErrorMiddleware = __decorate([MiddlewareClass()], DefaultParserErrorMiddleware);
1068
+ //#endregion
1069
+ //#region src/middleware/default/error/responsestatus.ts
827
1070
  let DefaultResponseStatusErrorMiddleware = class DefaultResponseStatusErrorMiddleware {
828
1071
  handle(err, _request, _response, next) {
829
1072
  if (err instanceof ResponseStatusError) return ResponseEntity.status(err.status).body({ message: err.message });
@@ -833,7 +1076,103 @@ let DefaultResponseStatusErrorMiddleware = class DefaultResponseStatusErrorMiddl
833
1076
  __decorate([Middleware()], DefaultResponseStatusErrorMiddleware.prototype, "handle", null);
834
1077
  DefaultResponseStatusErrorMiddleware = __decorate([MiddlewareClass()], DefaultResponseStatusErrorMiddleware);
835
1078
  //#endregion
1079
+ //#region src/middleware/default/openapi/index.ts
1080
+ let DefaultOpenApiMiddleware = class DefaultOpenApiMiddleware {
1081
+ handle(_request, _response, _next) {
1082
+ return ResponseEntity.ok().body(generateOpenApiSpec());
1083
+ }
1084
+ };
1085
+ __decorate([GET(_settings.doc.openApiPath)], DefaultOpenApiMiddleware.prototype, "handle", null);
1086
+ DefaultOpenApiMiddleware = __decorate([MiddlewareClass()], DefaultOpenApiMiddleware);
1087
+ //#endregion
1088
+ //#region src/middleware/default/swagger/index.ts
1089
+ /**
1090
+ * Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
1091
+ *
1092
+ * Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
1093
+ *
1094
+ * You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
1095
+ *
1096
+ * ```ts
1097
+ * const middlewares = [
1098
+ * DefaultOpenApiMiddleware,
1099
+ * DefaultSwaggerMiddleware.Serve,
1100
+ * DefaultSwaggerMiddleware.Setup,
1101
+ * ];
1102
+ * middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
1103
+ * ```
1104
+ */
1105
+ let Serve = class Serve {
1106
+ handlers = swagger_ui_express.default.serve;
1107
+ handle(request, response, next) {
1108
+ return Sapling.chainHandlers(this.handlers, request, response, next);
1109
+ }
1110
+ };
1111
+ __decorate([Middleware(_settings.doc.swaggerPath)], Serve.prototype, "handle", null);
1112
+ Serve = __decorate([MiddlewareClass()], Serve);
1113
+ /**
1114
+ * Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
1115
+ *
1116
+ * Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
1117
+ *
1118
+ * You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
1119
+ *
1120
+ * ```ts
1121
+ * const middlewares = [
1122
+ * DefaultOpenApiMiddleware,
1123
+ * DefaultSwaggerMiddleware.Serve,
1124
+ * DefaultSwaggerMiddleware.Setup,
1125
+ * ];
1126
+ * middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
1127
+ * ```
1128
+ */
1129
+ let Setup = class Setup {
1130
+ handler;
1131
+ constructor() {
1132
+ this.handler = swagger_ui_express.default.setup(null, { swaggerOptions: { url: _settings.doc.openApiPath } });
1133
+ }
1134
+ handle(request, response, next) {
1135
+ return this.handler(request, response, next);
1136
+ }
1137
+ };
1138
+ __decorate([Middleware(_settings.doc.swaggerPath)], Setup.prototype, "handle", null);
1139
+ Setup = __decorate([MiddlewareClass()], Setup);
1140
+ /**
1141
+ * Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
1142
+ *
1143
+ * Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
1144
+ *
1145
+ * You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
1146
+ *
1147
+ * ```ts
1148
+ * const middlewares = [
1149
+ * DefaultOpenApiMiddleware,
1150
+ * DefaultSwaggerMiddleware.Serve,
1151
+ * DefaultSwaggerMiddleware.Setup,
1152
+ * ];
1153
+ * middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
1154
+ * ```
1155
+ */
1156
+ const DefaultSwaggerMiddleware = {
1157
+ Serve,
1158
+ Setup
1159
+ };
1160
+ //#endregion
1161
+ //#region src/middleware/default/health/index.ts
1162
+ let DefaultHealthMiddleware = class DefaultHealthMiddleware {
1163
+ constructor(healthRegistrar) {
1164
+ this.healthRegistrar = healthRegistrar;
1165
+ }
1166
+ async serve(_request, _response, _next) {
1167
+ const up = await this.healthRegistrar.check();
1168
+ return ResponseEntity.ok().body({ up });
1169
+ }
1170
+ };
1171
+ __decorate([GET(_settings.health.path)], DefaultHealthMiddleware.prototype, "serve", null);
1172
+ DefaultHealthMiddleware = __decorate([MiddlewareClass({ deps: [HealthRegistrar] })], DefaultHealthMiddleware);
1173
+ //#endregion
836
1174
  exports.Controller = Controller;
1175
+ exports.ControllerSchema = ControllerSchema;
837
1176
  exports.DELETE = DELETE;
838
1177
  Object.defineProperty(exports, "DefaultBaseErrorMiddleware", {
839
1178
  enumerable: true,
@@ -841,14 +1180,39 @@ Object.defineProperty(exports, "DefaultBaseErrorMiddleware", {
841
1180
  return DefaultBaseErrorMiddleware;
842
1181
  }
843
1182
  });
1183
+ Object.defineProperty(exports, "DefaultHealthMiddleware", {
1184
+ enumerable: true,
1185
+ get: function() {
1186
+ return DefaultHealthMiddleware;
1187
+ }
1188
+ });
1189
+ Object.defineProperty(exports, "DefaultOpenApiMiddleware", {
1190
+ enumerable: true,
1191
+ get: function() {
1192
+ return DefaultOpenApiMiddleware;
1193
+ }
1194
+ });
1195
+ Object.defineProperty(exports, "DefaultParserErrorMiddleware", {
1196
+ enumerable: true,
1197
+ get: function() {
1198
+ return DefaultParserErrorMiddleware;
1199
+ }
1200
+ });
844
1201
  Object.defineProperty(exports, "DefaultResponseStatusErrorMiddleware", {
845
1202
  enumerable: true,
846
1203
  get: function() {
847
1204
  return DefaultResponseStatusErrorMiddleware;
848
1205
  }
849
1206
  });
1207
+ exports.DefaultSwaggerMiddleware = DefaultSwaggerMiddleware;
850
1208
  exports.GET = GET;
851
1209
  exports.HEAD = HEAD;
1210
+ Object.defineProperty(exports, "HealthRegistrar", {
1211
+ enumerable: true,
1212
+ get: function() {
1213
+ return HealthRegistrar;
1214
+ }
1215
+ });
852
1216
  exports.Html404ErrorPage = Html404ErrorPage;
853
1217
  exports.HttpStatus = HttpStatus;
854
1218
  exports.Injectable = Injectable;
@@ -863,16 +1227,29 @@ exports.RedirectView = RedirectView;
863
1227
  exports.RequestBody = RequestBody;
864
1228
  exports.RequestParam = RequestParam;
865
1229
  exports.RequestQuery = RequestQuery;
1230
+ exports.ResponseBody = ResponseBody;
866
1231
  exports.ResponseEntity = ResponseEntity;
867
1232
  exports.ResponseEntityBuilder = ResponseEntityBuilder;
868
1233
  exports.ResponseStatusError = ResponseStatusError;
1234
+ exports.RouteSchema = RouteSchema;
869
1235
  exports.Sapling = Sapling;
870
1236
  exports._ControllerRegistry = _ControllerRegistry;
871
1237
  exports._InjectableDeps = _InjectableDeps;
872
1238
  exports._InjectableRegistry = _InjectableRegistry;
873
1239
  exports._Route = _Route;
874
- exports._getRequestSchemas = _getRequestSchemas;
1240
+ exports._clearOpenApiRegistry = _clearOpenApiRegistry;
1241
+ exports._getControllerSchema = _getControllerSchema;
1242
+ exports._getOrCreateSchemaDefinition = _getOrCreateSchemaDefinition;
1243
+ exports._getRouteSchema = _getRouteSchema;
875
1244
  exports._getRoutes = _getRoutes;
1245
+ exports._getValidatorSchema = _getValidatorSchema;
876
1246
  exports._parseOrThrow = _parseOrThrow;
1247
+ exports._registerController = _registerController;
877
1248
  exports._resolve = _resolve;
1249
+ exports._saveValidatorSchema = _saveValidatorSchema;
1250
+ exports._setControllerSchema = _setControllerSchema;
1251
+ exports._setRouteSchema = _setRouteSchema;
1252
+ exports._settings = _settings;
1253
+ exports.generateOpenApiSpec = generateOpenApiSpec;
878
1254
  exports.methodResolve = methodResolve;
1255
+ exports.openApiGenerator = openApiGenerator;