@grupo-argenta/schema-kit-nest 0.0.20 → 0.0.21

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 (157) hide show
  1. package/config/naming-strategy.d.ts +6 -0
  2. package/config/naming-strategy.js +17 -0
  3. package/config/redis.constants.d.ts +1 -0
  4. package/config/redis.constants.js +4 -0
  5. package/context-logger.service.d.ts +4 -0
  6. package/context-logger.service.js +23 -0
  7. package/decorators/date-range.d.ts +4 -0
  8. package/decorators/date-range.js +17 -0
  9. package/decorators/encrypted.d.ts +10 -0
  10. package/decorators/encrypted.js +15 -0
  11. package/decorators/file-column.d.ts +17 -0
  12. package/decorators/file-column.js +20 -0
  13. package/decorators/get-user.decorator.d.ts +6 -0
  14. package/decorators/get-user.decorator.js +12 -0
  15. package/decorators/luxon.d.ts +6 -0
  16. package/decorators/luxon.js +20 -0
  17. package/decorators/multipart.decorator.d.ts +4 -0
  18. package/decorators/multipart.decorator.js +51 -0
  19. package/decorators/post-get.decorator.d.ts +10 -0
  20. package/decorators/post-get.decorator.js +25 -0
  21. package/decorators/query-or-body.decorator.d.ts +8 -0
  22. package/decorators/query-or-body.decorator.js +15 -0
  23. package/decorators/when.decorator.d.ts +8 -0
  24. package/decorators/when.decorator.js +16 -0
  25. package/html/components/badge.d.ts +13 -0
  26. package/html/components/badge.js +29 -0
  27. package/html/components/colors.d.ts +11 -0
  28. package/html/components/colors.js +15 -0
  29. package/html/components/component.d.ts +11 -0
  30. package/html/components/component.js +35 -0
  31. package/html/components/default/default-footer.d.ts +6 -0
  32. package/html/components/default/default-footer.js +18 -0
  33. package/html/components/default/default-header.d.ts +13 -0
  34. package/html/components/default/default-header.js +30 -0
  35. package/html/components/env-badge.d.ts +7 -0
  36. package/html/components/env-badge.js +29 -0
  37. package/html/components/grid.d.ts +17 -0
  38. package/html/components/grid.js +44 -0
  39. package/html/components/shell.d.ts +18 -0
  40. package/html/components/shell.js +423 -0
  41. package/html/components/table.d.ts +16 -0
  42. package/html/components/table.js +55 -0
  43. package/html/components/unordered-list.d.ts +6 -0
  44. package/html/components/unordered-list.js +21 -0
  45. package/index.d.ts +49 -0
  46. package/index.js +65 -0
  47. package/interfaces/paginated-result.d.ts +21 -0
  48. package/interfaces/paginated-result.js +12 -0
  49. package/modules/auth/access-token.d.ts +27 -0
  50. package/modules/auth/access-token.js +14 -0
  51. package/modules/auth/known-module.d.ts +45 -0
  52. package/modules/auth/known-module.js +46 -0
  53. package/modules/auth/refresh-token.d.ts +18 -0
  54. package/modules/auth/refresh-token.js +2 -0
  55. package/modules/auth/token-type.d.ts +4 -0
  56. package/modules/auth/token-type.js +8 -0
  57. package/modules/encrypted-column/encrypted-column.module.d.ts +16 -0
  58. package/modules/encrypted-column/encrypted-column.module.js +35 -0
  59. package/modules/pubsub/pubsub-dynamic-topic.service.d.ts +77 -0
  60. package/modules/pubsub/pubsub-dynamic-topic.service.js +324 -0
  61. package/modules/pubsub/pubsub-redeliver-subscriber.service.d.ts +14 -0
  62. package/modules/pubsub/pubsub-redeliver-subscriber.service.js +77 -0
  63. package/modules/pubsub/pubsub-redeliver.service.d.ts +22 -0
  64. package/modules/pubsub/pubsub-redeliver.service.js +48 -0
  65. package/modules/pubsub/pubsub.constants.d.ts +2 -0
  66. package/modules/pubsub/pubsub.constants.js +5 -0
  67. package/modules/pubsub/pubsub.methods.d.ts +18 -0
  68. package/modules/pubsub/pubsub.methods.js +18 -0
  69. package/modules/pubsub/pubsub.methods.redelivery.d.ts +3 -0
  70. package/modules/pubsub/pubsub.methods.redelivery.js +2 -0
  71. package/modules/redis/redis.module.d.ts +10 -0
  72. package/modules/redis/redis.module.js +59 -0
  73. package/modules/redis/redis.options.d.ts +7 -0
  74. package/modules/redis/redis.options.js +4 -0
  75. package/modules/storage/storage.service.d.ts +16 -0
  76. package/modules/storage/storage.service.js +61 -0
  77. package/monitoramento/http-request-log/http-request-log.controller.d.ts +184 -0
  78. package/monitoramento/http-request-log/http-request-log.controller.js +32 -0
  79. package/monitoramento/http-request-log/http-request-log.dto.d.ts +220 -0
  80. package/monitoramento/http-request-log/http-request-log.dto.js +42 -0
  81. package/monitoramento/http-request-log/http-request-log.entity.d.ts +17 -0
  82. package/monitoramento/http-request-log/http-request-log.entity.js +87 -0
  83. package/monitoramento/http-request-log/http-request-log.module.d.ts +2 -0
  84. package/monitoramento/http-request-log/http-request-log.module.js +26 -0
  85. package/monitoramento/http-request-log/http-request-log.service.d.ts +8 -0
  86. package/monitoramento/http-request-log/http-request-log.service.js +35 -0
  87. package/monitoramento/index.d.ts +17 -0
  88. package/monitoramento/index.js +33 -0
  89. package/monitoramento/migrations/1792689106394-create_http_request_logs_table.d.ts +5 -0
  90. package/monitoramento/migrations/1792689106394-create_http_request_logs_table.js +96 -0
  91. package/monitoramento/migrations/1792689106395-create_pubsub_message_logs_table.d.ts +5 -0
  92. package/monitoramento/migrations/1792689106395-create_pubsub_message_logs_table.js +157 -0
  93. package/monitoramento/monitoramento.constants.d.ts +2 -0
  94. package/monitoramento/monitoramento.constants.js +5 -0
  95. package/monitoramento/monitoramento.entities.d.ts +1 -0
  96. package/monitoramento/monitoramento.entities.js +7 -0
  97. package/monitoramento/monitoramento.module.d.ts +6 -0
  98. package/monitoramento/monitoramento.module.js +61 -0
  99. package/monitoramento/monitoramento.options.d.ts +15 -0
  100. package/monitoramento/monitoramento.options.js +2 -0
  101. package/monitoramento/outbound-request.interceptor.d.ts +14 -0
  102. package/monitoramento/outbound-request.interceptor.js +113 -0
  103. package/monitoramento/pubsub-message-log/pubsub-message-log.controller.d.ts +257 -0
  104. package/monitoramento/pubsub-message-log/pubsub-message-log.controller.js +34 -0
  105. package/monitoramento/pubsub-message-log/pubsub-message-log.dto.d.ts +320 -0
  106. package/monitoramento/pubsub-message-log/pubsub-message-log.dto.js +57 -0
  107. package/monitoramento/pubsub-message-log/pubsub-message-log.entity.d.ts +44 -0
  108. package/monitoramento/pubsub-message-log/pubsub-message-log.entity.js +152 -0
  109. package/monitoramento/pubsub-message-log/pubsub-message-log.module.d.ts +2 -0
  110. package/monitoramento/pubsub-message-log/pubsub-message-log.module.js +26 -0
  111. package/monitoramento/pubsub-message-log/pubsub-message-log.service.d.ts +20 -0
  112. package/monitoramento/pubsub-message-log/pubsub-message-log.service.js +99 -0
  113. package/monitoramento/pubsub-self-check/pubsub-self-check.controller.d.ts +9 -0
  114. package/monitoramento/pubsub-self-check/pubsub-self-check.controller.js +45 -0
  115. package/monitoramento/pubsub-self-check/pubsub-self-check.module.d.ts +11 -0
  116. package/monitoramento/pubsub-self-check/pubsub-self-check.module.js +41 -0
  117. package/monitoramento/pubsub-self-check/pubsub-self-check.options.d.ts +10 -0
  118. package/monitoramento/pubsub-self-check/pubsub-self-check.options.js +4 -0
  119. package/monitoramento/pubsub-self-check/pubsub-self-check.service.d.ts +68 -0
  120. package/monitoramento/pubsub-self-check/pubsub-self-check.service.js +213 -0
  121. package/package.json +1 -1
  122. package/schema/abstract.entity.d.ts +28 -0
  123. package/schema/abstract.entity.js +68 -0
  124. package/schema/schema-builder.d.ts +131 -0
  125. package/schema/schema-builder.js +162 -0
  126. package/schema/schema.controller.d.ts +51 -0
  127. package/schema/schema.controller.js +121 -0
  128. package/schema/schema.service.d.ts +81 -0
  129. package/schema/schema.service.js +305 -0
  130. package/schema/typeorm-extensions.d.ts +6 -0
  131. package/schema/typeorm-extensions.js +6 -0
  132. package/schema/zod-extensions/cnpj.validator.d.ts +28 -0
  133. package/schema/zod-extensions/cnpj.validator.js +133 -0
  134. package/schema/zod-extensions/cpf-cnpj.validator.d.ts +2 -0
  135. package/schema/zod-extensions/cpf-cnpj.validator.js +8 -0
  136. package/schema/zod-extensions/cpf.validator.d.ts +18 -0
  137. package/schema/zod-extensions/cpf.validator.js +166 -0
  138. package/schema/zod-extensions.d.ts +50 -0
  139. package/schema/zod-extensions.js +144 -0
  140. package/schema-kit.module.d.ts +2 -0
  141. package/schema-kit.module.js +23 -0
  142. package/transformers/date-range.transformer.d.ts +6 -0
  143. package/transformers/date-range.transformer.js +44 -0
  144. package/transformers/encrypted.transformer.d.ts +11 -0
  145. package/transformers/encrypted.transformer.js +35 -0
  146. package/transformers/luxon.transformer.d.ts +3 -0
  147. package/transformers/luxon.transformer.js +12 -0
  148. package/utils/utils.d.ts +49 -0
  149. package/utils/utils.js +79 -0
  150. package/validators/ip-validator.d.ts +3 -0
  151. package/validators/ip-validator.js +8 -0
  152. package/validators/pubsub-delete.validator.d.ts +6 -0
  153. package/validators/pubsub-delete.validator.js +11 -0
  154. package/validators/url-validator.d.ts +3 -0
  155. package/validators/url-validator.js +8 -0
  156. package/validators/uuid-validator.d.ts +3 -0
  157. package/validators/uuid-validator.js +8 -0
@@ -0,0 +1,324 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ var PubSubDynamicTopicService_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.PubSubAction = exports.PubSubDynamicTopicService = void 0;
17
+ const pubsub_1 = require("@google-cloud/pubsub");
18
+ const zod_1 = __importDefault(require("zod"));
19
+ const common_1 = require("@nestjs/common");
20
+ const context_logger_service_1 = require("../../context-logger.service");
21
+ // Imports relativos: importar o barrel da própria lib gera dependência circular
22
+ const pubsub_message_log_entity_1 = require("../../monitoramento/pubsub-message-log/pubsub-message-log.entity");
23
+ const pubsub_message_log_service_1 = require("../../monitoramento/pubsub-message-log/pubsub-message-log.service");
24
+ const pubsub_constants_1 = require("./pubsub.constants");
25
+ const pubsub_methods_1 = require("./pubsub.methods");
26
+ let PubSubDynamicTopicService = class PubSubDynamicTopicService {
27
+ static { PubSubDynamicTopicService_1 = this; }
28
+ options;
29
+ logger;
30
+ pubSubInstance;
31
+ apiName;
32
+ // Opcional: sem o MonitoramentoModule as mensagens só não são registradas
33
+ messageLog;
34
+ constructor(options) {
35
+ this.options = options;
36
+ this.schemas = {
37
+ [PubSubAction.SAVE]: this.getMessageSchema(options.validators.SAVE, PubSubAction.SAVE),
38
+ [PubSubAction.DELETE]: this.getMessageSchema(options.validators.DELETE, PubSubAction.DELETE),
39
+ };
40
+ if (!this.options.subscriptionOptions) {
41
+ this.options.subscriptionOptions = {
42
+ flowControl: {
43
+ maxMessages: this.options.poolOptions?.size ?? 10,
44
+ },
45
+ maxAckDeadline: pubsub_1.Duration.from({
46
+ seconds: 15,
47
+ }),
48
+ };
49
+ }
50
+ }
51
+ getMessageSchema(zd, action) {
52
+ if (!zd) {
53
+ return undefined;
54
+ }
55
+ return zod_1.default.object({
56
+ from: zod_1.default.string(),
57
+ action: zod_1.default.literal(action),
58
+ type: zod_1.default.enum(PubSubType),
59
+ data: zd,
60
+ });
61
+ }
62
+ onModuleInit() {
63
+ this.logger.setContext(`${PubSubDynamicTopicService_1.name}:${this.constructor.name}:${this.options.modelName}`);
64
+ // Aqui e não no constructor: o logger é injetado por propriedade, só existe depois do constructor
65
+ this.logger.setLogLevels(this.options.log ? ['error', 'warn', 'log', 'debug', 'verbose'] : ['error', 'warn']);
66
+ this.topic = this.pubSubInstance.topic(this.options.modelName);
67
+ }
68
+ schemas;
69
+ topic;
70
+ subscription;
71
+ /**
72
+ * Criações em andamento por recurso. O `register` roda os serviços em paralelo: sem isso, dois serviços com o mesmo
73
+ * tópico/subscription veem "não existe" ao mesmo tempo e o segundo create falha com ALREADY_EXISTS.
74
+ */
75
+ static pendingCreations = new Map();
76
+ /** Executa `create` uma única vez por `key` enquanto estiver em andamento; devolve se o recurso foi criado */
77
+ static createOnce(key, create) {
78
+ let pending = PubSubDynamicTopicService_1.pendingCreations.get(key);
79
+ if (!pending) {
80
+ pending = create().finally(() => PubSubDynamicTopicService_1.pendingCreations.delete(key));
81
+ PubSubDynamicTopicService_1.pendingCreations.set(key, pending);
82
+ }
83
+ return pending;
84
+ }
85
+ async send(message, action) {
86
+ if (Array.isArray(message) && !message.length) {
87
+ common_1.Logger.warn(`Attempted to send an empty array of messages to topic ${this.options.modelName}. No messages were sent.`);
88
+ return;
89
+ }
90
+ const publishMessage = {
91
+ from: this.apiName,
92
+ type: Array.isArray(message) ? PubSubType.ARRAY : PubSubType.OBJECT,
93
+ action: action,
94
+ };
95
+ let data;
96
+ const validator = this.options.validators[action];
97
+ if (!validator) {
98
+ throw new Error(`No validator defined for action ${action}`);
99
+ }
100
+ if (Array.isArray(message)) {
101
+ const validationResult = validator.array().safeParse(message);
102
+ if (!validationResult.success) {
103
+ throw new Error(`Message validation failed: ${validationResult.error.message}`);
104
+ }
105
+ data = validationResult.data;
106
+ }
107
+ else {
108
+ const validationResult = validator.safeParse(message);
109
+ if (!validationResult.success) {
110
+ throw new Error(`Message validation failed: ${validationResult.error.message}`);
111
+ }
112
+ data = validationResult.data;
113
+ }
114
+ this.logger.log('Publishing message to topic:');
115
+ const payload = Buffer.from(JSON.stringify({
116
+ ...publishMessage,
117
+ data: data,
118
+ }));
119
+ const publish = () => this.topic.publishMessage({ data: payload });
120
+ if (!this.messageLog || this.options.monitor === false) {
121
+ await publish();
122
+ return;
123
+ }
124
+ await this.messageLog.registerPublish(payload, { topic: this.options.modelName, originApi: this.apiName, handler: this.constructor.name }, publish);
125
+ }
126
+ async ensureTopicRegistered(topics) {
127
+ this.logger.log(`Ensuring topic ${this.options.modelName} is registered... ⏳`);
128
+ const topicName = this.options.modelName;
129
+ const topicListed = topics.some((topic) => topic.name.split('/').pop() === topicName);
130
+ try {
131
+ const created = !topicListed &&
132
+ (await PubSubDynamicTopicService_1.createOnce(`topic:${topicName}`, async () => {
133
+ // A listagem é eventualmente consistente: confirma com um get antes de criar
134
+ const [exists] = await this.pubSubInstance.topic(topicName).exists();
135
+ if (exists) {
136
+ return false;
137
+ }
138
+ await this.pubSubInstance.createTopic({ name: topicName });
139
+ return true;
140
+ }));
141
+ this.logger.log(`Topic ${topicName} ${created ? 'created' : 'already exists'} ✅`);
142
+ this.topic = this.pubSubInstance.topic(topicName, {
143
+ messageOrdering: true,
144
+ });
145
+ }
146
+ catch (error) {
147
+ if (error instanceof Error) {
148
+ common_1.Logger.error(`Failed to ensure topic ${this.options.modelName} is registered`);
149
+ }
150
+ throw error;
151
+ }
152
+ this.logger.log(`Topic ${this.options.modelName} is registered ✅`);
153
+ }
154
+ async ensureSubscriptionRegistered(subscriptions, options) {
155
+ this.logger.log(`Ensuring subscription ${this.options.modelName} is registered... ⏳`);
156
+ const subscriptionName = `${this.options.modelName}-${this.apiName}-subscription`;
157
+ const subscriptionListed = subscriptions.some((subscription) => subscription.name.split('/').pop() === subscriptionName);
158
+ try {
159
+ const created = !subscriptionListed &&
160
+ (await PubSubDynamicTopicService_1.createOnce(`subscription:${subscriptionName}`, async () => {
161
+ // A listagem é eventualmente consistente: confirma com um get antes de criar
162
+ const [exists] = await this.pubSubInstance.subscription(subscriptionName).exists();
163
+ if (exists) {
164
+ return false;
165
+ }
166
+ const deadLetterTopic = await this.ensureDeadLetterTopic();
167
+ await this.topic.createSubscription(subscriptionName, {
168
+ deadLetterPolicy: {
169
+ deadLetterTopic: deadLetterTopic.name,
170
+ maxDeliveryAttempts: 5,
171
+ },
172
+ });
173
+ return true;
174
+ }));
175
+ this.logger.log(`Subscription ${subscriptionName} ${created ? 'created' : 'already exists'} ✅`);
176
+ // Instancia sempre com as opções (flowControl etc.), inclusive quando acabou de criar
177
+ this.subscription = this.pubSubInstance.subscription(subscriptionName, {
178
+ ...this.options.subscriptionOptions,
179
+ ...options,
180
+ });
181
+ }
182
+ catch (error) {
183
+ if (error instanceof Error) {
184
+ common_1.Logger.error(`Failed to ensure subscription ${subscriptionName} is registered`);
185
+ }
186
+ throw error;
187
+ }
188
+ this.subscription.on('message', async (message) => {
189
+ if (!this.messageLog || this.options.monitor === false) {
190
+ await this.onDidReceiveMessage(message, subscriptionName);
191
+ return;
192
+ }
193
+ await this.messageLog.registerReceive(message, { topic: this.options.modelName, subscription: subscriptionName, handler: this.constructor.name }, async (log) => {
194
+ // `from` do envelope já parseado pelo log; ausente quando a mensagem não segue o formato
195
+ const from = log.payload?.from;
196
+ log.originApi = typeof from === 'string' ? from : null;
197
+ log.ackStatus = await this.onDidReceiveMessage(message, subscriptionName);
198
+ });
199
+ });
200
+ this.logger.log(`Subscription ${subscriptionName} is registered ✅`);
201
+ }
202
+ /** Cria o tópico de dead-letter do modelo se ainda não existir */
203
+ async ensureDeadLetterTopic() {
204
+ const topicName = `${this.options.modelName}-dead-letter`;
205
+ const topic = this.pubSubInstance.topic(topicName);
206
+ await PubSubDynamicTopicService_1.createOnce(`topic:${topicName}`, async () => {
207
+ const [exists] = await topic.exists();
208
+ if (exists) {
209
+ return false;
210
+ }
211
+ await this.pubSubInstance.createTopic({ name: topicName });
212
+ return true;
213
+ });
214
+ return topic;
215
+ }
216
+ /** Processa a mensagem e devolve o ack/nack dado, para o log */
217
+ async onDidReceiveMessage(message, subscriptionName) {
218
+ this.logger.log(`Received message on subscription ${subscriptionName}: ${message.id}`);
219
+ this.logger.log(`Message data: ${message.data.toString().substring(0, 50)}...`);
220
+ //#region Validate message
221
+ const parsedJson = JSON.parse(message.data.toString());
222
+ const { action, schema, type: _type } = this.determineSchemaOptions(parsedJson);
223
+ if (!schema) {
224
+ common_1.Logger.error(`No schema defined for action ${action}, message: ${message.data.toString()}`);
225
+ await message.nackWithResponse();
226
+ return pubsub_message_log_entity_1.PubsubAckStatus.NACK;
227
+ }
228
+ const fullValidation = schema.safeParse(parsedJson);
229
+ if (!fullValidation.success) {
230
+ common_1.Logger.error(`Message validation failed: ${fullValidation.error.message}, message: ${message.data.toString()}`);
231
+ message.nack();
232
+ return pubsub_message_log_entity_1.PubsubAckStatus.NACK;
233
+ }
234
+ if (!this.options.selfConsume && fullValidation.data.from == this.apiName) {
235
+ this.logger.log(`Ignoring message from self on subscription ${subscriptionName}: ${message.id}`);
236
+ message.ack();
237
+ return pubsub_message_log_entity_1.PubsubAckStatus.IGNORED;
238
+ }
239
+ //#endregion Validate message
240
+ switch (action) {
241
+ case PubSubAction.SAVE:
242
+ if ((0, pubsub_methods_1.isPubSubSave)(this)) {
243
+ try {
244
+ await this.onSave(fullValidation.data.data);
245
+ }
246
+ catch {
247
+ message.nack();
248
+ return pubsub_message_log_entity_1.PubsubAckStatus.NACK;
249
+ }
250
+ message.ack();
251
+ return pubsub_message_log_entity_1.PubsubAckStatus.ACK;
252
+ }
253
+ break;
254
+ case PubSubAction.DELETE:
255
+ if ((0, pubsub_methods_1.isPubSubDelete)(this)) {
256
+ try {
257
+ await this.onDelete(fullValidation.data.data);
258
+ }
259
+ catch {
260
+ message.nack();
261
+ return pubsub_message_log_entity_1.PubsubAckStatus.NACK;
262
+ }
263
+ message.ack();
264
+ return pubsub_message_log_entity_1.PubsubAckStatus.ACK;
265
+ }
266
+ break;
267
+ }
268
+ common_1.Logger.error(`No handler defined for action ${action}, message: ${message.data.toString()}`);
269
+ message.nack();
270
+ return pubsub_message_log_entity_1.PubsubAckStatus.NACK;
271
+ }
272
+ determineSchemaOptions(parsedJson) {
273
+ const partial = PartialMessageValidator.safeParse(parsedJson);
274
+ if (!partial.success) {
275
+ throw new Error(`Message validation failed: ${partial.error.message}`);
276
+ }
277
+ const { action, type } = partial.data;
278
+ const schema = this.schemas[action];
279
+ if (!schema) {
280
+ throw new Error(`No schema defined for action ${action}`);
281
+ }
282
+ return { schema, action, type };
283
+ }
284
+ //#region Redisparo geral de tabelas
285
+ async onRequire() { }
286
+ };
287
+ exports.PubSubDynamicTopicService = PubSubDynamicTopicService;
288
+ __decorate([
289
+ (0, common_1.Inject)(context_logger_service_1.ContextLogger),
290
+ __metadata("design:type", context_logger_service_1.ContextLogger)
291
+ ], PubSubDynamicTopicService.prototype, "logger", void 0);
292
+ __decorate([
293
+ (0, common_1.Inject)(pubsub_1.PubSub),
294
+ __metadata("design:type", pubsub_1.PubSub)
295
+ ], PubSubDynamicTopicService.prototype, "pubSubInstance", void 0);
296
+ __decorate([
297
+ (0, common_1.Inject)(pubsub_constants_1.PUBSUB_API_NAME),
298
+ __metadata("design:type", String)
299
+ ], PubSubDynamicTopicService.prototype, "apiName", void 0);
300
+ __decorate([
301
+ (0, common_1.Optional)(),
302
+ (0, common_1.Inject)(pubsub_message_log_service_1.PubsubMessageLogService),
303
+ __metadata("design:type", pubsub_message_log_service_1.PubsubMessageLogService)
304
+ ], PubSubDynamicTopicService.prototype, "messageLog", void 0);
305
+ exports.PubSubDynamicTopicService = PubSubDynamicTopicService = PubSubDynamicTopicService_1 = __decorate([
306
+ (0, common_1.Injectable)(),
307
+ __metadata("design:paramtypes", [Object])
308
+ ], PubSubDynamicTopicService);
309
+ var PubSubAction;
310
+ (function (PubSubAction) {
311
+ PubSubAction["SAVE"] = "SAVE";
312
+ PubSubAction["DELETE"] = "DELETE";
313
+ })(PubSubAction || (exports.PubSubAction = PubSubAction = {}));
314
+ var PubSubType;
315
+ (function (PubSubType) {
316
+ PubSubType["ARRAY"] = "ARRAY";
317
+ PubSubType["OBJECT"] = "OBJECT";
318
+ })(PubSubType || (PubSubType = {}));
319
+ const PartialMessageValidator = zod_1.default.object({
320
+ from: zod_1.default.string(),
321
+ action: zod_1.default.enum(PubSubAction),
322
+ type: zod_1.default.enum(PubSubType),
323
+ data: zod_1.default.unknown(),
324
+ });
@@ -0,0 +1,14 @@
1
+ import { PubSubDynamicTopicService } from './pubsub-dynamic-topic.service';
2
+ import { PubSubSave } from './pubsub.methods';
3
+ import z from 'zod';
4
+ export declare class PubsubRedeliverSubscriberService extends PubSubDynamicTopicService implements PubSubSave<PubsubRedeliverValidatorDto> {
5
+ constructor();
6
+ private redeliverService;
7
+ private pubsub;
8
+ onSave(message: PubsubRedeliverValidatorDto): Promise<void>;
9
+ }
10
+ export declare const pubsubRedeliverValidator: z.ZodObject<{
11
+ schemaName: z.ZodString;
12
+ uuidRequest: z.ZodUUID;
13
+ }, z.core.$strip>;
14
+ export type PubsubRedeliverValidatorDto = z.infer<typeof pubsubRedeliverValidator>;
@@ -0,0 +1,77 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.pubsubRedeliverValidator = exports.PubsubRedeliverSubscriberService = void 0;
16
+ const pubsub_1 = require("@google-cloud/pubsub");
17
+ const common_1 = require("@nestjs/common");
18
+ const pubsub_dynamic_topic_service_1 = require("./pubsub-dynamic-topic.service");
19
+ const pubsub_redeliver_service_1 = require("./pubsub-redeliver.service");
20
+ const pubsub_constants_1 = require("./pubsub.constants");
21
+ const zod_1 = __importDefault(require("zod"));
22
+ let PubsubRedeliverSubscriberService = class PubsubRedeliverSubscriberService extends pubsub_dynamic_topic_service_1.PubSubDynamicTopicService {
23
+ constructor() {
24
+ super({
25
+ modelName: 'PubsubRedelivery',
26
+ validators: {
27
+ [pubsub_dynamic_topic_service_1.PubSubAction.SAVE]: exports.pubsubRedeliverValidator,
28
+ [pubsub_dynamic_topic_service_1.PubSubAction.DELETE]: exports.pubsubRedeliverValidator,
29
+ },
30
+ });
31
+ }
32
+ redeliverService;
33
+ pubsub;
34
+ async onSave(message) {
35
+ //Create subscription to the topic and listen for messages
36
+ const [topic] = await this.pubsub.createTopic({
37
+ name: `${message.schemaName}_redeliver_${message.uuidRequest}`,
38
+ });
39
+ await new Promise((resolve) => {
40
+ // Espera o subscription estar pronto para receber mensagens
41
+ const stream = topic.getSubscriptionsStream();
42
+ stream.on('data', () => {
43
+ resolve(undefined);
44
+ });
45
+ });
46
+ const data = await this.redeliverService.onRedeliverRequested({ schema: message.schemaName });
47
+ try {
48
+ zod_1.default.array(data.validator).validate(zod_1.default);
49
+ await topic.publishMessage({
50
+ json: data.redeliverData,
51
+ });
52
+ this.logger.log(`Redelivered data for schema ${message.schemaName}: [${data.redeliverData.length} items]`);
53
+ }
54
+ catch {
55
+ this.logger.error(`Invalid data for schema ${message.schemaName}, cannot redeliver. Deleting topic ${topic.name}`);
56
+ await topic.delete();
57
+ return;
58
+ }
59
+ }
60
+ };
61
+ exports.PubsubRedeliverSubscriberService = PubsubRedeliverSubscriberService;
62
+ __decorate([
63
+ (0, common_1.Inject)(pubsub_redeliver_service_1.PubsubRedeliverService),
64
+ __metadata("design:type", pubsub_redeliver_service_1.PubsubRedeliverService)
65
+ ], PubsubRedeliverSubscriberService.prototype, "redeliverService", void 0);
66
+ __decorate([
67
+ (0, common_1.Inject)(pubsub_constants_1.PUBSUB_INSTANCE),
68
+ __metadata("design:type", pubsub_1.PubSub)
69
+ ], PubsubRedeliverSubscriberService.prototype, "pubsub", void 0);
70
+ exports.PubsubRedeliverSubscriberService = PubsubRedeliverSubscriberService = __decorate([
71
+ (0, common_1.Injectable)(),
72
+ __metadata("design:paramtypes", [])
73
+ ], PubsubRedeliverSubscriberService);
74
+ exports.pubsubRedeliverValidator = zod_1.default.object({
75
+ schemaName: zod_1.default.string(),
76
+ uuidRequest: zod_1.default.uuidv7(),
77
+ });
@@ -0,0 +1,22 @@
1
+ import { Repository } from 'typeorm';
2
+ import { ContextLogger } from '../../context-logger.service';
3
+ import z from 'zod';
4
+ export declare class PubsubRedeliverService {
5
+ private options;
6
+ private apiName;
7
+ constructor(options: {
8
+ redeliverMap: Record<string, {
9
+ repository: Repository<any>;
10
+ validator: z.ZodType;
11
+ }>;
12
+ });
13
+ private redeliverSubscriber;
14
+ logger: ContextLogger;
15
+ onRedeliverRequested<T>(data: {
16
+ schema: string;
17
+ }): Promise<{
18
+ redeliverData: T[];
19
+ validator: z.ZodType;
20
+ }>;
21
+ requestRedeliver(_schema: string): Promise<void>;
22
+ }
@@ -0,0 +1,48 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.PubsubRedeliverService = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const pubsub_constants_1 = require("./pubsub.constants");
15
+ const pubsub_redeliver_subscriber_service_1 = require("./pubsub-redeliver-subscriber.service");
16
+ let PubsubRedeliverService = class PubsubRedeliverService {
17
+ options;
18
+ apiName;
19
+ constructor(options) {
20
+ this.options = options;
21
+ }
22
+ redeliverSubscriber;
23
+ logger;
24
+ async onRedeliverRequested(data) {
25
+ const repository = this.options.redeliverMap[data.schema].repository;
26
+ if (!repository) {
27
+ this.logger.warn(`No repository found for schema ${data.schema}`);
28
+ }
29
+ const validator = this.options.redeliverMap[data.schema].validator;
30
+ const redeliverData = await repository.createQueryBuilder().getMany();
31
+ this.logger.log(`Redelivering data for schema ${data.schema}: [${redeliverData.length} items]`);
32
+ return { redeliverData, validator };
33
+ }
34
+ async requestRedeliver(_schema) { }
35
+ };
36
+ exports.PubsubRedeliverService = PubsubRedeliverService;
37
+ __decorate([
38
+ (0, common_1.Inject)(pubsub_constants_1.PUBSUB_API_NAME),
39
+ __metadata("design:type", String)
40
+ ], PubsubRedeliverService.prototype, "apiName", void 0);
41
+ __decorate([
42
+ (0, common_1.Inject)(pubsub_redeliver_subscriber_service_1.PubsubRedeliverSubscriberService),
43
+ __metadata("design:type", pubsub_redeliver_subscriber_service_1.PubsubRedeliverSubscriberService)
44
+ ], PubsubRedeliverService.prototype, "redeliverSubscriber", void 0);
45
+ exports.PubsubRedeliverService = PubsubRedeliverService = __decorate([
46
+ (0, common_1.Injectable)(),
47
+ __metadata("design:paramtypes", [Object])
48
+ ], PubsubRedeliverService);
@@ -0,0 +1,2 @@
1
+ export declare const PUBSUB_API_NAME = "PUBSUB_API_NAME";
2
+ export declare const PUBSUB_INSTANCE = "PUBSUB_INSTANCE";
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PUBSUB_INSTANCE = exports.PUBSUB_API_NAME = void 0;
4
+ exports.PUBSUB_API_NAME = 'PUBSUB_API_NAME';
5
+ exports.PUBSUB_INSTANCE = 'PUBSUB_INSTANCE';
@@ -0,0 +1,18 @@
1
+ import { PubSubDynamicTopicService } from './pubsub-dynamic-topic.service';
2
+ export interface PubSubSave<T> {
3
+ onSave: (message: T) => Promise<void>;
4
+ }
5
+ export declare function isPubSubSave<T>(obj: any): obj is PubSubSave<T>;
6
+ export interface PubSubSaveList<T> {
7
+ onSaveList: (message: T[]) => Promise<void>;
8
+ }
9
+ export declare function isPubSubSaveList<T>(obj: any): obj is PubSubSaveList<T>;
10
+ export interface PubSubDelete<T> {
11
+ onDelete: (message: T) => Promise<void>;
12
+ }
13
+ export declare function isPubSubDelete<T>(obj: any): obj is PubSubDelete<T>;
14
+ export interface PubSubDeleteList<T> {
15
+ onDeleteList: (message: T[]) => Promise<void>;
16
+ }
17
+ export declare function isPubSubDeleteList<T>(obj: any): obj is PubSubDeleteList<T>;
18
+ export type PubSubServiceChecker<S extends PubSubDynamicTopicService = PubSubDynamicTopicService, PS = PubSubSave<unknown>, PD = PubSubDelete<unknown>> = (obj: S) => obj is S & (PS | PD);
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isPubSubSave = isPubSubSave;
4
+ exports.isPubSubSaveList = isPubSubSaveList;
5
+ exports.isPubSubDelete = isPubSubDelete;
6
+ exports.isPubSubDeleteList = isPubSubDeleteList;
7
+ function isPubSubSave(obj) {
8
+ return typeof obj.onSave === 'function';
9
+ }
10
+ function isPubSubSaveList(obj) {
11
+ return typeof obj.onSaveList === 'function';
12
+ }
13
+ function isPubSubDelete(obj) {
14
+ return typeof obj.onDelete === 'function';
15
+ }
16
+ function isPubSubDeleteList(obj) {
17
+ return typeof obj.onDeleteList === 'function';
18
+ }
@@ -0,0 +1,3 @@
1
+ export interface PubSubRedeliverable {
2
+ onRedeliver: () => Promise<void>;
3
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,10 @@
1
+ import { DynamicModule, OnApplicationShutdown } from '@nestjs/common';
2
+ import Redis, { RedisOptions } from 'ioredis';
3
+ import { IRedisModuleAsyncOptions } from './redis.options';
4
+ export declare class RedisModule implements OnApplicationShutdown {
5
+ private readonly redis;
6
+ constructor(redis: Redis);
7
+ static forRoot(options: RedisOptions): DynamicModule;
8
+ static forRootAsync(options: IRedisModuleAsyncOptions): DynamicModule;
9
+ onApplicationShutdown(): Promise<void>;
10
+ }
@@ -0,0 +1,59 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ var RedisModule_1;
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.RedisModule = void 0;
20
+ const common_1 = require("@nestjs/common");
21
+ const ioredis_1 = __importDefault(require("ioredis"));
22
+ const redis_constants_1 = require("../../config/redis.constants");
23
+ const redis_options_1 = require("./redis.options");
24
+ let RedisModule = RedisModule_1 = class RedisModule {
25
+ redis;
26
+ constructor(redis) {
27
+ this.redis = redis;
28
+ }
29
+ static forRoot(options) {
30
+ return this.forRootAsync({ useFactory: () => options });
31
+ }
32
+ static forRootAsync(options) {
33
+ return {
34
+ module: RedisModule_1,
35
+ // O provider de opções usa `inject`, então os módulos que fornecem essas dependências precisam estar aqui
36
+ imports: options.imports ?? [],
37
+ providers: [
38
+ { provide: redis_options_1.REDIS_OPTIONS, inject: options.inject ?? [], useFactory: options.useFactory },
39
+ {
40
+ provide: redis_constants_1.REDIS_CLIENT,
41
+ inject: [redis_options_1.REDIS_OPTIONS],
42
+ useFactory: (redisOptions) => new ioredis_1.default(redisOptions),
43
+ },
44
+ ],
45
+ exports: [redis_constants_1.REDIS_CLIENT],
46
+ };
47
+ }
48
+ async onApplicationShutdown() {
49
+ // Fecha a conexão sem perder comandos pendentes
50
+ await this.redis.quit();
51
+ }
52
+ };
53
+ exports.RedisModule = RedisModule;
54
+ exports.RedisModule = RedisModule = RedisModule_1 = __decorate([
55
+ (0, common_1.Global)(),
56
+ (0, common_1.Module)({}),
57
+ __param(0, (0, common_1.Inject)(redis_constants_1.REDIS_CLIENT)),
58
+ __metadata("design:paramtypes", [ioredis_1.default])
59
+ ], RedisModule);
@@ -0,0 +1,7 @@
1
+ import { ModuleMetadata } from '@nestjs/common';
2
+ import { RedisOptions } from 'ioredis';
3
+ export declare const REDIS_OPTIONS = "REDIS_OPTIONS";
4
+ export interface IRedisModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
5
+ inject?: any[];
6
+ useFactory: (...args: any[]) => RedisOptions | Promise<RedisOptions>;
7
+ }
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REDIS_OPTIONS = void 0;
4
+ exports.REDIS_OPTIONS = 'REDIS_OPTIONS';
@@ -0,0 +1,16 @@
1
+ import { ConfigService } from '@nestjs/config';
2
+ import { ContextLogger } from '../../context-logger.service';
3
+ /**
4
+ * Arquivos no bucket privado do Cloud Storage (`GOOGLE_CLOUD_STORAGE_BUCKET`), autenticado por `GOOGLE_APPLICATION_CREDENTIALS`.
5
+ * O banco guarda o caminho do objeto; o front recebe URLs assinadas de leitura.
6
+ */
7
+ export declare class StorageService {
8
+ private readonly bucket;
9
+ logger: ContextLogger;
10
+ constructor(config: ConfigService);
11
+ /** Envia o arquivo para `<prefix>/<uuid>/<nome do arquivo>` e retorna esse caminho */
12
+ upload(file: File, prefix: string): Promise<string>;
13
+ /** URL de leitura temporária do objeto */
14
+ signedUrl(path: string): Promise<string>;
15
+ delete(path: string): Promise<void>;
16
+ }