@tahminator/sapling 2.0.5 → 2.1.0-beta.a2de2fb9

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