@innv/nest-initializer 0.1.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.
Files changed (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +257 -0
  3. package/dist/cjs/core/app-initializer.js +431 -0
  4. package/dist/cjs/core/auto-discovery.helper.js +46 -0
  5. package/dist/cjs/core/config-validator.helper.js +28 -0
  6. package/dist/cjs/core/index.js +17 -0
  7. package/dist/cjs/features/health.controller.js +92 -0
  8. package/dist/cjs/features/index.js +18 -0
  9. package/dist/cjs/features/metrics/metrics.controller.js +41 -0
  10. package/dist/cjs/features/metrics/metrics.interceptor.js +45 -0
  11. package/dist/cjs/features/metrics/metrics.module.js +38 -0
  12. package/dist/cjs/features/metrics/metrics.provider.js +29 -0
  13. package/dist/cjs/features/metrics/metrics.tokens.js +5 -0
  14. package/dist/cjs/features/terminus-health-check.module.js +39 -0
  15. package/dist/cjs/index.js +18 -0
  16. package/dist/cjs/plugins/index.js +19 -0
  17. package/dist/cjs/plugins/rate-limiter.plugin.js +26 -0
  18. package/dist/cjs/plugins/request-logger.plugin.js +13 -0
  19. package/dist/cjs/plugins/typeorm-migration.plugin.js +30 -0
  20. package/dist/cjs/starters/caching.starter.js +27 -0
  21. package/dist/cjs/starters/index.js +19 -0
  22. package/dist/cjs/starters/mongoose.starter.js +24 -0
  23. package/dist/cjs/starters/typeorm.starter.js +31 -0
  24. package/dist/esm/core/app-initializer.js +431 -0
  25. package/dist/esm/core/auto-discovery.helper.js +46 -0
  26. package/dist/esm/core/config-validator.helper.js +28 -0
  27. package/dist/esm/core/index.js +17 -0
  28. package/dist/esm/features/health.controller.js +92 -0
  29. package/dist/esm/features/index.js +18 -0
  30. package/dist/esm/features/metrics/metrics.controller.js +41 -0
  31. package/dist/esm/features/metrics/metrics.interceptor.js +45 -0
  32. package/dist/esm/features/metrics/metrics.module.js +38 -0
  33. package/dist/esm/features/metrics/metrics.provider.js +29 -0
  34. package/dist/esm/features/metrics/metrics.tokens.js +5 -0
  35. package/dist/esm/features/terminus-health-check.module.js +39 -0
  36. package/dist/esm/index.js +18 -0
  37. package/dist/esm/plugins/index.js +19 -0
  38. package/dist/esm/plugins/rate-limiter.plugin.js +26 -0
  39. package/dist/esm/plugins/request-logger.plugin.js +13 -0
  40. package/dist/esm/plugins/typeorm-migration.plugin.js +30 -0
  41. package/dist/esm/starters/caching.starter.js +27 -0
  42. package/dist/esm/starters/index.js +19 -0
  43. package/dist/esm/starters/mongoose.starter.js +24 -0
  44. package/dist/esm/starters/typeorm.starter.js +31 -0
  45. package/dist/types/core/app-initializer.d.ts +206 -0
  46. package/dist/types/core/auto-discovery.helper.d.ts +15 -0
  47. package/dist/types/core/config-validator.helper.d.ts +9 -0
  48. package/dist/types/core/index.d.ts +1 -0
  49. package/dist/types/features/health.controller.d.ts +11 -0
  50. package/dist/types/features/index.d.ts +2 -0
  51. package/dist/types/features/metrics/metrics.controller.d.ts +6 -0
  52. package/dist/types/features/metrics/metrics.interceptor.d.ts +8 -0
  53. package/dist/types/features/metrics/metrics.module.d.ts +4 -0
  54. package/dist/types/features/metrics/metrics.provider.d.ts +2 -0
  55. package/dist/types/features/metrics/metrics.tokens.d.ts +2 -0
  56. package/dist/types/features/terminus-health-check.module.d.ts +11 -0
  57. package/dist/types/index.d.ts +6 -0
  58. package/dist/types/plugins/index.d.ts +3 -0
  59. package/dist/types/plugins/rate-limiter.plugin.d.ts +8 -0
  60. package/dist/types/plugins/request-logger.plugin.d.ts +5 -0
  61. package/dist/types/plugins/typeorm-migration.plugin.d.ts +15 -0
  62. package/dist/types/starters/caching.starter.d.ts +20 -0
  63. package/dist/types/starters/index.d.ts +3 -0
  64. package/dist/types/starters/mongoose.starter.d.ts +24 -0
  65. package/dist/types/starters/typeorm.starter.d.ts +19 -0
  66. package/package.json +159 -0
@@ -0,0 +1,431 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.AppInitializer = void 0;
13
+ const path_1 = require("path");
14
+ const common_1 = require("@nestjs/common");
15
+ const config_1 = require("@nestjs/config");
16
+ const core_1 = require("@nestjs/core");
17
+ const swagger_1 = require("@nestjs/swagger");
18
+ const compression_1 = __importDefault(require("compression"));
19
+ const helmet_1 = __importDefault(require("helmet"));
20
+ const auto_discovery_helper_1 = require("./auto-discovery.helper");
21
+ const config_validator_helper_1 = require("./config-validator.helper");
22
+ const features_1 = require("../features");
23
+ const plugins_1 = require("../plugins");
24
+ const starters_1 = require("../starters");
25
+ /**
26
+ * Uma classe fluente (Builder) para inicializar uma aplicação NestJS de forma declarativa.
27
+ */
28
+ class AppInitializer {
29
+ app;
30
+ module;
31
+ adapter;
32
+ logger = new common_1.Logger(AppInitializer.name);
33
+ port = parseInt(process.env.PORT || '3000', 10);
34
+ globalPrefix;
35
+ versioningOptions;
36
+ corsOptions;
37
+ swaggerOptions;
38
+ setupFunctions = [];
39
+ plugins = [];
40
+ featureModules = [];
41
+ advancedSwaggerUiOptions;
42
+ autoDiscoveredComponents;
43
+ globalProviders = [];
44
+ factoryGeneratedControllers = [];
45
+ constructor(module, adapter) {
46
+ this.module = module;
47
+ this.adapter = adapter;
48
+ }
49
+ /**
50
+ * Aplica um conjunto de configurações padrão recomendadas para o ambiente de desenvolvimento.
51
+ * Inclui Swagger e um logger de requisições.
52
+ * @param swaggerOptions Opções para customizar a documentação Swagger.
53
+ */
54
+ useDevelopmentDefaults(swaggerOptions) {
55
+ this.withSwagger({ ...swaggerOptions, path: 'docs' });
56
+ this.withPlugin(new plugins_1.RequestLoggerPlugin());
57
+ return this;
58
+ }
59
+ /**
60
+ * Aplica um conjunto de configurações padrão recomendadas para o ambiente de produção.
61
+ * Inclui Helmet, compressão, graceful shutdown e um rate limiter básico.
62
+ */
63
+ useProductionDefaults() {
64
+ this.useHelmet();
65
+ this.enableCompression();
66
+ this.withGracefulShutdown();
67
+ this.withPlugin(new plugins_1.RateLimiterPlugin());
68
+ return this;
69
+ }
70
+ /**
71
+ * Aplica um bloco de configurações de forma condicional.
72
+ * @param condition A condição booleana. Se for `true`, o callback de configuração será executado.
73
+ * @param configure A função de callback que recebe o builder para aplicar as configurações.
74
+ */
75
+ when(condition, configure) {
76
+ if (condition) {
77
+ configure(this);
78
+ }
79
+ return this;
80
+ }
81
+ withHealthCheck(options) {
82
+ this.featureModules.push(features_1.TerminusHealthCheckModule.forRoot(options));
83
+ return this;
84
+ }
85
+ /**
86
+ * Habilita a coleta e exposição de métricas no padrão Prometheus
87
+ * no endpoint /metrics. Inclui métricas padrão do Node.js
88
+ * e métricas de latência de requisições HTTP.
89
+ */
90
+ withMetrics() {
91
+ this.featureModules.push(features_1.MetricsModule.forRoot());
92
+ return this;
93
+ }
94
+ /**
95
+ * Ponto de entrada estático para criar, configurar e iniciar a aplicação.
96
+ * @param module O módulo raiz da aplicação (ex: AppModule).
97
+ * @param adapterOrConfigurator O adaptador HTTP ou a função de configuração.
98
+ * @param configurator Uma função de callback que recebe o builder para aplicar as configurações.
99
+ */
100
+ static async bootstrap(module, adapterOrConfigurator, configurator) {
101
+ const isExpress = typeof adapterOrConfigurator === 'function';
102
+ const adapter = isExpress ? undefined : adapterOrConfigurator;
103
+ const finalConfigurator = isExpress ? adapterOrConfigurator : configurator;
104
+ if (!finalConfigurator) {
105
+ throw new TypeError('Função de configuração do bootstrap não encontrada. Verifique os argumentos.');
106
+ }
107
+ const initializer = new AppInitializer(module, adapter);
108
+ try {
109
+ initializer.logger.log('Iniciando o processo de bootstrap da aplicação...');
110
+ finalConfigurator(initializer);
111
+ await initializer.listen();
112
+ }
113
+ catch (error) {
114
+ if (error instanceof Error) {
115
+ initializer.logger.error(`Falha ao inicializar a aplicação. Error: ${error.message}`, error.stack);
116
+ }
117
+ else {
118
+ initializer.logger.error('Falha ao inicializar a aplicação com um erro não-padrão.', error);
119
+ }
120
+ process.exit(1);
121
+ }
122
+ }
123
+ /**
124
+ * Define a porta em que a aplicação vai rodar.
125
+ * @param port O número da porta.
126
+ */
127
+ onPort(port) {
128
+ this.port = port;
129
+ return this;
130
+ }
131
+ /**
132
+ * Registra um plugin para ser executado durante a inicialização.
133
+ * @param plugin Uma instância de um objeto que implementa a interface AppInitializerPlugin.
134
+ */
135
+ withPlugin(plugin) {
136
+ this.plugins.push(plugin);
137
+ return this;
138
+ }
139
+ /**
140
+ * Habilita e configura o versionamento da API.
141
+ * @param options As opções de versionamento do NestJS.
142
+ */
143
+ withVersioning(options) {
144
+ this.versioningOptions = options;
145
+ return this;
146
+ }
147
+ /**
148
+ * Define um prefixo global para todas as rotas da aplicação (ex: /api/v1).
149
+ * @param prefix O prefixo a ser aplicado.
150
+ */
151
+ withGlobalPrefix(prefix) {
152
+ this.globalPrefix = prefix.startsWith('/') ? prefix : `/${prefix}`;
153
+ return this;
154
+ }
155
+ /**
156
+ * Habilita e configura o Cross-Origin Resource Sharing (CORS).
157
+ * @param options As opções de configuração do CORS.
158
+ */
159
+ withCors(options = {}) {
160
+ this.corsOptions = options;
161
+ return this;
162
+ }
163
+ /**
164
+ * Adiciona o ValidationPipe global com opções customizadas.
165
+ * Esta é a forma recomendada de habilitar a validação padrão.
166
+ * @param options Opções de configuração para o ValidationPipe.
167
+ */
168
+ withValidationPipe(options = {}) {
169
+ const defaultOptions = {
170
+ whitelist: true,
171
+ forbidNonWhitelisted: true,
172
+ transform: true,
173
+ transformOptions: { enableImplicitConversion: true },
174
+ };
175
+ const finalOptions = { ...defaultOptions, ...options };
176
+ this.globalProviders.push({
177
+ provide: core_1.APP_PIPE,
178
+ useValue: new common_1.ValidationPipe(finalOptions),
179
+ });
180
+ return this;
181
+ }
182
+ /**
183
+ * Registra um Pipe global customizado (ex: um pipe de parsing).
184
+ * O pipe participará da Injeção de Dependência.
185
+ * @param pipe A *classe* do pipe a ser registrada.
186
+ */
187
+ useGlobalPipe(pipe) {
188
+ this.globalProviders.push({
189
+ provide: core_1.APP_PIPE,
190
+ useClass: pipe,
191
+ });
192
+ return this;
193
+ }
194
+ /**
195
+ * Registra um Filtro de Exceção global (ex: HttpExceptionFilter).
196
+ * O filtro participará da Injeção de Dependência.
197
+ * @param filter A *classe* do filtro a ser registrada.
198
+ */
199
+ useGlobalFilter(filter) {
200
+ this.globalProviders.push({
201
+ provide: core_1.APP_FILTER,
202
+ useClass: filter,
203
+ });
204
+ return this;
205
+ }
206
+ /**
207
+ * Registra um Guard global (ex: JwtAuthGuard).
208
+ * O guard participará da Injeção de Dependência.
209
+ * @param guard A *classe* do guard a ser registrada.
210
+ */
211
+ useGlobalGuard(guard) {
212
+ this.globalProviders.push({
213
+ provide: core_1.APP_GUARD,
214
+ useClass: guard,
215
+ });
216
+ return this;
217
+ }
218
+ /**
219
+ * Registra um Interceptor global (ex: LoggingInterceptor).
220
+ * O interceptor participará da Injeção de Dependência.
221
+ * @param interceptor A *classe* do interceptor a ser registrada.
222
+ */
223
+ useGlobalInterceptor(interceptor) {
224
+ this.globalProviders.push({
225
+ provide: core_1.APP_INTERCEPTOR,
226
+ useClass: interceptor,
227
+ });
228
+ return this;
229
+ }
230
+ /**
231
+ * Registra o ClassSerializerInterceptor globalmente.
232
+ * Essencial para transformações de DTO (@Exclude, @Expose).
233
+ * Ele automaticamente recebe o Reflector via DI.
234
+ */
235
+ withClassSerializer() {
236
+ this.globalProviders.push({
237
+ provide: core_1.APP_INTERCEPTOR,
238
+ useClass: common_1.ClassSerializerInterceptor,
239
+ });
240
+ return this;
241
+ }
242
+ /**
243
+ * Habilita e configura a documentação da API via Swagger (OpenAPI).
244
+ * @param options As opções para construir a documentação.
245
+ */
246
+ withSwagger(options) {
247
+ this.swaggerOptions = { path: 'docs', ...options };
248
+ return this;
249
+ }
250
+ /**
251
+ * Aplica customizações avançadas à interface do Swagger UI.
252
+ * Isso pode incluir temas, scripts e outras configurações visuais.
253
+ * Por padrão, aplica um tema escuro e algumas configurações de layout.
254
+ */
255
+ withAdvancedSwaggerUI() {
256
+ // Aponta para os arquivos de customização que criamos.
257
+ // O __dirname aponta para o diretório compilado, que deve ser 'dist' ou 'build'.
258
+ // Os arquivos .css e .js devem estar lá também após a compilação.
259
+ this.advancedSwaggerUiOptions = {
260
+ customCss: (0, path_1.join)(__dirname, 'swagger-ui-customization', 'swagger-dark-theme.css'),
261
+ customJs: (0, path_1.join)(__dirname, 'swagger-ui-customization', 'swagger-custom.js'),
262
+ };
263
+ return this;
264
+ }
265
+ /**
266
+ * Habilita os 'shutdown hooks' do NestJS para um desligamento gracioso.
267
+ */
268
+ withGracefulShutdown() {
269
+ this.setupFunctions.push((app) => app.enableShutdownHooks());
270
+ return this;
271
+ }
272
+ /**
273
+ * Adiciona o middleware de segurança Helmet com configurações padrão.
274
+ */
275
+ useHelmet() {
276
+ this.setupFunctions.push((app) => app.use((0, helmet_1.default)()));
277
+ return this;
278
+ }
279
+ /**
280
+ * Adiciona o middleware de compressão (gzip) para as respostas.
281
+ */
282
+ enableCompression() {
283
+ this.setupFunctions.push((app) => app.use((0, compression_1.default)()));
284
+ return this;
285
+ }
286
+ /**
287
+ * Carrega e valida as variáveis de ambiente na inicialização
288
+ * usando um schema de validação (classe com decoradores class-validator).
289
+ * Se a validação falhar, a aplicação não será iniciada.
290
+ * @param schema A classe de schema para validar (ex: EnvironmentVariables).
291
+ */
292
+ withValidatedConfig(schema) {
293
+ const configModule = config_1.ConfigModule.forRoot({
294
+ isGlobal: true,
295
+ validate: (config) => (0, config_validator_helper_1.validateConfig)(config, schema),
296
+ });
297
+ this.featureModules.push(configModule);
298
+ return this;
299
+ }
300
+ /**
301
+ * Configura e registra automaticamente o TypeOrmModule (Estilo "Starter").
302
+ * @param options Opções para o "Starter" de TypeORM.
303
+ */
304
+ withTypeOrm(options = {}) {
305
+ const starter = (0, starters_1.createTypeOrmStarter)(options);
306
+ this.featureModules.push(starter.module);
307
+ for (const plugin of starter.plugins) {
308
+ this.withPlugin(plugin);
309
+ }
310
+ return this;
311
+ }
312
+ /**
313
+ * Configura e registra automaticamente o MongooseModule (Estilo "Starter").
314
+ * Usa a configuração global (de .withValidatedConfig) para se conectar
315
+ * ao MongoDB e descobre schemas automaticamente.
316
+ *
317
+ * @param options Opções para o "Starter" de Mongoose.
318
+ */
319
+ withMongoose(options = {}) {
320
+ const starter = (0, starters_1.createMongooseStarter)(options);
321
+ this.featureModules.push(starter.module);
322
+ return this;
323
+ }
324
+ /**
325
+ * Configura e registra automaticamente o CacheModule (Estilo "Starter").
326
+ * Usa a configuração global (de .withValidatedConfig) para se conectar
327
+ * ao Redis e torna o cache globalmente disponível.
328
+ *
329
+ * @param options Opções para o "Starter" de Cache.
330
+ */
331
+ withCaching(options = {}) {
332
+ const cacheDynamicModule = (0, starters_1.createCachingStarter)(options);
333
+ this.featureModules.push(cacheDynamicModule);
334
+ return this;
335
+ }
336
+ /**
337
+ * Retorna a instância da aplicação NestJS (INestApplication) após a inicialização.
338
+ * @throws Error se a aplicação ainda não foi inicializada.
339
+ */
340
+ getApp() {
341
+ return this.app;
342
+ }
343
+ /**
344
+ * Habilita a descoberta e registro automático de Providers e Controllers.
345
+ * Varre o projeto em busca de classes com @Injectable() e @Controller()
346
+ * e as adiciona ao módulo raiz.
347
+ * @param options Opções para configurar a descoberta.
348
+ */
349
+ withAutoDiscovery(options) {
350
+ const reflector = new core_1.Reflector();
351
+ this.autoDiscoveredComponents = (0, auto_discovery_helper_1.discoverComponents)(options.basePath, reflector);
352
+ return this;
353
+ }
354
+ async listen() {
355
+ this.logger.log('Criando a instância da aplicação NestJS...');
356
+ const rootImports = [this.module, ...this.featureModules];
357
+ const allProviders = [
358
+ ...(this.autoDiscoveredComponents?.providers ?? []),
359
+ ...this.globalProviders,
360
+ ];
361
+ const allControllers = [
362
+ ...(this.autoDiscoveredComponents?.controllers ?? []),
363
+ ...this.factoryGeneratedControllers,
364
+ ];
365
+ let DynamicRootModule = class DynamicRootModule {
366
+ };
367
+ DynamicRootModule = __decorate([
368
+ (0, common_1.Module)({
369
+ imports: rootImports,
370
+ controllers: allControllers,
371
+ providers: allProviders,
372
+ })
373
+ ], DynamicRootModule);
374
+ this.app = this.adapter
375
+ ? await core_1.NestFactory.create(DynamicRootModule, this.adapter)
376
+ : await core_1.NestFactory.create(DynamicRootModule);
377
+ if (this.globalPrefix)
378
+ this.app.setGlobalPrefix(this.globalPrefix);
379
+ if (this.corsOptions)
380
+ this.app.enableCors(this.corsOptions);
381
+ if (this.versioningOptions) {
382
+ this.app.enableVersioning(this.versioningOptions);
383
+ }
384
+ for (const setup of this.setupFunctions) {
385
+ setup(this.app);
386
+ }
387
+ for (const plugin of this.plugins) {
388
+ this.logger.log(`Aplicando o plugin: ${plugin.constructor.name}`);
389
+ await plugin.apply(this.app);
390
+ }
391
+ if (this.swaggerOptions) {
392
+ const config = new swagger_1.DocumentBuilder()
393
+ .setTitle(this.swaggerOptions.title)
394
+ .setDescription(this.swaggerOptions.description)
395
+ .setVersion(this.swaggerOptions.version)
396
+ .addBearerAuth()
397
+ .build();
398
+ const document = swagger_1.SwaggerModule.createDocument(this.app, config);
399
+ const swaggerSetupOptions = {};
400
+ if (this.advancedSwaggerUiOptions?.customCss) {
401
+ swaggerSetupOptions.customCssUrl =
402
+ this.advancedSwaggerUiOptions.customCss;
403
+ }
404
+ if (this.advancedSwaggerUiOptions?.customJs) {
405
+ swaggerSetupOptions.customJsUrl =
406
+ this.advancedSwaggerUiOptions.customJs;
407
+ }
408
+ swaggerSetupOptions.swaggerOptions = {
409
+ docExpansion: 'none',
410
+ filter: true,
411
+ showRequestDuration: true,
412
+ deepLinking: true,
413
+ displayRequestDuration: true,
414
+ tryItOutEnabled: true,
415
+ persistAuthorization: true,
416
+ defaultModelsExpandDepth: -1,
417
+ operationsSorter: 'alpha',
418
+ tagsSorter: 'alpha',
419
+ };
420
+ swagger_1.SwaggerModule.setup(this.swaggerOptions.path ?? 'docs', this.app, document, swaggerSetupOptions);
421
+ }
422
+ await this.app.listen(this.port);
423
+ const appUrl = await this.app.getUrl();
424
+ this.logger.log(`🚀 Aplicação rodando em: ${appUrl}`);
425
+ if (this.swaggerOptions) {
426
+ const swaggerPath = this.swaggerOptions.path ?? 'docs';
427
+ this.logger.log(`📄 Documentação Swagger disponível em: ${appUrl}/${swaggerPath}`);
428
+ }
429
+ }
430
+ }
431
+ exports.AppInitializer = AppInitializer;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.discoverComponents = discoverComponents;
4
+ const path_1 = require("path");
5
+ const glob_1 = require("glob");
6
+ /**
7
+ * Descobre componentes NestJS (Providers e Controllers) em um diretório.
8
+ * @param basePath O diretório raiz para a varredura.
9
+ * @param reflectorInst Uma instância do Reflector.
10
+ * @param requireFn A função 'require' a ser usada (padrão: Node's require).
11
+ */
12
+ function discoverComponents(basePath, reflectorInst, requireFn = require) {
13
+ const providers = [];
14
+ const controllers = [];
15
+ const files = (0, glob_1.globSync)((0, path_1.join)(basePath, '**/*.{ts,js}'), {
16
+ ignore: [
17
+ '**/*.module.{ts,js}',
18
+ '**/*.spec.{ts,js}',
19
+ '**/node_modules/**',
20
+ '**/features/**',
21
+ '**/plugins/**',
22
+ ],
23
+ absolute: true,
24
+ });
25
+ for (const file of files) {
26
+ try {
27
+ const exports = requireFn(file);
28
+ for (const key in exports) {
29
+ const exportedClass = exports[key];
30
+ if (typeof exportedClass === 'function' && exportedClass.prototype) {
31
+ if (reflectorInst.get('path', exportedClass)) {
32
+ controllers.push(exportedClass);
33
+ }
34
+ else if (reflectorInst.get('__injectable__', exportedClass)) {
35
+ providers.push(exportedClass);
36
+ }
37
+ }
38
+ }
39
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
40
+ }
41
+ catch (_) {
42
+ // Ignora erros
43
+ }
44
+ }
45
+ return { providers, controllers };
46
+ }
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateConfig = validateConfig;
4
+ const class_transformer_1 = require("class-transformer");
5
+ const class_validator_1 = require("class-validator");
6
+ /**
7
+ * Valida um objeto de configuração (ex: process.env) contra uma classe de schema.
8
+ * Se a validação falhar, lança um erro detalhado.
9
+ * @param config O objeto de configuração a ser validado (geralmente process.env).
10
+ * @param schema A classe de schema com decoradores do class-validator.
11
+ * @returns O objeto de configuração validado e transformado.
12
+ */
13
+ function validateConfig(config, schema) {
14
+ const validatedConfig = (0, class_transformer_1.plainToInstance)(schema, config, {
15
+ enableImplicitConversion: true,
16
+ excludeExtraneousValues: true,
17
+ });
18
+ const errors = (0, class_validator_1.validateSync)(validatedConfig, {
19
+ skipMissingProperties: false,
20
+ });
21
+ if (errors.length > 0) {
22
+ const errorMessages = errors
23
+ .map((error) => Object.values(error.constraints || {}).join(', '))
24
+ .join('; ');
25
+ throw new Error(`[Configuração Inválida] ${errorMessages}`);
26
+ }
27
+ return validatedConfig;
28
+ }
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./app-initializer"), exports);
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ 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;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
45
+ return function (target, key) { decorator(target, key, paramIndex); }
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.HealthController = exports.HEALTH_CHECK_OPTIONS = void 0;
49
+ const common_1 = require("@nestjs/common");
50
+ const terminus_1 = require("@nestjs/terminus");
51
+ const terminusHealthCheckModule = __importStar(require("./terminus-health-check.module"));
52
+ exports.HEALTH_CHECK_OPTIONS = 'HEALTH_CHECK_OPTIONS';
53
+ let HealthController = class HealthController {
54
+ options;
55
+ health;
56
+ db;
57
+ memory;
58
+ constructor(options, health, db, memory) {
59
+ this.options = options;
60
+ this.health = health;
61
+ this.db = db;
62
+ this.memory = memory;
63
+ }
64
+ check() {
65
+ const checks = [];
66
+ if (this.options.database && this.db) {
67
+ checks.push(() => this.db.pingCheck('database'));
68
+ }
69
+ if (this.options.memory) {
70
+ const { heapThreshold = 200, rssThreshold = 300 } = this.options.memory;
71
+ checks.push(() => this.memory.checkHeap('memory_heap', heapThreshold * 1024 * 1024));
72
+ checks.push(() => this.memory.checkRSS('memory_rss', rssThreshold * 1024 * 1024));
73
+ }
74
+ return this.health.check(checks);
75
+ }
76
+ };
77
+ exports.HealthController = HealthController;
78
+ __decorate([
79
+ (0, common_1.Get)(),
80
+ (0, terminus_1.HealthCheck)(),
81
+ __metadata("design:type", Function),
82
+ __metadata("design:paramtypes", []),
83
+ __metadata("design:returntype", void 0)
84
+ ], HealthController.prototype, "check", null);
85
+ exports.HealthController = HealthController = __decorate([
86
+ (0, common_1.Controller)('health'),
87
+ __param(0, (0, common_1.Inject)(exports.HEALTH_CHECK_OPTIONS)),
88
+ __param(2, (0, common_1.Optional)()),
89
+ __metadata("design:paramtypes", [Object, terminus_1.HealthCheckService,
90
+ terminus_1.TypeOrmHealthIndicator,
91
+ terminus_1.MemoryHealthIndicator])
92
+ ], HealthController);
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./metrics/metrics.module"), exports);
18
+ __exportStar(require("./terminus-health-check.module"), exports);
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ 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;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.MetricsController = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const prom_client_1 = require("prom-client");
18
+ const metrics_tokens_1 = require("./metrics.tokens");
19
+ let MetricsController = class MetricsController {
20
+ registry;
21
+ constructor(registry) {
22
+ this.registry = registry;
23
+ }
24
+ async getMetrics(res) {
25
+ res.header('Content-Type', this.registry.contentType);
26
+ res.send(await this.registry.metrics());
27
+ }
28
+ };
29
+ exports.MetricsController = MetricsController;
30
+ __decorate([
31
+ (0, common_1.Get)(),
32
+ __param(0, (0, common_1.Res)()),
33
+ __metadata("design:type", Function),
34
+ __metadata("design:paramtypes", [Object]),
35
+ __metadata("design:returntype", Promise)
36
+ ], MetricsController.prototype, "getMetrics", null);
37
+ exports.MetricsController = MetricsController = __decorate([
38
+ (0, common_1.Controller)('metrics'),
39
+ __param(0, (0, common_1.Inject)(metrics_tokens_1.METRICS_REGISTRY)),
40
+ __metadata("design:paramtypes", [prom_client_1.Registry])
41
+ ], MetricsController);