@friggframework/core 2.0.0--canary.658.e11f3b0.0 → 2.0.0--canary.737.83b4e17.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 (102) hide show
  1. package/CLAUDE.md +42 -58
  2. package/application/commands/README.md +17 -11
  3. package/application/commands/entity-commands.js +18 -60
  4. package/application/commands/integration-commands.js +63 -0
  5. package/core/CLAUDE.md +1 -3
  6. package/core/Worker.js +2 -1
  7. package/core/create-handler.js +0 -3
  8. package/core/index.js +0 -6
  9. package/core/invocation-scope.js +24 -30
  10. package/database/documentdb-encryption-service.js +2 -33
  11. package/database/documentdb-utils.js +4 -1
  12. package/database/encryption/README.md +3 -3
  13. package/database/encryption/ciphertext-format.js +24 -0
  14. package/database/encryption/encryption-schema-registry.js +109 -29
  15. package/database/encryption/field-encryption-service.js +55 -16
  16. package/database/encryption/prisma-encryption-extension.js +6 -9
  17. package/database/prisma.js +10 -1
  18. package/encrypt/Cryptor.js +90 -38
  19. package/errors/fetch-error.js +18 -11
  20. package/errors/index.js +4 -2
  21. package/errors/mapping-already-exists-error.js +14 -0
  22. package/generated/prisma-mongodb/edge.js +6 -2
  23. package/generated/prisma-mongodb/index.js +10 -2
  24. package/generated/prisma-mongodb/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  25. package/generated/prisma-mongodb/package.json +1 -1
  26. package/generated/prisma-mongodb/schema.prisma +1 -1
  27. package/generated/prisma-mongodb/wasm.js +6 -2
  28. package/generated/prisma-postgresql/edge.js +6 -2
  29. package/generated/prisma-postgresql/index.js +10 -2
  30. package/generated/prisma-postgresql/libquery_engine-linux-arm64-openssl-3.0.x.so.node +0 -0
  31. package/generated/prisma-postgresql/package.json +1 -1
  32. package/generated/prisma-postgresql/schema.prisma +1 -1
  33. package/generated/prisma-postgresql/wasm.js +6 -2
  34. package/handlers/WEBHOOKS.md +29 -0
  35. package/handlers/app-definition-loader.js +9 -2
  36. package/handlers/app-handler-helpers.js +12 -1
  37. package/handlers/workers/integration-defined-workers.js +0 -2
  38. package/index.js +2 -18
  39. package/infrastructure/scheduler/eventbridge-scheduler-adapter.js +67 -13
  40. package/integrations/integration-base.js +52 -25
  41. package/integrations/integration-router.js +30 -22
  42. package/integrations/repositories/integration-mapping-repository-documentdb.js +50 -0
  43. package/integrations/repositories/integration-mapping-repository-interface.js +15 -0
  44. package/integrations/repositories/integration-mapping-repository-mongo.js +29 -0
  45. package/integrations/repositories/integration-mapping-repository-postgres.js +30 -0
  46. package/integrations/repositories/integration-mapping-repository.js +29 -0
  47. package/integrations/repositories/integration-repository-documentdb.js +42 -23
  48. package/integrations/repositories/integration-repository-interface.js +37 -21
  49. package/integrations/repositories/integration-repository-mongo.js +69 -30
  50. package/integrations/repositories/integration-repository-postgres.js +74 -30
  51. package/integrations/repositories/process-repository-mongo.js +1 -1
  52. package/integrations/tests/doubles/test-integration-repository.js +2 -15
  53. package/integrations/use-cases/add-entities-to-integration.js +92 -0
  54. package/integrations/use-cases/create-integration.js +57 -19
  55. package/integrations/use-cases/delete-integration-for-user.js +8 -11
  56. package/integrations/use-cases/get-integration-instance.js +12 -12
  57. package/integrations/use-cases/remove-entities-from-integration.js +70 -0
  58. package/integrations/use-cases/update-integration-messages.js +9 -28
  59. package/integrations/use-cases/update-integration.js +12 -12
  60. package/integrations/utils/assert-entity-ids-input.js +42 -0
  61. package/jest-setup.js +13 -2
  62. package/jest-teardown.js +5 -2
  63. package/jest.config.js +4 -0
  64. package/jest.db.config.js +23 -0
  65. package/logs/serialize.js +0 -15
  66. package/modules/module.js +0 -27
  67. package/modules/requester/requester.js +9 -211
  68. package/modules/use-cases/create-entity-from-credential.js +105 -0
  69. package/modules/use-cases/get-entity-options-by-id.js +7 -5
  70. package/modules/use-cases/get-module.js +29 -8
  71. package/modules/use-cases/process-authorization-callback.js +78 -27
  72. package/modules/use-cases/refresh-entity-options.js +7 -5
  73. package/modules/use-cases/test-module-auth.js +7 -5
  74. package/modules/utils/find-module-definition.js +23 -0
  75. package/modules/utils/map-module-dto.js +5 -3
  76. package/modules/utils/to-credential-id.js +14 -0
  77. package/package.json +10 -7
  78. package/prisma-mongodb/schema.prisma +1 -1
  79. package/prisma-postgresql/schema.prisma +1 -1
  80. package/queues/queuer-util.js +9 -7
  81. package/queues/sqs-message-body.js +17 -0
  82. package/telemetry/otel-telemetry.js +76 -3
  83. package/telemetry/telemetry-config.js +16 -5
  84. package/telemetry/telemetry-runtime.js +14 -1
  85. package/token/repositories/token-repository-documentdb.js +13 -1
  86. package/token/repositories/token-repository-mongo.js +13 -1
  87. package/token/repositories/token-repository-postgres.js +13 -1
  88. package/types/core/index.d.ts +0 -33
  89. package/types/errors/index.d.ts +0 -47
  90. package/types/integrations/index.d.ts +4 -20
  91. package/types/module-plugin/index.d.ts +0 -47
  92. package/user/tests/doubles/test-user-repository.js +1 -1
  93. package/user/use-cases/authenticate-user.js +23 -7
  94. package/user/use-cases/get-user-from-bearer-token.js +7 -2
  95. package/core/invocation-deadline.js +0 -91
  96. package/errors/rate-limit-error.js +0 -46
  97. package/integrations/repositories/message-item-shared.js +0 -4
  98. package/integrations/tests/doubles/prisma-message-row.js +0 -24
  99. package/integrations/use-cases/record-rate-limit-message.js +0 -110
  100. package/modules/requester/rate-limit/index.js +0 -4
  101. package/modules/requester/rate-limit/parsers.js +0 -245
  102. package/modules/requester/rate-limit/policy.js +0 -304
@@ -3,7 +3,6 @@ const {
3
3
  IntegrationRepositoryInterface,
4
4
  } = require('./integration-repository-interface');
5
5
  const { validateConfigPatch } = require('./config-patch-shared');
6
- const { messagesOfType } = require('./message-item-shared');
7
6
  const { strictIntId } = require('./report-id');
8
7
 
9
8
  /**
@@ -274,16 +273,17 @@ class IntegrationRepositoryPostgres extends IntegrationRepositoryInterface {
274
273
  *
275
274
  * @param {string} integrationId - Integration ID (string from application layer)
276
275
  * @param {string} messageType - Type of message (errors, warnings, info, logs)
277
- * @param {Object} item - Message item, stored as it is
278
- * @param {Object} options
279
- * @param {number} options.keepLast - How many of the newest items of the type to keep
276
+ * @param {string} messageTitle - Message title
277
+ * @param {string} messageBody - Message body
278
+ * @param {Date} messageTimestamp - Message timestamp
280
279
  * @returns {Promise<boolean>} Success indicator
281
280
  */
282
281
  async updateIntegrationMessages(
283
282
  integrationId,
284
283
  messageType,
285
- item,
286
- { keepLast }
284
+ messageTitle,
285
+ messageBody,
286
+ messageTimestamp
287
287
  ) {
288
288
  const intId = this._convertId(integrationId);
289
289
 
@@ -297,43 +297,29 @@ class IntegrationRepositoryPostgres extends IntegrationRepositoryInterface {
297
297
  }
298
298
 
299
299
  // Parse existing messages (JSON field)
300
- const messageArray = messagesOfType(integration, messageType);
300
+ const messages = integration.messages || {};
301
+ const messageArray = Array.isArray(messages[messageType])
302
+ ? messages[messageType]
303
+ : [];
301
304
 
302
305
  // Add new message
303
- messageArray.push(item);
306
+ messageArray.push({
307
+ title: messageTitle,
308
+ message: messageBody,
309
+ timestamp: messageTimestamp,
310
+ });
304
311
 
305
312
  // Update messages
306
313
  await this.prisma.integration.update({
307
314
  where: { id: intId },
308
315
  data: {
309
- [messageType]: messageArray.slice(-keepLast),
316
+ [messageType]: messageArray,
310
317
  },
311
318
  });
312
319
 
313
320
  return true; // Mongoose compatibility
314
321
  }
315
322
 
316
- /**
317
- * Find the stored messages of one type
318
- *
319
- * @param {string} integrationId - Integration ID (string from application layer)
320
- * @param {string} messageType - Type of message (errors, warnings, info, logs)
321
- * @returns {Promise<Array>} The stored message items of that type, oldest first
322
- */
323
- async findIntegrationMessages(integrationId, messageType) {
324
- const intId = this._convertId(integrationId);
325
- const integration = await this.prisma.integration.findUnique({
326
- where: { id: intId },
327
- select: { [messageType]: true },
328
- });
329
-
330
- if (!integration) {
331
- throw new Error(`Integration ${integrationId} not found`);
332
- }
333
-
334
- return messagesOfType(integration, messageType);
335
- }
336
-
337
323
  /**
338
324
  * Create a new integration
339
325
  *
@@ -379,6 +365,64 @@ class IntegrationRepositoryPostgres extends IntegrationRepositoryInterface {
379
365
  };
380
366
  }
381
367
 
368
+ /**
369
+ * Attach entities to an existing integration. Entities already attached
370
+ * are left as they are.
371
+ *
372
+ * @param {string} integrationId - Integration ID (string from application layer)
373
+ * @param {Array<string>} entityIds - Entity IDs to attach
374
+ * @returns {Promise<Object|null>} Updated integration, or null when the integration does not exist
375
+ */
376
+ async addEntitiesToIntegration(integrationId, entityIds) {
377
+ const intId = this._convertId(integrationId);
378
+
379
+ try {
380
+ await this.prisma.integration.update({
381
+ where: { id: intId },
382
+ data: {
383
+ entities: {
384
+ connect: entityIds.map((id) => ({
385
+ id: this._convertId(id),
386
+ })),
387
+ },
388
+ },
389
+ });
390
+ } catch (error) {
391
+ if (error.code === 'P2025') return null;
392
+ throw error;
393
+ }
394
+ return this.findIntegrationById(integrationId);
395
+ }
396
+
397
+ /**
398
+ * Detach entities from an integration. Entities that are not attached
399
+ * are ignored. The entities themselves are not deleted.
400
+ *
401
+ * @param {string} integrationId - Integration ID (string from application layer)
402
+ * @param {Array<string>} entityIds - Entity IDs to detach
403
+ * @returns {Promise<Object|null>} Updated integration, or null when the integration does not exist
404
+ */
405
+ async removeEntitiesFromIntegration(integrationId, entityIds) {
406
+ const intId = this._convertId(integrationId);
407
+
408
+ try {
409
+ await this.prisma.integration.update({
410
+ where: { id: intId },
411
+ data: {
412
+ entities: {
413
+ disconnect: entityIds.map((id) => ({
414
+ id: this._convertId(id),
415
+ })),
416
+ },
417
+ },
418
+ });
419
+ } catch (error) {
420
+ if (error.code === 'P2025') return null;
421
+ throw error;
422
+ }
423
+ return this.findIntegrationById(integrationId);
424
+ }
425
+
382
426
  /**
383
427
  * Find integration by user ID (returns single integration)
384
428
  *
@@ -120,7 +120,7 @@ class ProcessRepositoryMongo extends ProcessRepositoryInterface {
120
120
  if (normalized.newState !== null) {
121
121
  $set.state = normalized.newState;
122
122
  }
123
- $set.updatedAt = new Date();
123
+ $set.updatedAt = { $date: new Date().toISOString() };
124
124
  update.$set = $set;
125
125
 
126
126
  if (Object.keys(normalized.pushSlice).length > 0) {
@@ -72,31 +72,18 @@ class TestIntegrationRepository {
72
72
  return results;
73
73
  }
74
74
 
75
- async updateIntegrationMessages(id, type, item, { keepLast }) {
75
+ async updateIntegrationMessages(id, type, title, body, timestamp) {
76
76
  const rec = this.store.get(id);
77
77
  if (!rec) {
78
78
  this.operationHistory.push({ operation: 'updateMessages', id, success: false });
79
79
  return false;
80
80
  }
81
81
  if (!rec.messages[type]) rec.messages[type] = [];
82
- rec.messages[type].push(item);
83
- rec.messages[type] = rec.messages[type].slice(-keepLast);
82
+ rec.messages[type].push({ title, message: body, timestamp });
84
83
  this.operationHistory.push({ operation: 'updateMessages', id, type, success: true });
85
84
  return true;
86
85
  }
87
86
 
88
- async findIntegrationMessages(id, type) {
89
- const rec = this.store.get(id);
90
- this.operationHistory.push({
91
- operation: 'findMessages',
92
- id,
93
- type,
94
- found: !!rec,
95
- });
96
- if (!rec) throw new Error(`Integration ${id} not found`);
97
- return [...(rec.messages[type] ?? [])];
98
- }
99
-
100
87
  async updateIntegrationConfig(id, config) {
101
88
  if (config === null || config === undefined) {
102
89
  throw new Error('Config parameter is required');
@@ -0,0 +1,92 @@
1
+ const {
2
+ assertEntityIdsInput,
3
+ integrationNotFound,
4
+ loadIntegration,
5
+ } = require('../utils/assert-entity-ids-input');
6
+
7
+ /**
8
+ * Attaches entities to an existing integration, e.g. when a user grants
9
+ * access to more accounts after the integration was created. Every entity
10
+ * must exist, belong to the integration's user, and be of a module the
11
+ * integration already holds (so hydration can load it). Entities that are
12
+ * already attached are left as they are.
13
+ * @class AddEntitiesToIntegration
14
+ */
15
+ class AddEntitiesToIntegration {
16
+ /**
17
+ * @param {Object} params
18
+ * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
19
+ * @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
20
+ */
21
+ constructor({ integrationRepository, moduleRepository }) {
22
+ this.integrationRepository = integrationRepository;
23
+ this.moduleRepository = moduleRepository;
24
+ }
25
+
26
+ /**
27
+ * @param {string} integrationId
28
+ * @param {string[]} entityIds
29
+ * @returns {Promise<Object>} The updated integration record.
30
+ */
31
+ async execute(integrationId, entityIds) {
32
+ assertEntityIdsInput(integrationId, entityIds);
33
+
34
+ const integration = await loadIntegration(
35
+ this.integrationRepository,
36
+ integrationId
37
+ );
38
+
39
+ const entities = await this.moduleRepository.findEntitiesByIds(
40
+ entityIds
41
+ );
42
+ const foundIds = new Set(entities.map((e) => String(e.id)));
43
+ const missing = entityIds.filter((id) => !foundIds.has(String(id)));
44
+ if (missing.length > 0) {
45
+ const error = new Error(
46
+ `Entities not found: ${missing.join(', ')}`
47
+ );
48
+ error.code = 'ENTITIES_NOT_FOUND';
49
+ throw error;
50
+ }
51
+
52
+ const foreign = entities.filter(
53
+ (e) => String(e.userId) !== String(integration.userId)
54
+ );
55
+ if (foreign.length > 0) {
56
+ const error = new Error(
57
+ `Entities do not belong to the integration's user: ${foreign
58
+ .map((e) => e.id)
59
+ .join(', ')}`
60
+ );
61
+ error.code = 'ENTITY_USER_MISMATCH';
62
+ throw error;
63
+ }
64
+
65
+ const attached = await this.moduleRepository.findEntitiesByIds(
66
+ integration.entitiesIds ?? []
67
+ );
68
+ const heldModules = new Set(attached.map((e) => e.moduleName));
69
+ const otherModules = entities.filter(
70
+ (e) => !heldModules.has(e.moduleName)
71
+ );
72
+ if (otherModules.length > 0) {
73
+ const error = new Error(
74
+ `Entities belong to a module the integration does not hold: ${otherModules
75
+ .map((e) => `${e.id} (${e.moduleName})`)
76
+ .join(', ')}`
77
+ );
78
+ error.code = 'ENTITY_MODULE_MISMATCH';
79
+ throw error;
80
+ }
81
+
82
+ const updated =
83
+ await this.integrationRepository.addEntitiesToIntegration(
84
+ integrationId,
85
+ entityIds
86
+ );
87
+ if (!updated) throw integrationNotFound(integrationId);
88
+ return updated;
89
+ }
90
+ }
91
+
92
+ module.exports = { AddEntitiesToIntegration };
@@ -62,7 +62,7 @@ class CreateIntegration {
62
62
 
63
63
  // A concurrent request may have created a matching row between the
64
64
  // lookup above and this insert; re-check before any side effects run.
65
- const survivor = await this._findDuplicate(
65
+ const survivor = await this._findSurvivor(
66
66
  userId,
67
67
  config?.type,
68
68
  entities
@@ -135,30 +135,68 @@ class CreateIntegration {
135
135
  return mapIntegrationClassToIntegrationDTO(integrationInstance);
136
136
  }
137
137
 
138
- async _findDuplicate(userId, type, entityIds) {
138
+ async _findMatches(userId, type, entityIds) {
139
139
  const candidates =
140
140
  await this.integrationRepository.findIntegrationsByUserId(userId);
141
- const target = [...(entityIds ?? [])].map(String).sort();
142
-
143
- const matches = candidates.filter((integration) => {
144
- // An IN_DELETION row is either mid-teardown or a zombie left
145
- // behind by a failed deleteIntegrationById call — never a live
146
- // integration. Treating it as a duplicate would hand a reinstall
147
- // attempt a row nothing will ever move out of IN_DELETION,
148
- // silently discarded by the queue worker forever. Let a fresh
149
- // create proceed instead; the zombie is cleaned up out-of-band,
150
- // matching how teardown failures are already handled here.
151
- if (integration.status === 'IN_DELETION') return false;
152
- if (integration.config?.type !== type) return false;
153
- const current = [...(integration.entitiesIds ?? [])]
154
- .map(String)
155
- .sort();
141
+ const target = new Set((entityIds ?? []).map(String));
142
+
143
+ const live = candidates.filter(
144
+ (integration) =>
145
+ // An IN_DELETION row is either mid-teardown or a zombie left
146
+ // behind by a failed deleteIntegrationById call — never a live
147
+ // integration. Treating it as a duplicate would hand a
148
+ // reinstall attempt a row nothing will ever move out of
149
+ // IN_DELETION, silently discarded by the queue worker forever.
150
+ // Let a fresh create proceed instead; the zombie is cleaned up
151
+ // out-of-band, matching how teardown failures are already
152
+ // handled here.
153
+ integration.status !== 'IN_DELETION' &&
154
+ integration.config?.type === type
155
+ );
156
+ const entitySet = (integration) =>
157
+ new Set((integration.entitiesIds ?? []).map(String));
158
+
159
+ const exact = live.filter((integration) => {
160
+ const current = entitySet(integration);
156
161
  return (
157
- current.length === target.length &&
158
- current.every((id, index) => id === target[index])
162
+ current.size === target.size &&
163
+ [...target].every((id) => current.has(id))
159
164
  );
160
165
  });
161
166
 
167
+ // Entities may have been attached after create (addEntitiesToIntegration),
168
+ // so a reconnect that sends the original entities must still find the
169
+ // integration that now holds them, instead of creating a second one
170
+ // that would share those entities.
171
+ const supersets = live.filter((integration) => {
172
+ const current = entitySet(integration);
173
+ return [...target].every((id) => current.has(id));
174
+ });
175
+ return { exact, supersets: target.size ? supersets : [] };
176
+ }
177
+
178
+ async _findDuplicate(userId, type, entityIds) {
179
+ const { exact, supersets } = await this._findMatches(
180
+ userId,
181
+ type,
182
+ entityIds
183
+ );
184
+ if (exact.length) return this._pickOldest(exact);
185
+ return supersets.length ? this._pickOldest(supersets) : null;
186
+ }
187
+
188
+ // After an insert the new row is itself an exact match, so the survivor
189
+ // is the oldest of every exact or superset match (the new row included):
190
+ // an older integration that already holds these entities always wins.
191
+ async _findSurvivor(userId, type, entityIds) {
192
+ const { exact, supersets } = await this._findMatches(
193
+ userId,
194
+ type,
195
+ entityIds
196
+ );
197
+ // supersets includes the exact matches; it is empty only for an
198
+ // empty entity set, where exact matching alone applies.
199
+ const matches = supersets.length ? supersets : exact;
162
200
  return matches.length ? this._pickOldest(matches) : null;
163
201
  }
164
202
 
@@ -31,14 +31,17 @@ class DeleteIntegrationForUser {
31
31
  * @param {string} integrationId - ID of the integration to delete.
32
32
  * @param {string} userId - ID of the user requesting the deletion.
33
33
  * @returns {Promise<void>} Resolves when the integration is successfully deleted.
34
- * @throws {Boom.notFound} When integration with the specified ID does not exist.
35
- * @throws {Error} When the integration doesn't belong to the specified user.
34
+ * @throws {Boom.notFound} When integration does not exist or doesn't belong to the specified user.
36
35
  */
37
36
  async execute(integrationId, userId) {
38
- const integrationRecord =
39
- await this.integrationRepository.findIntegrationById(integrationId);
37
+ const integrationRecord = await this.integrationRepository
38
+ .findIntegrationById(integrationId)
39
+ .catch((error) => {
40
+ if (error.message?.includes('not found')) return null;
41
+ throw error;
42
+ });
40
43
 
41
- if (!integrationRecord) {
44
+ if (!integrationRecord || integrationRecord.userId !== userId) {
42
45
  throw Boom.notFound(
43
46
  `Integration with id of ${integrationId} does not exist`
44
47
  );
@@ -50,12 +53,6 @@ class DeleteIntegrationForUser {
50
53
  integrationRecord.config.type
51
54
  );
52
55
 
53
- if (integrationRecord.userId !== userId) {
54
- throw new Error(
55
- `Integration ${integrationId} does not belong to User ${userId}`
56
- );
57
- }
58
-
59
56
  // Load modules with API clients for webhook deletion
60
57
  const modules = [];
61
58
  const failedModuleLoads = [];
@@ -1,3 +1,4 @@
1
+ const Boom = require('@hapi/boom');
1
2
  // Removed Integration wrapper - using IntegrationBase directly
2
3
 
3
4
  /**
@@ -24,15 +25,20 @@ class GetIntegrationInstance {
24
25
  * @param {string} integrationId - ID of the integration to retrieve.
25
26
  * @param {string} userId - ID of the user requesting the integration.
26
27
  * @returns {Promise<Integration>} The fully initialized integration instance.
27
- * @throws {Error} When integration is not found, doesn't belong to user, or integration class is not found.
28
+ * @throws {Boom.notFound} When integration is not found or doesn't belong to user.
29
+ * @throws {Error} When integration class is not found.
28
30
  */
29
31
  async execute(integrationId, userId) {
30
- const integrationRecord =
31
- await this.integrationRepository.findIntegrationById(integrationId);
32
+ const integrationRecord = await this.integrationRepository
33
+ .findIntegrationById(integrationId)
34
+ .catch((error) => {
35
+ if (error.message?.includes('not found')) return null;
36
+ throw error;
37
+ });
32
38
 
33
- if (!integrationRecord) {
34
- throw new Error(
35
- `No integration found by the ID of ${integrationId}`
39
+ if (!integrationRecord || integrationRecord.userId !== userId) {
40
+ throw Boom.notFound(
41
+ `Integration with id of ${integrationId} does not exist`
36
42
  );
37
43
  }
38
44
 
@@ -48,12 +54,6 @@ class GetIntegrationInstance {
48
54
  );
49
55
  }
50
56
 
51
- if (integrationRecord.userId !== userId) {
52
- throw new Error(
53
- `Integration ${integrationId} does not belong to User ${userId}`
54
- );
55
- }
56
-
57
57
  const modules = [];
58
58
  for (const entityId of integrationRecord.entitiesIds) {
59
59
  const moduleInstance = await this.moduleFactory.getModuleInstance(
@@ -0,0 +1,70 @@
1
+ const {
2
+ assertEntityIdsInput,
3
+ integrationNotFound,
4
+ loadIntegration,
5
+ } = require('../utils/assert-entity-ids-input');
6
+
7
+ /**
8
+ * Detaches entities from an integration. Entities that are not attached are
9
+ * ignored, and detached entities are not deleted. Every module the
10
+ * integration holds must keep at least one entity, so the integration can
11
+ * still hydrate each of its modules.
12
+ * @class RemoveEntitiesFromIntegration
13
+ */
14
+ class RemoveEntitiesFromIntegration {
15
+ /**
16
+ * @param {Object} params
17
+ * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository
18
+ * @param {import('../../modules/repositories/module-repository-interface').ModuleRepositoryInterface} params.moduleRepository
19
+ */
20
+ constructor({ integrationRepository, moduleRepository }) {
21
+ this.integrationRepository = integrationRepository;
22
+ this.moduleRepository = moduleRepository;
23
+ }
24
+
25
+ /**
26
+ * @param {string} integrationId
27
+ * @param {string[]} entityIds
28
+ * @returns {Promise<Object>} The updated integration record.
29
+ */
30
+ async execute(integrationId, entityIds) {
31
+ assertEntityIdsInput(integrationId, entityIds);
32
+
33
+ const integration = await loadIntegration(
34
+ this.integrationRepository,
35
+ integrationId
36
+ );
37
+
38
+ const removing = new Set(entityIds.map(String));
39
+ const attached = await this.moduleRepository.findEntitiesByIds(
40
+ integration.entitiesIds ?? []
41
+ );
42
+ const emptied = [...new Set(attached.map((e) => e.moduleName))].filter(
43
+ (moduleName) =>
44
+ !attached.some(
45
+ (e) =>
46
+ e.moduleName === moduleName &&
47
+ !removing.has(String(e.id))
48
+ )
49
+ );
50
+ if (emptied.length > 0) {
51
+ const error = new Error(
52
+ `Removing these entities would leave no entity for module(s): ${emptied.join(
53
+ ', '
54
+ )}`
55
+ );
56
+ error.code = 'LAST_ENTITY_OF_MODULE';
57
+ throw error;
58
+ }
59
+
60
+ const updated =
61
+ await this.integrationRepository.removeEntitiesFromIntegration(
62
+ integrationId,
63
+ entityIds
64
+ );
65
+ if (!updated) throw integrationNotFound(integrationId);
66
+ return updated;
67
+ }
68
+ }
69
+
70
+ module.exports = { RemoveEntitiesFromIntegration };
@@ -1,17 +1,3 @@
1
- const MAX_MESSAGES_PER_TYPE = 50;
2
-
3
- const isPlainObject = (value) =>
4
- value !== null && typeof value === 'object' && !Array.isArray(value);
5
-
6
- function toMessageItem(titleOrItem, messageBody, messageTimestamp) {
7
- if (isPlainObject(titleOrItem)) return { ...titleOrItem };
8
- return {
9
- title: titleOrItem,
10
- message: messageBody,
11
- timestamp: messageTimestamp,
12
- };
13
- }
14
-
15
1
  /**
16
2
  * Use case for updating messages associated with an integration.
17
3
  * @class UpdateIntegrationMessages
@@ -27,21 +13,19 @@ class UpdateIntegrationMessages {
27
13
  }
28
14
 
29
15
  /**
30
- * Executes the integration messages update. Pass the positional form
31
- * (title, body, timestamp) or one message item object; the keys of an item
32
- * object are stored as they are.
16
+ * Executes the integration messages update.
33
17
  * @async
34
18
  * @param {string} integrationId - ID of the integration to update.
35
19
  * @param {string} messageType - Type of message: 'errors', 'warnings', 'info', or 'logs'.
36
- * @param {string|Object} messageTitleOrItem - Title of the message, or the whole message item.
37
- * @param {string} [messageBody] - Body content of the message (positional form).
38
- * @param {string} [messageTimestamp] - Timestamp when the message was created (positional form).
20
+ * @param {string} messageTitle - Title of the message.
21
+ * @param {string} messageBody - Body content of the message.
22
+ * @param {string} messageTimestamp - Timestamp when the message was created.
39
23
  * @returns {Promise<Object>} The updated integration record.
40
24
  */
41
25
  async execute(
42
26
  integrationId,
43
27
  messageType,
44
- messageTitleOrItem,
28
+ messageTitle,
45
29
  messageBody,
46
30
  messageTimestamp
47
31
  ) {
@@ -49,15 +33,12 @@ class UpdateIntegrationMessages {
49
33
  await this.integrationRepository.updateIntegrationMessages(
50
34
  integrationId,
51
35
  messageType,
52
- toMessageItem(
53
- messageTitleOrItem,
54
- messageBody,
55
- messageTimestamp
56
- ),
57
- { keepLast: MAX_MESSAGES_PER_TYPE }
36
+ messageTitle,
37
+ messageBody,
38
+ messageTimestamp
58
39
  );
59
40
  return integration;
60
41
  }
61
42
  }
62
43
 
63
- module.exports = { MAX_MESSAGES_PER_TYPE, UpdateIntegrationMessages };
44
+ module.exports = { UpdateIntegrationMessages };
@@ -1,3 +1,4 @@
1
+ const Boom = require('@hapi/boom');
1
2
  const {
2
3
  mapIntegrationClassToIntegrationDTO,
3
4
  } = require('../utils/map-integration-dto');
@@ -27,16 +28,21 @@ class UpdateIntegration {
27
28
  * @param {string} userId - ID of the user requesting the update.
28
29
  * @param {Object} config - New configuration object for the integration.
29
30
  * @returns {Promise<Object>} The updated integration DTO.
30
- * @throws {Error} When integration is not found, doesn't belong to user, or integration class is not found.
31
+ * @throws {Boom.notFound} When integration is not found or doesn't belong to user.
32
+ * @throws {Error} When integration class is not found.
31
33
  */
32
34
  async execute(integrationId, userId, config) {
33
35
  // 1. Get integration record from repository
34
- const integrationRecord =
35
- await this.integrationRepository.findIntegrationById(integrationId);
36
+ const integrationRecord = await this.integrationRepository
37
+ .findIntegrationById(integrationId)
38
+ .catch((error) => {
39
+ if (error.message?.includes('not found')) return null;
40
+ throw error;
41
+ });
36
42
 
37
- if (!integrationRecord) {
38
- throw new Error(
39
- `No integration found by the ID of ${integrationId}`
43
+ if (!integrationRecord || integrationRecord.userId !== userId) {
44
+ throw Boom.notFound(
45
+ `Integration with id of ${integrationId} does not exist`
40
46
  );
41
47
  }
42
48
 
@@ -53,12 +59,6 @@ class UpdateIntegration {
53
59
  );
54
60
  }
55
61
 
56
- if (integrationRecord.userId !== userId) {
57
- throw new Error(
58
- `Integration ${integrationId} does not belong to User ${userId}`
59
- );
60
- }
61
-
62
62
  // 3. Load modules based on entity references
63
63
  const modules = [];
64
64
  for (const entityId of integrationRecord.entitiesIds) {