@tsed/common 6.83.0 → 6.86.0

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.
@@ -1,7 +1,9 @@
1
+ /// <reference types="node" />
1
2
  import { Type } from "@tsed/core";
2
- import { Container, InjectorService, IProvider } from "@tsed/di";
3
+ import { InjectorService, IProvider } from "@tsed/di";
3
4
  import { Platform } from "../services/Platform";
4
5
  import { PlatformApplication } from "../services/PlatformApplication";
6
+ import { IncomingMessage, ServerResponse } from "http";
5
7
  /**
6
8
  * @ignore
7
9
  */
@@ -12,8 +14,15 @@ export interface PlatformType<T = any> extends Type<T> {
12
14
  * @ignore
13
15
  */
14
16
  export interface PlatformBootstrap {
17
+ create(module: Type<any>, settings?: Partial<TsED.Configuration>): PlatformBuilder;
15
18
  bootstrap(module: Type<any>, settings?: Partial<TsED.Configuration>): Promise<PlatformBuilder>;
16
19
  }
20
+ export interface PlatformBuilderOptions {
21
+ name: string;
22
+ providers: IProvider[];
23
+ settings: any;
24
+ module: Type<any>;
25
+ }
17
26
  /**
18
27
  * @platform
19
28
  */
@@ -22,11 +31,8 @@ export declare abstract class PlatformBuilder<App = TsED.Application, Router = T
22
31
  static currentPlatform: Type<PlatformBuilder<any, any>> & PlatformBootstrap;
23
32
  readonly name: string;
24
33
  protected startedAt: Date;
25
- protected locals: Container;
26
- constructor({ name, providers }: {
27
- name: string;
28
- providers: IProvider[];
29
- });
34
+ protected current: Date;
35
+ constructor({ name, providers, settings, module }: PlatformBuilderOptions);
30
36
  get injector(): InjectorService;
31
37
  get rootModule(): any;
32
38
  get app(): PlatformApplication<App, Router>;
@@ -55,7 +61,9 @@ export declare abstract class PlatformBuilder<App = TsED.Application, Router = T
55
61
  get settings(): TsED.Configuration & import("@tsed/di").DIConfiguration;
56
62
  get logger(): import("@tsed/di").DILogger;
57
63
  get disableBootstrapLog(): boolean | undefined;
58
- static build<T extends PlatformBuilder<any, any>>(platformBuildClass: PlatformType<T>): T;
64
+ static build<T extends PlatformBuilder<any, any>>(platformBuildClass: PlatformType<T>, module: Type<any>, settings?: Partial<TsED.Configuration>): T;
65
+ callback(): (req: IncomingMessage, res: ServerResponse) => void;
66
+ callback(req: IncomingMessage, res: ServerResponse): void;
59
67
  log(...data: any[]): any;
60
68
  /**
61
69
  * Add classes to the components list
@@ -83,7 +91,7 @@ export declare abstract class PlatformBuilder<App = TsED.Application, Router = T
83
91
  * @param {any[]} controllers
84
92
  */
85
93
  addControllers(endpoint: string, controllers: any | string | (any | string)[]): void;
86
- runLifecycle(): Promise<void>;
94
+ runLifecycle(): Promise<this>;
87
95
  loadInjector(): Promise<void>;
88
96
  listen(): Promise<void>;
89
97
  stop(): Promise<void>;
@@ -91,6 +99,8 @@ export declare abstract class PlatformBuilder<App = TsED.Application, Router = T
91
99
  callHook(hook: string, ...args: any[]): Promise<void>;
92
100
  loadStatics(hook: string): Promise<void>;
93
101
  useProvider(token: Type<any>, settings?: Partial<IProvider>): this;
102
+ bootstrap(): Promise<this>;
103
+ protected diff(): string;
94
104
  protected importProviders(): Promise<void>;
95
105
  /**
96
106
  * Load middlewares from configuration for the given hook
@@ -100,9 +110,8 @@ export declare abstract class PlatformBuilder<App = TsED.Application, Router = T
100
110
  protected loadMiddlewaresFor(hook: string): void;
101
111
  protected useRouter(): this;
102
112
  protected useContext(): this;
103
- protected bootstrap(module: Type<any>, settings?: Partial<TsED.Configuration>): Promise<this>;
104
113
  protected listenServers(): Promise<void>;
105
114
  protected logRoutes(): Promise<void>;
106
115
  protected loadRoutes(): Promise<void>;
107
- protected createInjector(module: Type<any>, settings: any): void;
116
+ protected createInjector(module: Type<any>, providers: IProvider[], settings: any): void;
108
117
  }
@@ -47,6 +47,10 @@ declare global {
47
47
  * List of directories to scan [Services](/docs/services.md), [Middlewares](/docs/middlewares.md) or [Converters](/docs/converters.md).
48
48
  */
49
49
  componentsScan: (string | RegExp)[];
50
+ /**
51
+ * Disable the glob pattern. In v7 the componentsScan options will be removed in favor of external module loader.
52
+ */
53
+ disableComponentsScan: boolean;
50
54
  /**
51
55
  * List of glob patterns. Exclude all files which matching with this list when Server scan all components with the `mount` or `scanComponents` options.
52
56
  */
package/lib/index.js CHANGED
@@ -11,7 +11,6 @@ var componentsScan = require('@tsed/components-scan');
11
11
  var platformLogMiddleware = require('@tsed/platform-log-middleware');
12
12
  var tslib = require('tslib');
13
13
  var core = require('@tsed/core');
14
- var perf = require('@tsed/perf');
15
14
  var exceptions = require('@tsed/exceptions');
16
15
  var schema = require('@tsed/schema');
17
16
  var util = require('util');
@@ -99,27 +98,7 @@ const rootDir = process.cwd();
99
98
  exports.PlatformConfiguration = PlatformConfiguration_1 = class PlatformConfiguration extends di.DIConfiguration {
100
99
  constructor() {
101
100
  super({
102
- rootDir,
103
- env: process.env.NODE_ENV || core.Env.DEV,
104
- httpPort: 8080,
105
- httpsPort: false,
106
- scopes: {
107
- [di.ProviderType.CONTROLLER]: di.ProviderScope.SINGLETON
108
- },
109
- logger: {
110
- debug: false,
111
- level: "info",
112
- logRequest: true,
113
- jsonIndentation: process.env.NODE_ENV === core.Env.PROD ? 0 : 2
114
- },
115
- errors: {
116
- headerName: "errors"
117
- },
118
- mount: {
119
- "/rest": "${rootDir}/controllers/**/*.ts"
120
- },
121
- exclude: ["**/*.spec.ts", "**/*.spec.js"],
122
- componentsScan: ["${rootDir}/mvc/**/*.ts", "${rootDir}/services/**/*.ts", "${rootDir}/middlewares/**/*.ts"]
101
+ rootDir
123
102
  });
124
103
  }
125
104
 
@@ -2509,45 +2488,81 @@ function getStaticsOptions(statics) {
2509
2488
  }, []);
2510
2489
  }
2511
2490
 
2512
- const {
2513
- bind,
2514
- start,
2515
- end,
2516
- log
2517
- } = perf.PerfLogger.get("bootstrap");
2491
+ function getConfiguration(configuration = {}, module = null) {
2492
+ const store = module ? core.Store.from(module).get("configuration") || {} : {};
2493
+ const env = configuration.env || store.mount || process.env.NODE_ENV || core.Env.DEV;
2494
+
2495
+ const config = _extends({
2496
+ exclude: ["**/*.spec.ts", "**/*.spec.js"],
2497
+ componentsScan: ["${rootDir}/mvc/**/*.ts", "${rootDir}/services/**/*.ts", "${rootDir}/middlewares/**/*.ts"],
2498
+ env,
2499
+ httpPort: 8080,
2500
+ httpsPort: false
2501
+ }, store, configuration, {
2502
+ scopes: _extends({
2503
+ [di.ProviderType.CONTROLLER]: di.ProviderScope.SINGLETON
2504
+ }, store.scopes, configuration.scopes),
2505
+ mount: store.mount || configuration.mount ? core.deepMerge(store.mount || {}, configuration.mount || {}) : {
2506
+ "/rest": "${rootDir}/controllers/**/*.ts"
2507
+ },
2508
+ logger: _extends({
2509
+ debug: false,
2510
+ level: env === core.Env.TEST ? "off" : "info",
2511
+ logRequest: true
2512
+ }, store.logger, configuration.logger, {
2513
+ jsonIndentation: process.env.NODE_ENV === core.Env.PROD ? 0 : 2
2514
+ })
2515
+ });
2516
+
2517
+ if (!configuration.disableComponentsScan && store.componentsScan && configuration.componentsScan) {
2518
+ config.componentsScan = [...store.componentsScan, ...configuration.componentsScan];
2519
+ }
2520
+
2521
+ return config;
2522
+ }
2523
+
2524
+ const DEFAULT_PROVIDERS = [{
2525
+ provide: exports.PlatformHandler
2526
+ }, {
2527
+ provide: exports.PlatformResponse
2528
+ }, {
2529
+ provide: exports.PlatformRequest
2530
+ }, {
2531
+ provide: exports.PlatformRouter
2532
+ }, {
2533
+ provide: exports.PlatformApplication
2534
+ }, {
2535
+ provide: exports.Platform
2536
+ }];
2518
2537
  /**
2519
2538
  * @platform
2520
2539
  */
2521
2540
 
2522
2541
  var _injector = /*#__PURE__*/_classPrivateFieldLooseKey("injector");
2523
2542
 
2524
- var _providers = /*#__PURE__*/_classPrivateFieldLooseKey("providers");
2525
-
2526
2543
  var _rootModule = /*#__PURE__*/_classPrivateFieldLooseKey("rootModule");
2527
2544
 
2528
2545
  class PlatformBuilder {
2529
2546
  constructor({
2530
2547
  name,
2531
- providers
2548
+ providers,
2549
+ settings,
2550
+ module
2532
2551
  }) {
2533
2552
  Object.defineProperty(this, _injector, {
2534
2553
  writable: true,
2535
2554
  value: void 0
2536
2555
  });
2537
- Object.defineProperty(this, _providers, {
2538
- writable: true,
2539
- value: void 0
2540
- });
2541
2556
  Object.defineProperty(this, _rootModule, {
2542
2557
  writable: true,
2543
2558
  value: void 0
2544
2559
  });
2545
2560
  this.name = "";
2546
2561
  this.startedAt = new Date();
2562
+ this.current = new Date();
2547
2563
  this.name = name;
2548
- _classPrivateFieldLooseBase(this, _providers)[_providers] = core.toMap(providers, "provide");
2549
- this.locals = new di.Container();
2550
- this.useProvider(exports.PlatformHandler, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformHandler)).useProvider(exports.PlatformResponse, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformResponse)).useProvider(exports.PlatformRequest, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformRequest)).useProvider(exports.PlatformRouter, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformRouter)).useProvider(exports.PlatformApplication, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.PlatformApplication)).useProvider(exports.Platform, _classPrivateFieldLooseBase(this, _providers)[_providers].get(exports.Platform));
2564
+ _classPrivateFieldLooseBase(this, _rootModule)[_rootModule] = module;
2565
+ this.createInjector(module, providers, settings);
2551
2566
  }
2552
2567
 
2553
2568
  get injector() {
@@ -2602,15 +2617,25 @@ class PlatformBuilder {
2602
2617
  return (_this$settings$logger = this.settings.logger) == null ? void 0 : _this$settings$logger.disableBootstrapLog;
2603
2618
  }
2604
2619
 
2605
- static build(platformBuildClass) {
2620
+ static build(platformBuildClass, module, settings = {}) {
2606
2621
  return new platformBuildClass({
2607
2622
  name: core.nameOf(platformBuildClass).replace("Platform", "").toLowerCase(),
2623
+ module,
2624
+ settings,
2608
2625
  providers: platformBuildClass.providers
2609
2626
  });
2610
2627
  }
2611
2628
 
2629
+ callback(req, res) {
2630
+ if (req && res) {
2631
+ return this.app.callback()(req, res);
2632
+ }
2633
+
2634
+ return this.app.callback();
2635
+ }
2636
+
2612
2637
  log(...data) {
2613
- return this.disableBootstrapLog && this.logger.info(...data);
2638
+ return !this.disableBootstrapLog && this.logger.info(...data, this.diff());
2614
2639
  }
2615
2640
  /**
2616
2641
  * Add classes to the components list
@@ -2656,6 +2681,7 @@ class PlatformBuilder {
2656
2681
  this.useRouter();
2657
2682
  await this.loadRoutes();
2658
2683
  await this.logRoutes();
2684
+ return this;
2659
2685
  }
2660
2686
 
2661
2687
  async loadInjector() {
@@ -2669,7 +2695,7 @@ class PlatformBuilder {
2669
2695
  scope: di.ProviderScope.SINGLETON
2670
2696
  });
2671
2697
  await injector.load(container);
2672
- this.log("Settings and injector loaded");
2698
+ this.log("Settings and injector loaded...");
2673
2699
  await this.callHook("$afterInit");
2674
2700
  }
2675
2701
 
@@ -2678,7 +2704,6 @@ class PlatformBuilder {
2678
2704
  await this.listenServers();
2679
2705
  await this.callHook("$afterListen");
2680
2706
  await this.ready();
2681
- end();
2682
2707
  }
2683
2708
 
2684
2709
  async stop() {
@@ -2699,16 +2724,15 @@ class PlatformBuilder {
2699
2724
  const {
2700
2725
  injector
2701
2726
  } = this;
2702
- log(hook);
2703
2727
 
2704
2728
  if (!this.disableBootstrapLog) {
2705
- injector.logger.info(`\x1B[1mCall hook ${hook}\x1B[22m`);
2729
+ injector.logger.debug(`\x1B[1mCall hook ${hook}\x1B[22m`);
2706
2730
  } // Load middlewares for the given hook
2707
2731
 
2708
2732
 
2709
2733
  this.loadMiddlewaresFor(hook); // call hooks added by providers
2710
2734
 
2711
- await injector.emit(hook);
2735
+ await injector.emit(hook, ...args);
2712
2736
  }
2713
2737
 
2714
2738
  async loadStatics(hook) {
@@ -2724,10 +2748,20 @@ class PlatformBuilder {
2724
2748
  }
2725
2749
 
2726
2750
  useProvider(token, settings) {
2727
- this.locals.addProvider(token, settings);
2751
+ this.injector.addProvider(token, settings);
2728
2752
  return this;
2729
2753
  }
2730
2754
 
2755
+ async bootstrap() {
2756
+ return this.runLifecycle();
2757
+ }
2758
+
2759
+ diff() {
2760
+ const ms = di.colors.yellow(`+${new Date().getTime() - this.current.getTime()}ms`);
2761
+ this.current = new Date();
2762
+ return ms;
2763
+ }
2764
+
2731
2765
  async importProviders() {
2732
2766
  this.injector.logger.debug("Scan components");
2733
2767
  const providers = await componentsScan.importProviders(this.injector.settings, ["imports", "mount", "componentsScan"]);
@@ -2739,6 +2773,7 @@ class PlatformBuilder {
2739
2773
  token
2740
2774
  }));
2741
2775
  this.settings.set("routes", routes);
2776
+ this.log("Providers loaded...");
2742
2777
  }
2743
2778
  /**
2744
2779
  * Load middlewares from configuration for the given hook
@@ -2763,25 +2798,6 @@ class PlatformBuilder {
2763
2798
  return this;
2764
2799
  }
2765
2800
 
2766
- async bootstrap(module, settings = {}) {
2767
- var _settings$logger;
2768
-
2769
- // istanbul ignore next
2770
- if ((_settings$logger = settings.logger) != null && _settings$logger.perf) {
2771
- start();
2772
- bind(this);
2773
- settings.logger = _extends({}, settings.logger, {
2774
- level: "off"
2775
- });
2776
- }
2777
-
2778
- this.createInjector(module, _extends({}, settings, {
2779
- PLATFORM_NAME: this.name
2780
- }));
2781
- await this.runLifecycle();
2782
- return this;
2783
- }
2784
-
2785
2801
  async listenServers() {
2786
2802
  await Promise.all([listenHttpServer(this.injector), listenHttpsServer(this.injector)]);
2787
2803
  }
@@ -2793,9 +2809,9 @@ class PlatformBuilder {
2793
2809
  logger,
2794
2810
  platform
2795
2811
  } = this;
2812
+ this.log("Routes mounted...");
2796
2813
 
2797
2814
  if (!((_this$settings$logger2 = this.settings.logger) != null && _this$settings$logger2.disableRoutesSummary) && !this.disableBootstrapLog) {
2798
- logger.info("Routes mounted :");
2799
2815
  logger.info(printRoutes(await this.injector.alterAsync("$logRoutes", platform.getRoutes())));
2800
2816
  }
2801
2817
  }
@@ -2825,17 +2841,18 @@ class PlatformBuilder {
2825
2841
  await this.callHook("$afterRoutesInit");
2826
2842
  }
2827
2843
 
2828
- createInjector(module, settings) {
2829
- _classPrivateFieldLooseBase(this, _rootModule)[_rootModule] = module;
2830
- const configuration = di.getConfiguration(module, settings);
2831
- _classPrivateFieldLooseBase(this, _injector)[_injector] = createInjector(configuration); // configure locals providers
2832
-
2833
- this.locals.forEach(provider => {
2834
- this.injector.addProvider(provider.token, provider);
2844
+ createInjector(module, providers, settings) {
2845
+ const configuration = getConfiguration(settings, module);
2846
+ configuration.PLATFORM_NAME = this.name;
2847
+ _classPrivateFieldLooseBase(this, _injector)[_injector] = createInjector(configuration);
2848
+ providers = [...DEFAULT_PROVIDERS, ...providers];
2849
+ core.toMap(providers, "provide").forEach((provider, token) => {
2850
+ this.injector.addProvider(token, provider);
2835
2851
  });
2836
2852
  createPlatformApplication(this.injector);
2837
2853
  createHttpsServer(this.injector);
2838
2854
  createHttpServer(this.injector);
2855
+ this.log("Injector created...");
2839
2856
  }
2840
2857
 
2841
2858
  }
@@ -3211,7 +3228,7 @@ function mapReturnedResponse(_ref) {
3211
3228
 
3212
3229
  class PlatformTest extends di.DITest {
3213
3230
  static async create(options = {}) {
3214
- di.DITest.injector = PlatformTest.createInjector(options);
3231
+ di.DITest.injector = PlatformTest.createInjector(getConfiguration(options, null));
3215
3232
  const container = di.createContainer();
3216
3233
  await di.DITest.injector.load(container);
3217
3234
  }
@@ -3243,7 +3260,8 @@ class PlatformTest extends di.DITest {
3243
3260
  } // @ts-ignore
3244
3261
 
3245
3262
 
3246
- instance = await PlatformBuilder.build(platform).bootstrap(mod, di.DITest.configure(settings));
3263
+ settings = di.DITest.configure(settings);
3264
+ instance = await PlatformBuilder.build(platform, mod, settings).bootstrap();
3247
3265
 
3248
3266
  if (!settings.listen) {
3249
3267
  await instance.callHook("$beforeListen");