@tahminator/sapling 2.0.5 → 2.1.0-beta.da115635
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/README.md +161 -12
- package/dist/index.cjs +699 -299
- package/dist/index.d.cts +611 -86
- package/dist/index.d.mts +611 -86
- package/dist/index.mjs +659 -299
- package/package.json +8 -2
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
|
|
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;
|
|
291
|
-
}
|
|
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;
|
|
261
|
+
return `Failed to parse ${this.getPrettyLocationString(location)} with ${vendor} on ${functionName}: ${formatted}`;
|
|
353
262
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
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,243 @@ function _resolve(ctor) {
|
|
|
503
390
|
return _InjectableRegistry.get(ctor);
|
|
504
391
|
}
|
|
505
392
|
//#endregion
|
|
506
|
-
//#region
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
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
|
-
|
|
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
|
+
return new Proxy(app, { get(target, prop, receiver) {
|
|
503
|
+
if (prop === "listen") {
|
|
504
|
+
const originalListen = target[prop];
|
|
505
|
+
return function(...args) {
|
|
506
|
+
const lastArg = args[args.length - 1];
|
|
507
|
+
let originalCallback;
|
|
508
|
+
if (typeof lastArg === "function") {
|
|
509
|
+
originalCallback = lastArg;
|
|
510
|
+
args.pop();
|
|
511
|
+
}
|
|
512
|
+
const server = originalListen.apply(target, args);
|
|
513
|
+
server.once("listening", function(...cbArgs) {
|
|
514
|
+
Sapling.onStartup();
|
|
515
|
+
console.log("Sapling successfully initialized post-startup hooks on server start");
|
|
516
|
+
if (originalCallback) originalCallback(...cbArgs);
|
|
517
|
+
});
|
|
518
|
+
return server;
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
return Reflect.get(target, prop, receiver);
|
|
522
|
+
} });
|
|
523
|
+
}
|
|
524
|
+
static onStartup() {
|
|
525
|
+
_InjectableRegistry.get(HealthRegistrar)?.seal();
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Serialize a value into a JSON string.
|
|
529
|
+
*
|
|
530
|
+
* This function is used in {@link ResponseEntity} to serialize the `body`.
|
|
531
|
+
*
|
|
532
|
+
* Use `setSerializeFn` to override underlying implementation.
|
|
533
|
+
*
|
|
534
|
+
* @defaultValue `JSON.stringify`
|
|
535
|
+
*/
|
|
536
|
+
static serialize(value) {
|
|
537
|
+
return _settings.serialize(value);
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* Replace the function used for `serialize`.
|
|
541
|
+
*/
|
|
542
|
+
static setSerializeFn(fn) {
|
|
543
|
+
_settings.serialize = fn;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* De-serialize a JSON string back to a JavaScript object.
|
|
547
|
+
*
|
|
548
|
+
* This function is used to de-serialize a string into a `body`.
|
|
549
|
+
*
|
|
550
|
+
* Use `setDeserializeFn` to override underlying implementation.
|
|
551
|
+
*
|
|
552
|
+
* @defaultValue `JSON.parse`
|
|
553
|
+
*/
|
|
554
|
+
static deserialize(value) {
|
|
555
|
+
return _settings.deserialize(value);
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Replace the function used for `deserialize`
|
|
559
|
+
*/
|
|
560
|
+
static setDeserializeFn(fn) {
|
|
561
|
+
_settings.deserialize = fn;
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Modify extra settings
|
|
565
|
+
*/
|
|
566
|
+
static Extras = {
|
|
567
|
+
/**
|
|
568
|
+
* Modify default settings applied to OpenAPI & Swagger
|
|
569
|
+
*/
|
|
570
|
+
swaggerAndOpenApi: {
|
|
571
|
+
/**
|
|
572
|
+
* Set base OpenAPI metadata values.
|
|
573
|
+
*
|
|
574
|
+
* @default { title: "API", version: "1.0.0" }
|
|
575
|
+
*/
|
|
576
|
+
setMetadata(metadata) {
|
|
577
|
+
_settings.doc.metadata = metadata;
|
|
578
|
+
},
|
|
579
|
+
/**
|
|
580
|
+
* change default endpoint that will serve OpenAPI spec.
|
|
581
|
+
* Swagger will also load this endpoint on load.
|
|
582
|
+
*
|
|
583
|
+
* @default `/openapi.json`
|
|
584
|
+
*/
|
|
585
|
+
setOpenApiPath(path) {
|
|
586
|
+
_settings.doc.openApiPath = path;
|
|
587
|
+
},
|
|
588
|
+
/**
|
|
589
|
+
* change Swagger endpoint.
|
|
590
|
+
*
|
|
591
|
+
* @default `/swagger.html`
|
|
592
|
+
*/
|
|
593
|
+
setSwaggerPath(path) {
|
|
594
|
+
_settings.doc.swaggerPath = path;
|
|
595
|
+
}
|
|
596
|
+
} };
|
|
597
|
+
/**
|
|
598
|
+
* This method can be used in a `@MiddlewareClass` to register any libraries
|
|
599
|
+
* that expect you to register multiple registers at once. An example is `swagger-ui-express`
|
|
600
|
+
*
|
|
601
|
+
* @example
|
|
602
|
+
* ```ts
|
|
603
|
+
* ⠀@MiddlewareClass()
|
|
604
|
+
* class Serve {
|
|
605
|
+
* // `swagger.serve` returns multiple Express handlers for all the assets and routes
|
|
606
|
+
* // that will be served
|
|
607
|
+
* private readonly handlers: RequestHandler[] = swagger.serve;
|
|
608
|
+
*
|
|
609
|
+
* ⠀@Middleware(_settings.doc.swaggerPath)
|
|
610
|
+
* handle(request: Request, response: Response, next: NextFunction) {
|
|
611
|
+
* return Sapling.chainHandlers(this.handlers, request, response, next);
|
|
612
|
+
* }
|
|
613
|
+
* }
|
|
614
|
+
* ```
|
|
615
|
+
*/
|
|
616
|
+
static chainHandlers(handlers, request, response, next, index = 0) {
|
|
617
|
+
if (index >= handlers.length) {
|
|
618
|
+
next();
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
handlers[index]?.(request, response, (err) => {
|
|
622
|
+
if (err) {
|
|
623
|
+
next(err);
|
|
624
|
+
return;
|
|
625
|
+
}
|
|
626
|
+
Sapling.chainHandlers(handlers, request, response, next, index + 1);
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
};
|
|
632
630
|
//#endregion
|
|
633
631
|
//#region src/annotation/route.ts
|
|
634
632
|
const _routeStore = /* @__PURE__ */ new WeakMap();
|
|
@@ -711,6 +709,245 @@ function _getRoutes(ctor) {
|
|
|
711
709
|
return _routeStore.get(ctor) ?? [];
|
|
712
710
|
}
|
|
713
711
|
//#endregion
|
|
712
|
+
//#region src/annotation/schema.ts
|
|
713
|
+
function ControllerSchema(options) {
|
|
714
|
+
return (target) => {
|
|
715
|
+
_setControllerSchema(target, options);
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
function RouteSchema(options) {
|
|
719
|
+
return (target, propertyKey) => {
|
|
720
|
+
const ctor = target.constructor;
|
|
721
|
+
_setRouteSchema(ctor, String(propertyKey), options);
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
const _routeSchemaStore = /* @__PURE__ */ new WeakMap();
|
|
725
|
+
const _controllerSchemaStore = /* @__PURE__ */ new WeakMap();
|
|
726
|
+
function getOrCreateRouteSchemaStore(store, ctor) {
|
|
727
|
+
const existing = store.get(ctor);
|
|
728
|
+
if (existing) return existing;
|
|
729
|
+
const created = /* @__PURE__ */ new Map();
|
|
730
|
+
store.set(ctor, created);
|
|
731
|
+
return created;
|
|
732
|
+
}
|
|
733
|
+
function _setRouteSchema(ctor, fnName, options) {
|
|
734
|
+
getOrCreateRouteSchemaStore(_routeSchemaStore, ctor).set(fnName, options);
|
|
735
|
+
}
|
|
736
|
+
function _setControllerSchema(ctor, options) {
|
|
737
|
+
_controllerSchemaStore.set(ctor, options);
|
|
738
|
+
}
|
|
739
|
+
function _getRouteSchema(ctor, fnName) {
|
|
740
|
+
return _routeSchemaStore.get(ctor)?.get(fnName);
|
|
741
|
+
}
|
|
742
|
+
function _getControllerSchema(ctor) {
|
|
743
|
+
return _controllerSchemaStore.get(ctor);
|
|
744
|
+
}
|
|
745
|
+
//#endregion
|
|
746
|
+
//#region src/annotation/validator.ts
|
|
747
|
+
const _validatorSchemaStore = /* @__PURE__ */ new WeakMap();
|
|
748
|
+
function ResponseBody(schema) {
|
|
749
|
+
return (target, propertyKey) => {
|
|
750
|
+
const ctor = target.constructor;
|
|
751
|
+
const fnName = String(propertyKey);
|
|
752
|
+
_saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "responseBody", schema, fnName);
|
|
753
|
+
};
|
|
754
|
+
}
|
|
755
|
+
function RequestBody(schema) {
|
|
756
|
+
return (target, propertyKey) => {
|
|
757
|
+
const ctor = target.constructor;
|
|
758
|
+
const fnName = String(propertyKey);
|
|
759
|
+
_saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestBody", schema, fnName);
|
|
760
|
+
};
|
|
761
|
+
}
|
|
762
|
+
function RequestParam(schema) {
|
|
763
|
+
return (target, propertyKey) => {
|
|
764
|
+
const ctor = target.constructor;
|
|
765
|
+
const fnName = String(propertyKey);
|
|
766
|
+
_saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestParam", schema, fnName);
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
function RequestQuery(schema) {
|
|
770
|
+
return (target, propertyKey) => {
|
|
771
|
+
const ctor = target.constructor;
|
|
772
|
+
const fnName = String(propertyKey);
|
|
773
|
+
_saveValidatorSchema(_getOrCreateSchemaDefinition(ctor, fnName), "requestQuery", schema, fnName);
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
function getOrCreateValidatorSchemaStore(store, ctor) {
|
|
777
|
+
const existing = store.get(ctor);
|
|
778
|
+
if (existing) return existing;
|
|
779
|
+
const created = /* @__PURE__ */ new Map();
|
|
780
|
+
store.set(ctor, created);
|
|
781
|
+
return created;
|
|
782
|
+
}
|
|
783
|
+
function _getOrCreateSchemaDefinition(ctor, fnName) {
|
|
784
|
+
const byFn = getOrCreateValidatorSchemaStore(_validatorSchemaStore, ctor);
|
|
785
|
+
const existing = byFn.get(fnName);
|
|
786
|
+
if (existing) return existing;
|
|
787
|
+
const created = {};
|
|
788
|
+
byFn.set(fnName, created);
|
|
789
|
+
return created;
|
|
790
|
+
}
|
|
791
|
+
async function _parseOrThrow(schema, input, location, fnName) {
|
|
792
|
+
const result = await schema["~standard"].validate(input);
|
|
793
|
+
if (result.issues) throw new ParserError(location, result.issues, schema["~standard"].vendor, fnName);
|
|
794
|
+
return result.value;
|
|
795
|
+
}
|
|
796
|
+
function _saveValidatorSchema(def, key, schema, fnName) {
|
|
797
|
+
if (def[key]) throw new Error(`Duplicate schema for "${String(key)}" on method "${fnName}"`);
|
|
798
|
+
def[key] = schema;
|
|
799
|
+
}
|
|
800
|
+
function _getValidatorSchema(ctor, fnName) {
|
|
801
|
+
return _validatorSchemaStore.get(ctor)?.get(fnName);
|
|
802
|
+
}
|
|
803
|
+
//#endregion
|
|
804
|
+
//#region src/helper/openapi.ts
|
|
805
|
+
var OpenAPIGenerator = class {
|
|
806
|
+
OPENAPI_VERSION = "3.0.0";
|
|
807
|
+
controllers = /* @__PURE__ */ new Set();
|
|
808
|
+
registerController(controllerClass, prefix) {
|
|
809
|
+
this.controllers.add({
|
|
810
|
+
class: controllerClass,
|
|
811
|
+
prefix
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* visible for testing
|
|
816
|
+
*/
|
|
817
|
+
_clearControllers() {
|
|
818
|
+
this.controllers.clear();
|
|
819
|
+
}
|
|
820
|
+
get metadata() {
|
|
821
|
+
return _settings.doc.metadata;
|
|
822
|
+
}
|
|
823
|
+
generateSpec() {
|
|
824
|
+
const metadata = this.metadata;
|
|
825
|
+
const paths = {};
|
|
826
|
+
const tags = [];
|
|
827
|
+
for (const { class: controllerClass, prefix } of this.controllers) {
|
|
828
|
+
const routes = _getRoutes(controllerClass);
|
|
829
|
+
const controllerSchema = _getControllerSchema(controllerClass);
|
|
830
|
+
if (controllerSchema?.title) tags.push({
|
|
831
|
+
name: controllerSchema.title,
|
|
832
|
+
description: controllerSchema.description
|
|
833
|
+
});
|
|
834
|
+
for (const route of routes) {
|
|
835
|
+
if (route.method === "USE") continue;
|
|
836
|
+
const schemas = _getValidatorSchema(controllerClass, route.fnName);
|
|
837
|
+
const routeSchema = _getRouteSchema(controllerClass, route.fnName);
|
|
838
|
+
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.`);
|
|
839
|
+
const openApiPath = (prefix + route.path).replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
840
|
+
if (!paths[openApiPath]) paths[openApiPath] = {};
|
|
841
|
+
const responses = {};
|
|
842
|
+
if (schemas?.responseBody) {
|
|
843
|
+
const responseSchema = this.toJsonSchema(schemas.responseBody, "output");
|
|
844
|
+
responses["200"] = {
|
|
845
|
+
description: responseSchema.description ?? "Successful response",
|
|
846
|
+
content: { "application/json": { schema: responseSchema } }
|
|
847
|
+
};
|
|
848
|
+
} else responses["200"] = { description: "Successful response" };
|
|
849
|
+
if (routeSchema?.responses) for (const resp of routeSchema.responses) {
|
|
850
|
+
const statusCode = String(resp.statusCode);
|
|
851
|
+
const existingResponse = responses[statusCode];
|
|
852
|
+
const existingSchema = existingResponse && "content" in existingResponse ? existingResponse.content?.["application/json"]?.schema : void 0;
|
|
853
|
+
const responseSchema = resp.schema ? this.toJsonSchema(resp.schema, "output") : statusCode === "200" ? existingSchema : void 0;
|
|
854
|
+
responses[statusCode] = {
|
|
855
|
+
...existingResponse,
|
|
856
|
+
description: resp.description ?? responseSchema?.description ?? existingResponse?.description ?? `Response ${resp.statusCode}`,
|
|
857
|
+
...responseSchema ? { content: { "application/json": { schema: responseSchema } } } : {}
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
const operation = {
|
|
861
|
+
responses,
|
|
862
|
+
summary: routeSchema?.summary,
|
|
863
|
+
description: routeSchema?.description,
|
|
864
|
+
tags: controllerSchema?.title ? [controllerSchema.title] : void 0
|
|
865
|
+
};
|
|
866
|
+
const parameters = [];
|
|
867
|
+
if (schemas?.requestParam) {
|
|
868
|
+
const paramSchema = this.toJsonSchema(schemas.requestParam, "input");
|
|
869
|
+
if (paramSchema.type === "object" && paramSchema.properties) for (const [name, schema] of Object.entries(paramSchema.properties)) {
|
|
870
|
+
const parameterSchema = schema;
|
|
871
|
+
parameters.push({
|
|
872
|
+
name,
|
|
873
|
+
in: "path",
|
|
874
|
+
required: true,
|
|
875
|
+
description: parameterSchema.description,
|
|
876
|
+
schema: parameterSchema
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
if (schemas?.requestQuery) {
|
|
881
|
+
const querySchema = this.toJsonSchema(schemas.requestQuery, "input");
|
|
882
|
+
if (querySchema.type === "object" && querySchema.properties) for (const [name, schema] of Object.entries(querySchema.properties)) {
|
|
883
|
+
const isRequired = Array.isArray(querySchema.required) && querySchema.required.includes(name);
|
|
884
|
+
const parameterSchema = schema;
|
|
885
|
+
parameters.push({
|
|
886
|
+
name,
|
|
887
|
+
in: "query",
|
|
888
|
+
required: isRequired,
|
|
889
|
+
description: parameterSchema.description,
|
|
890
|
+
schema: parameterSchema
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
if (parameters.length > 0) operation.parameters = parameters;
|
|
895
|
+
if (schemas?.requestBody) {
|
|
896
|
+
const requestSchema = this.toJsonSchema(schemas.requestBody, "input");
|
|
897
|
+
operation.requestBody = {
|
|
898
|
+
required: true,
|
|
899
|
+
description: requestSchema.description,
|
|
900
|
+
content: { "application/json": { schema: requestSchema } }
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
const method = route.method.toLowerCase();
|
|
904
|
+
paths[openApiPath][method] = operation;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
return {
|
|
908
|
+
openapi: this.OPENAPI_VERSION,
|
|
909
|
+
info: {
|
|
910
|
+
title: metadata.title,
|
|
911
|
+
version: metadata.version,
|
|
912
|
+
description: metadata.description
|
|
913
|
+
},
|
|
914
|
+
tags: tags.length > 0 ? tags : void 0,
|
|
915
|
+
paths
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
toJsonSchema(schema, direction = "output") {
|
|
919
|
+
try {
|
|
920
|
+
const jsonSchema = schema["~standard"].jsonSchema;
|
|
921
|
+
return direction === "input" ? jsonSchema.input({ target: "openapi-3.0" }) : jsonSchema.output({ target: "openapi-3.0" });
|
|
922
|
+
} catch (e) {
|
|
923
|
+
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 });
|
|
924
|
+
throw e;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
const openApiGenerator = new OpenAPIGenerator();
|
|
929
|
+
function _registerController(controllerClass, prefix) {
|
|
930
|
+
openApiGenerator.registerController(controllerClass, prefix);
|
|
931
|
+
}
|
|
932
|
+
function generateOpenApiSpec() {
|
|
933
|
+
return openApiGenerator.generateSpec();
|
|
934
|
+
}
|
|
935
|
+
function _clearOpenApiRegistry() {
|
|
936
|
+
openApiGenerator._clearControllers();
|
|
937
|
+
}
|
|
938
|
+
//#endregion
|
|
939
|
+
//#region src/types.ts
|
|
940
|
+
const methodResolve = {
|
|
941
|
+
GET: "get",
|
|
942
|
+
PUT: "put",
|
|
943
|
+
POST: "post",
|
|
944
|
+
DELETE: "delete",
|
|
945
|
+
OPTIONS: "options",
|
|
946
|
+
PATCH: "patch",
|
|
947
|
+
HEAD: "head",
|
|
948
|
+
USE: "use"
|
|
949
|
+
};
|
|
950
|
+
//#endregion
|
|
714
951
|
//#region src/annotation/controller.ts
|
|
715
952
|
const _ControllerRegistry = /* @__PURE__ */ new WeakMap();
|
|
716
953
|
/**
|
|
@@ -722,6 +959,7 @@ const _ControllerRegistry = /* @__PURE__ */ new WeakMap();
|
|
|
722
959
|
function Controller({ prefix = "", deps = [] } = {}) {
|
|
723
960
|
return (target) => {
|
|
724
961
|
const targetClass = target;
|
|
962
|
+
_registerController(target, prefix);
|
|
725
963
|
const router = (0, express.Router)();
|
|
726
964
|
const routes = _getRoutes(target);
|
|
727
965
|
const usedRoutes = /* @__PURE__ */ new Set();
|
|
@@ -746,15 +984,20 @@ Split these into separate @MiddlewareClass classes, or merge the logic into a si
|
|
|
746
984
|
if (method === "USE" && fn.length >= 4) {
|
|
747
985
|
const middlewareFn = async (err, request, response, next) => {
|
|
748
986
|
try {
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
987
|
+
await validate({
|
|
988
|
+
target,
|
|
989
|
+
fnName,
|
|
990
|
+
request
|
|
991
|
+
});
|
|
992
|
+
await handleResult({
|
|
993
|
+
result: fn.bind(controllerInstance)(err, request, response, next),
|
|
994
|
+
response,
|
|
995
|
+
target,
|
|
996
|
+
fnName,
|
|
997
|
+
method,
|
|
998
|
+
path: path instanceof RegExp ? path.source : fp,
|
|
999
|
+
isErrorMiddleware: true
|
|
1000
|
+
});
|
|
758
1001
|
} catch (e) {
|
|
759
1002
|
console.error(e);
|
|
760
1003
|
next(e);
|
|
@@ -764,34 +1007,52 @@ Split these into separate @MiddlewareClass classes, or merge the logic into a si
|
|
|
764
1007
|
return;
|
|
765
1008
|
}
|
|
766
1009
|
router[methodName](fp, async (request, response, next) => {
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
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}`));
|
|
1010
|
+
await validate({
|
|
1011
|
+
target,
|
|
1012
|
+
fnName,
|
|
1013
|
+
request
|
|
1014
|
+
});
|
|
1015
|
+
await handleResult({
|
|
1016
|
+
result: await fn.bind(controllerInstance)(request, response, next),
|
|
1017
|
+
response,
|
|
1018
|
+
target,
|
|
1019
|
+
fnName,
|
|
1020
|
+
method,
|
|
1021
|
+
path: path instanceof RegExp ? path.source : fp
|
|
1022
|
+
});
|
|
790
1023
|
});
|
|
791
1024
|
}
|
|
792
1025
|
_ControllerRegistry.set(targetClass, router);
|
|
793
1026
|
};
|
|
794
1027
|
}
|
|
1028
|
+
async function handleResult({ result, target, fnName, response, method, path, isErrorMiddleware = false }) {
|
|
1029
|
+
const schemas = _getValidatorSchema(target, fnName);
|
|
1030
|
+
if (result instanceof ResponseEntity) {
|
|
1031
|
+
const body = schemas && schemas.responseBody ? await _parseOrThrow(schemas.responseBody, result.getBody(), "resbody", fnName) : result.getBody();
|
|
1032
|
+
response.contentType("application/json").status(result.getStatusCode()).set(result.getHeaders()).send(Sapling.serialize(body));
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
if (result instanceof RedirectView) {
|
|
1036
|
+
response.redirect(result.getUrl());
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
if (!isErrorMiddleware && method !== "USE" && !response.writableEnded) response.status(404).send(Html404ErrorPage(`Cannot ${method} ${path}`));
|
|
1040
|
+
}
|
|
1041
|
+
async function validate({ target, fnName, request }) {
|
|
1042
|
+
const schemas = _getValidatorSchema(target, fnName);
|
|
1043
|
+
if (schemas) {
|
|
1044
|
+
if (schemas.requestBody) request.body = await _parseOrThrow(schemas.requestBody, request.body, "reqbody", fnName);
|
|
1045
|
+
if (schemas.requestParam) request.params = await _parseOrThrow(schemas.requestParam, request.params, "reqparams", fnName);
|
|
1046
|
+
if (schemas.requestQuery) {
|
|
1047
|
+
const parsedQuery = await _parseOrThrow(schemas.requestQuery, request.query, "reqquery", fnName);
|
|
1048
|
+
Object.defineProperty(request, "query", {
|
|
1049
|
+
value: parsedQuery,
|
|
1050
|
+
writable: true,
|
|
1051
|
+
configurable: true
|
|
1052
|
+
});
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
795
1056
|
//#endregion
|
|
796
1057
|
//#region src/annotation/middleware.ts
|
|
797
1058
|
/**
|
|
@@ -805,15 +1066,7 @@ function MiddlewareClass(...args) {
|
|
|
805
1066
|
return Controller(...args);
|
|
806
1067
|
}
|
|
807
1068
|
//#endregion
|
|
808
|
-
//#region
|
|
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
|
|
1069
|
+
//#region src/middleware/default/error/base.ts
|
|
817
1070
|
let DefaultBaseErrorMiddleware = class DefaultBaseErrorMiddleware {
|
|
818
1071
|
handle(err, _request, _response, _next) {
|
|
819
1072
|
console.error("[Error]", err);
|
|
@@ -823,7 +1076,20 @@ let DefaultBaseErrorMiddleware = class DefaultBaseErrorMiddleware {
|
|
|
823
1076
|
__decorate([Middleware()], DefaultBaseErrorMiddleware.prototype, "handle", null);
|
|
824
1077
|
DefaultBaseErrorMiddleware = __decorate([MiddlewareClass()], DefaultBaseErrorMiddleware);
|
|
825
1078
|
//#endregion
|
|
826
|
-
//#region src/middleware/default/
|
|
1079
|
+
//#region src/middleware/default/error/parse.ts
|
|
1080
|
+
let DefaultParserErrorMiddleware = class DefaultParserErrorMiddleware {
|
|
1081
|
+
handle(err, _request, _response, next) {
|
|
1082
|
+
if (err instanceof ParserError) {
|
|
1083
|
+
console.warn(err);
|
|
1084
|
+
return ResponseEntity.status(err.status).body({ message: err.message });
|
|
1085
|
+
}
|
|
1086
|
+
next(err);
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
__decorate([Middleware()], DefaultParserErrorMiddleware.prototype, "handle", null);
|
|
1090
|
+
DefaultParserErrorMiddleware = __decorate([MiddlewareClass()], DefaultParserErrorMiddleware);
|
|
1091
|
+
//#endregion
|
|
1092
|
+
//#region src/middleware/default/error/responsestatus.ts
|
|
827
1093
|
let DefaultResponseStatusErrorMiddleware = class DefaultResponseStatusErrorMiddleware {
|
|
828
1094
|
handle(err, _request, _response, next) {
|
|
829
1095
|
if (err instanceof ResponseStatusError) return ResponseEntity.status(err.status).body({ message: err.message });
|
|
@@ -833,7 +1099,103 @@ let DefaultResponseStatusErrorMiddleware = class DefaultResponseStatusErrorMiddl
|
|
|
833
1099
|
__decorate([Middleware()], DefaultResponseStatusErrorMiddleware.prototype, "handle", null);
|
|
834
1100
|
DefaultResponseStatusErrorMiddleware = __decorate([MiddlewareClass()], DefaultResponseStatusErrorMiddleware);
|
|
835
1101
|
//#endregion
|
|
1102
|
+
//#region src/middleware/default/openapi/index.ts
|
|
1103
|
+
let DefaultOpenApiMiddleware = class DefaultOpenApiMiddleware {
|
|
1104
|
+
handle(_request, _response, _next) {
|
|
1105
|
+
return ResponseEntity.ok().body(generateOpenApiSpec());
|
|
1106
|
+
}
|
|
1107
|
+
};
|
|
1108
|
+
__decorate([GET(_settings.doc.openApiPath)], DefaultOpenApiMiddleware.prototype, "handle", null);
|
|
1109
|
+
DefaultOpenApiMiddleware = __decorate([MiddlewareClass()], DefaultOpenApiMiddleware);
|
|
1110
|
+
//#endregion
|
|
1111
|
+
//#region src/middleware/default/swagger/index.ts
|
|
1112
|
+
/**
|
|
1113
|
+
* Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
|
|
1114
|
+
*
|
|
1115
|
+
* Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
|
|
1116
|
+
*
|
|
1117
|
+
* You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
|
|
1118
|
+
*
|
|
1119
|
+
* ```ts
|
|
1120
|
+
* const middlewares = [
|
|
1121
|
+
* DefaultOpenApiMiddleware,
|
|
1122
|
+
* DefaultSwaggerMiddleware.Serve,
|
|
1123
|
+
* DefaultSwaggerMiddleware.Setup,
|
|
1124
|
+
* ];
|
|
1125
|
+
* middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
|
|
1126
|
+
* ```
|
|
1127
|
+
*/
|
|
1128
|
+
let Serve = class Serve {
|
|
1129
|
+
handlers = swagger_ui_express.default.serve;
|
|
1130
|
+
handle(request, response, next) {
|
|
1131
|
+
return Sapling.chainHandlers(this.handlers, request, response, next);
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
__decorate([Middleware(_settings.doc.swaggerPath)], Serve.prototype, "handle", null);
|
|
1135
|
+
Serve = __decorate([MiddlewareClass()], Serve);
|
|
1136
|
+
/**
|
|
1137
|
+
* Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
|
|
1138
|
+
*
|
|
1139
|
+
* Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
|
|
1140
|
+
*
|
|
1141
|
+
* You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
|
|
1142
|
+
*
|
|
1143
|
+
* ```ts
|
|
1144
|
+
* const middlewares = [
|
|
1145
|
+
* DefaultOpenApiMiddleware,
|
|
1146
|
+
* DefaultSwaggerMiddleware.Serve,
|
|
1147
|
+
* DefaultSwaggerMiddleware.Setup,
|
|
1148
|
+
* ];
|
|
1149
|
+
* middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
|
|
1150
|
+
* ```
|
|
1151
|
+
*/
|
|
1152
|
+
let Setup = class Setup {
|
|
1153
|
+
handler;
|
|
1154
|
+
constructor() {
|
|
1155
|
+
this.handler = swagger_ui_express.default.setup(null, { swaggerOptions: { url: _settings.doc.openApiPath } });
|
|
1156
|
+
}
|
|
1157
|
+
handle(request, response, next) {
|
|
1158
|
+
return this.handler(request, response, next);
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
__decorate([Middleware(_settings.doc.swaggerPath)], Setup.prototype, "handle", null);
|
|
1162
|
+
Setup = __decorate([MiddlewareClass()], Setup);
|
|
1163
|
+
/**
|
|
1164
|
+
* Enable the serving of the Swagger endpoint used to serve the OpenAPI spec generated by Sapling.
|
|
1165
|
+
*
|
|
1166
|
+
* Configure any middleware-specific settings with `Sapling.Extras.swaggerAndOpenApi`
|
|
1167
|
+
*
|
|
1168
|
+
* You must register `DefaultSwaggerMiddleware.Serve` & `DefaultSwaggerMiddleware.Setup` after `DefaultOpenApiMiddleware`
|
|
1169
|
+
*
|
|
1170
|
+
* ```ts
|
|
1171
|
+
* const middlewares = [
|
|
1172
|
+
* DefaultOpenApiMiddleware,
|
|
1173
|
+
* DefaultSwaggerMiddleware.Serve,
|
|
1174
|
+
* DefaultSwaggerMiddleware.Setup,
|
|
1175
|
+
* ];
|
|
1176
|
+
* middlewares.map(Sapling.resolve).forEach((r) => app.use(r));
|
|
1177
|
+
* ```
|
|
1178
|
+
*/
|
|
1179
|
+
const DefaultSwaggerMiddleware = {
|
|
1180
|
+
Serve,
|
|
1181
|
+
Setup
|
|
1182
|
+
};
|
|
1183
|
+
//#endregion
|
|
1184
|
+
//#region src/middleware/default/health/index.ts
|
|
1185
|
+
let DefaultHealthMiddleware = class DefaultHealthMiddleware {
|
|
1186
|
+
constructor(healthRegistrar) {
|
|
1187
|
+
this.healthRegistrar = healthRegistrar;
|
|
1188
|
+
}
|
|
1189
|
+
async serve(_request, _response, _next) {
|
|
1190
|
+
const up = await this.healthRegistrar.check();
|
|
1191
|
+
return ResponseEntity.ok().body({ up });
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1194
|
+
__decorate([GET(_settings.health.path)], DefaultHealthMiddleware.prototype, "serve", null);
|
|
1195
|
+
DefaultHealthMiddleware = __decorate([MiddlewareClass({ deps: [HealthRegistrar] })], DefaultHealthMiddleware);
|
|
1196
|
+
//#endregion
|
|
836
1197
|
exports.Controller = Controller;
|
|
1198
|
+
exports.ControllerSchema = ControllerSchema;
|
|
837
1199
|
exports.DELETE = DELETE;
|
|
838
1200
|
Object.defineProperty(exports, "DefaultBaseErrorMiddleware", {
|
|
839
1201
|
enumerable: true,
|
|
@@ -841,14 +1203,39 @@ Object.defineProperty(exports, "DefaultBaseErrorMiddleware", {
|
|
|
841
1203
|
return DefaultBaseErrorMiddleware;
|
|
842
1204
|
}
|
|
843
1205
|
});
|
|
1206
|
+
Object.defineProperty(exports, "DefaultHealthMiddleware", {
|
|
1207
|
+
enumerable: true,
|
|
1208
|
+
get: function() {
|
|
1209
|
+
return DefaultHealthMiddleware;
|
|
1210
|
+
}
|
|
1211
|
+
});
|
|
1212
|
+
Object.defineProperty(exports, "DefaultOpenApiMiddleware", {
|
|
1213
|
+
enumerable: true,
|
|
1214
|
+
get: function() {
|
|
1215
|
+
return DefaultOpenApiMiddleware;
|
|
1216
|
+
}
|
|
1217
|
+
});
|
|
1218
|
+
Object.defineProperty(exports, "DefaultParserErrorMiddleware", {
|
|
1219
|
+
enumerable: true,
|
|
1220
|
+
get: function() {
|
|
1221
|
+
return DefaultParserErrorMiddleware;
|
|
1222
|
+
}
|
|
1223
|
+
});
|
|
844
1224
|
Object.defineProperty(exports, "DefaultResponseStatusErrorMiddleware", {
|
|
845
1225
|
enumerable: true,
|
|
846
1226
|
get: function() {
|
|
847
1227
|
return DefaultResponseStatusErrorMiddleware;
|
|
848
1228
|
}
|
|
849
1229
|
});
|
|
1230
|
+
exports.DefaultSwaggerMiddleware = DefaultSwaggerMiddleware;
|
|
850
1231
|
exports.GET = GET;
|
|
851
1232
|
exports.HEAD = HEAD;
|
|
1233
|
+
Object.defineProperty(exports, "HealthRegistrar", {
|
|
1234
|
+
enumerable: true,
|
|
1235
|
+
get: function() {
|
|
1236
|
+
return HealthRegistrar;
|
|
1237
|
+
}
|
|
1238
|
+
});
|
|
852
1239
|
exports.Html404ErrorPage = Html404ErrorPage;
|
|
853
1240
|
exports.HttpStatus = HttpStatus;
|
|
854
1241
|
exports.Injectable = Injectable;
|
|
@@ -863,16 +1250,29 @@ exports.RedirectView = RedirectView;
|
|
|
863
1250
|
exports.RequestBody = RequestBody;
|
|
864
1251
|
exports.RequestParam = RequestParam;
|
|
865
1252
|
exports.RequestQuery = RequestQuery;
|
|
1253
|
+
exports.ResponseBody = ResponseBody;
|
|
866
1254
|
exports.ResponseEntity = ResponseEntity;
|
|
867
1255
|
exports.ResponseEntityBuilder = ResponseEntityBuilder;
|
|
868
1256
|
exports.ResponseStatusError = ResponseStatusError;
|
|
1257
|
+
exports.RouteSchema = RouteSchema;
|
|
869
1258
|
exports.Sapling = Sapling;
|
|
870
1259
|
exports._ControllerRegistry = _ControllerRegistry;
|
|
871
1260
|
exports._InjectableDeps = _InjectableDeps;
|
|
872
1261
|
exports._InjectableRegistry = _InjectableRegistry;
|
|
873
1262
|
exports._Route = _Route;
|
|
874
|
-
exports.
|
|
1263
|
+
exports._clearOpenApiRegistry = _clearOpenApiRegistry;
|
|
1264
|
+
exports._getControllerSchema = _getControllerSchema;
|
|
1265
|
+
exports._getOrCreateSchemaDefinition = _getOrCreateSchemaDefinition;
|
|
1266
|
+
exports._getRouteSchema = _getRouteSchema;
|
|
875
1267
|
exports._getRoutes = _getRoutes;
|
|
1268
|
+
exports._getValidatorSchema = _getValidatorSchema;
|
|
876
1269
|
exports._parseOrThrow = _parseOrThrow;
|
|
1270
|
+
exports._registerController = _registerController;
|
|
877
1271
|
exports._resolve = _resolve;
|
|
1272
|
+
exports._saveValidatorSchema = _saveValidatorSchema;
|
|
1273
|
+
exports._setControllerSchema = _setControllerSchema;
|
|
1274
|
+
exports._setRouteSchema = _setRouteSchema;
|
|
1275
|
+
exports._settings = _settings;
|
|
1276
|
+
exports.generateOpenApiSpec = generateOpenApiSpec;
|
|
878
1277
|
exports.methodResolve = methodResolve;
|
|
1278
|
+
exports.openApiGenerator = openApiGenerator;
|