@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
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { MappingAlreadyExistsError } = require('../../errors');
2
3
  const {
3
4
  toObjectId,
4
5
  fromObjectId,
@@ -180,6 +181,55 @@ class IntegrationMappingRepositoryDocumentDB extends IntegrationMappingRepositor
180
181
  return this._mapMapping(decryptedMapping);
181
182
  }
182
183
 
184
+ async createMapping(integrationId, sourceId, mapping) {
185
+ const now = new Date();
186
+ const encryptedDocument = await this.encryptionService.encryptFields(
187
+ 'IntegrationMapping',
188
+ {
189
+ integrationId,
190
+ sourceId:
191
+ sourceId === null || sourceId === undefined
192
+ ? null
193
+ : String(sourceId),
194
+ mapping,
195
+ createdAt: now,
196
+ updatedAt: now,
197
+ }
198
+ );
199
+
200
+ let insertedId;
201
+ try {
202
+ insertedId = await insertOne(
203
+ this.prisma,
204
+ 'IntegrationMapping',
205
+ encryptedDocument
206
+ );
207
+ } catch (error) {
208
+ if (error.code === 11000) {
209
+ throw new MappingAlreadyExistsError(integrationId, sourceId, {
210
+ cause: error,
211
+ });
212
+ }
213
+ throw error;
214
+ }
215
+
216
+ const created = await findOne(this.prisma, 'IntegrationMapping', {
217
+ _id: insertedId,
218
+ });
219
+ if (!created) {
220
+ throw new Error(
221
+ 'Failed to create mapping: Document not found after insert. ' +
222
+ 'This indicates a database consistency issue.'
223
+ );
224
+ }
225
+ return this._mapMapping(
226
+ await this.encryptionService.decryptFields(
227
+ 'IntegrationMapping',
228
+ created
229
+ )
230
+ );
231
+ }
232
+
183
233
  async findMappingsByIntegration(integrationId) {
184
234
  const filter = {};
185
235
  if (integrationId) filter.integrationId = integrationId;
@@ -39,6 +39,21 @@ class IntegrationMappingRepositoryInterface {
39
39
  throw new Error('Method upsertMapping must be implemented by subclass');
40
40
  }
41
41
 
42
+ /**
43
+ * Insert a mapping, failing if one already exists for the
44
+ * (integrationId, sourceId) pair. Atomic: usable as a claim/lock row.
45
+ *
46
+ * @param {string|number} integrationId - The integration ID
47
+ * @param {string} sourceId - The source ID for lookup
48
+ * @param {Object} mapping - The mapping data
49
+ * @returns {Promise<Object>} The created mapping document
50
+ * @throws {MappingAlreadyExistsError} If the pair already exists
51
+ * @abstract
52
+ */
53
+ async createMapping(integrationId, sourceId, mapping) {
54
+ throw new Error('createMapping must be implemented by subclass');
55
+ }
56
+
42
57
  /**
43
58
  * Find all mappings for an integration
44
59
  *
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { MappingAlreadyExistsError } = require('../../errors');
2
3
  const {
3
4
  assertMappingWrittenUnencrypted,
4
5
  decryptQueriedMappings,
@@ -93,6 +94,34 @@ class IntegrationMappingRepositoryMongo extends IntegrationMappingRepositoryInte
93
94
  });
94
95
  }
95
96
 
97
+ /**
98
+ * Insert a mapping; fails if (integrationId, sourceId) already exists
99
+ *
100
+ * @param {string} integrationId - The integration ID
101
+ * @param {string} sourceId - The source ID
102
+ * @param {Object} mapping - The mapping data
103
+ * @returns {Promise<Object>} The created mapping document
104
+ * @throws {MappingAlreadyExistsError} If the pair already exists
105
+ */
106
+ async createMapping(integrationId, sourceId, mapping) {
107
+ try {
108
+ return await this.prisma.integrationMapping.create({
109
+ data: {
110
+ integrationId,
111
+ sourceId: this._toString(sourceId),
112
+ mapping,
113
+ },
114
+ });
115
+ } catch (error) {
116
+ if (error.code === 'P2002') {
117
+ throw new MappingAlreadyExistsError(integrationId, sourceId, {
118
+ cause: error,
119
+ });
120
+ }
121
+ throw error;
122
+ }
123
+ }
124
+
96
125
  /**
97
126
  * Find all mappings for an integration
98
127
  * Replaces: IntegrationMapping.find({ integration: integrationId })
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { MappingAlreadyExistsError } = require('../../errors');
2
3
  const {
3
4
  assertMappingWrittenUnencrypted,
4
5
  decryptQueriedMappings,
@@ -150,6 +151,35 @@ class IntegrationMappingRepositoryPostgres extends IntegrationMappingRepositoryI
150
151
  return this._convertMappingIds(result);
151
152
  }
152
153
 
154
+ /**
155
+ * Insert a mapping; fails if (integrationId, sourceId) already exists
156
+ *
157
+ * @param {string} integrationId - The integration ID
158
+ * @param {string} sourceId - The source ID
159
+ * @param {Object} mapping - The mapping data
160
+ * @returns {Promise<Object>} The created mapping document
161
+ * @throws {MappingAlreadyExistsError} If the pair already exists
162
+ */
163
+ async createMapping(integrationId, sourceId, mapping) {
164
+ try {
165
+ const created = await this.prisma.integrationMapping.create({
166
+ data: {
167
+ integrationId: this._stringToInt(integrationId),
168
+ sourceId: this._toString(sourceId),
169
+ mapping,
170
+ },
171
+ });
172
+ return this._convertMappingIds(created);
173
+ } catch (error) {
174
+ if (error.code === 'P2002') {
175
+ throw new MappingAlreadyExistsError(integrationId, sourceId, {
176
+ cause: error,
177
+ });
178
+ }
179
+ throw error;
180
+ }
181
+ }
182
+
153
183
  /**
154
184
  * Find all mappings for an integration
155
185
  * Replaces: IntegrationMapping.find({ integration: integrationId })
@@ -1,4 +1,5 @@
1
1
  const { prisma } = require('../../database/prisma');
2
+ const { MappingAlreadyExistsError } = require('../../errors');
2
3
  const {
3
4
  IntegrationMappingRepositoryInterface,
4
5
  } = require('./integration-mapping-repository-interface');
@@ -69,6 +70,34 @@ class IntegrationMappingRepository extends IntegrationMappingRepositoryInterface
69
70
  });
70
71
  }
71
72
 
73
+ /**
74
+ * Insert a mapping; fails if (integrationId, sourceId) already exists
75
+ *
76
+ * @param {string} integrationId - The integration ID
77
+ * @param {string} sourceId - The source ID
78
+ * @param {Object} mapping - The mapping data
79
+ * @returns {Promise<Object>} The created mapping document
80
+ * @throws {MappingAlreadyExistsError} If the pair already exists
81
+ */
82
+ async createMapping(integrationId, sourceId, mapping) {
83
+ try {
84
+ return await this.prisma.integrationMapping.create({
85
+ data: {
86
+ integrationId,
87
+ sourceId,
88
+ mapping,
89
+ },
90
+ });
91
+ } catch (error) {
92
+ if (error.code === 'P2002') {
93
+ throw new MappingAlreadyExistsError(integrationId, sourceId, {
94
+ cause: error,
95
+ });
96
+ }
97
+ throw error;
98
+ }
99
+ }
100
+
72
101
  /**
73
102
  * Find all mappings for an integration
74
103
  * Replaces: IntegrationMapping.find({ integration: integrationId })
@@ -14,7 +14,6 @@ const {
14
14
  IntegrationRepositoryInterface,
15
15
  } = require('./integration-repository-interface');
16
16
  const { validateConfigPatch } = require('./config-patch-shared');
17
- const { messagesOfType } = require('./message-item-shared');
18
17
 
19
18
  class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
20
19
  constructor() {
@@ -95,8 +94,9 @@ class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
95
94
  async updateIntegrationMessages(
96
95
  integrationId,
97
96
  messageType,
98
- item,
99
- { keepLast }
97
+ messageTitle,
98
+ messageBody,
99
+ messageTimestamp
100
100
  ) {
101
101
  const objectId = toObjectId(integrationId);
102
102
  if (!objectId) {
@@ -107,12 +107,13 @@ class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
107
107
  throw new Error(`Integration ${integrationId} not found`);
108
108
  }
109
109
  const messages = this._extractMessages(existing);
110
- const list = [...messagesOfType(messages, messageType)];
111
- list.push({ ...item, title: item.title ?? null });
112
- const updatedMessages = {
113
- ...messages,
114
- [messageType]: list.slice(-keepLast),
115
- };
110
+ const list = Array.isArray(messages[messageType]) ? [...messages[messageType]] : [];
111
+ list.push({
112
+ title: messageTitle ?? null,
113
+ message: messageBody,
114
+ timestamp: messageTimestamp,
115
+ });
116
+ const updatedMessages = { ...messages, [messageType]: list };
116
117
  await updateOne(
117
118
  this.prisma,
118
119
  'Integration',
@@ -131,20 +132,6 @@ class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
131
132
  return true;
132
133
  }
133
134
 
134
- async findIntegrationMessages(integrationId, messageType) {
135
- const objectId = toObjectId(integrationId);
136
- if (!objectId) {
137
- throw new Error(`Integration ${integrationId} not found`);
138
- }
139
- const existing = await findOne(this.prisma, 'Integration', {
140
- _id: objectId,
141
- });
142
- if (!existing) {
143
- throw new Error(`Integration ${integrationId} not found`);
144
- }
145
- return messagesOfType(this._extractMessages(existing), messageType);
146
- }
147
-
148
135
  async createIntegration(entities, userId, config) {
149
136
  const now = new Date();
150
137
  const document = {
@@ -177,6 +164,38 @@ class IntegrationRepositoryDocumentDB extends IntegrationRepositoryInterface {
177
164
  return this._mapIntegration(created);
178
165
  }
179
166
 
167
+ async addEntitiesToIntegration(integrationId, entityIds) {
168
+ const objectId = toObjectId(integrationId);
169
+ if (!objectId) return null;
170
+ const result = await updateOne(
171
+ this.prisma,
172
+ 'Integration',
173
+ { _id: objectId },
174
+ {
175
+ $addToSet: { entityIds: { $each: toObjectIdArray(entityIds) } },
176
+ $set: { updatedAt: { $date: new Date().toISOString() } },
177
+ }
178
+ );
179
+ if (!result?.n) return null;
180
+ return this.findIntegrationById(integrationId);
181
+ }
182
+
183
+ async removeEntitiesFromIntegration(integrationId, entityIds) {
184
+ const objectId = toObjectId(integrationId);
185
+ if (!objectId) return null;
186
+ const result = await updateOne(
187
+ this.prisma,
188
+ 'Integration',
189
+ { _id: objectId },
190
+ {
191
+ $pullAll: { entityIds: toObjectIdArray(entityIds) },
192
+ $set: { updatedAt: { $date: new Date().toISOString() } },
193
+ }
194
+ );
195
+ if (!result?.n) return null;
196
+ return this.findIntegrationById(integrationId);
197
+ }
198
+
180
199
  async findIntegrationByUserId(userId) {
181
200
  const objectId = toObjectId(userId);
182
201
  if (!objectId) return null;
@@ -97,40 +97,26 @@ class IntegrationRepositoryInterface {
97
97
  }
98
98
 
99
99
  /**
100
- * Append a message item to the stored messages of one type
100
+ * Update integration messages
101
101
  *
102
102
  * @param {string|number} integrationId - Integration ID
103
103
  * @param {string} messageType - Type of message (errors, warnings, info, logs)
104
- * @param {Object} item - Message item, stored as it is
105
- * @param {Object} options
106
- * @param {number} options.keepLast - How many of the newest items of the type to keep
104
+ * @param {string} messageTitle - Message title
105
+ * @param {string} messageBody - Message body
106
+ * @param {Date} messageTimestamp - Message timestamp
107
107
  * @returns {Promise<boolean>} Success indicator
108
108
  * @abstract
109
109
  */
110
110
  async updateIntegrationMessages(
111
111
  integrationId,
112
112
  messageType,
113
- item,
114
- { keepLast }
113
+ messageTitle,
114
+ messageBody,
115
+ messageTimestamp
115
116
  ) {
116
117
  throw new Error('Method updateIntegrationMessages must be implemented by subclass');
117
118
  }
118
119
 
119
- /**
120
- * Find the stored messages of one type. Reads the stored items, not the
121
- * `messages` of an integration record, which some adapters do not fill.
122
- *
123
- * @param {string|number} integrationId - Integration ID
124
- * @param {string} messageType - Type of message (errors, warnings, info, logs)
125
- * @returns {Promise<Array>} The stored message items of that type, oldest first
126
- * @abstract
127
- */
128
- async findIntegrationMessages(integrationId, messageType) {
129
- throw new Error(
130
- 'Method findIntegrationMessages must be implemented by subclass'
131
- );
132
- }
133
-
134
120
  /**
135
121
  * Create a new integration
136
122
  *
@@ -198,6 +184,36 @@ class IntegrationRepositoryInterface {
198
184
  'Method findIntegrationsByEntityId must be implemented by subclass'
199
185
  );
200
186
  }
187
+
188
+ /**
189
+ * Attach entities to an existing integration. Entities that are already
190
+ * attached are left as they are.
191
+ *
192
+ * @param {string|number} integrationId - Integration ID
193
+ * @param {Array<string|number>} entityIds - Entity IDs to attach
194
+ * @returns {Promise<Object|null>} Updated integration, or null when the integration does not exist
195
+ * @abstract
196
+ */
197
+ async addEntitiesToIntegration(integrationId, entityIds) {
198
+ throw new Error(
199
+ 'Method addEntitiesToIntegration must be implemented by subclass'
200
+ );
201
+ }
202
+
203
+ /**
204
+ * Detach entities from an integration. Entities that are not attached
205
+ * are ignored; the entities themselves are not deleted.
206
+ *
207
+ * @param {string|number} integrationId - Integration ID
208
+ * @param {Array<string|number>} entityIds - Entity IDs to detach
209
+ * @returns {Promise<Object|null>} Updated integration, or null when the integration does not exist
210
+ * @abstract
211
+ */
212
+ async removeEntitiesFromIntegration(integrationId, entityIds) {
213
+ throw new Error(
214
+ 'Method removeEntitiesFromIntegration must be implemented by subclass'
215
+ );
216
+ }
201
217
  }
202
218
 
203
219
  module.exports = { IntegrationRepositoryInterface };
@@ -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
 
8
7
  /**
9
8
  * MongoDB Integration Repository Adapter
@@ -230,16 +229,17 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
230
229
  *
231
230
  * @param {string} integrationId - Integration ID
232
231
  * @param {string} messageType - Type of message (errors, warnings, info, logs)
233
- * @param {Object} item - Message item, stored as it is
234
- * @param {Object} options
235
- * @param {number} options.keepLast - How many of the newest items of the type to keep
232
+ * @param {string} messageTitle - Message title
233
+ * @param {string} messageBody - Message body
234
+ * @param {Date} messageTimestamp - Message timestamp
236
235
  * @returns {Promise<boolean>} Success indicator
237
236
  */
238
237
  async updateIntegrationMessages(
239
238
  integrationId,
240
239
  messageType,
241
- item,
242
- { keepLast }
240
+ messageTitle,
241
+ messageBody,
242
+ messageTimestamp
243
243
  ) {
244
244
  // Get current integration
245
245
  const integration = await this.prisma.integration.findUnique({
@@ -251,42 +251,29 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
251
251
  }
252
252
 
253
253
  // Parse existing messages (JSON field)
254
- const messageArray = messagesOfType(integration, messageType);
254
+ const messages = integration.messages || {};
255
+ const messageArray = Array.isArray(messages[messageType])
256
+ ? messages[messageType]
257
+ : [];
255
258
 
256
259
  // Add new message
257
- messageArray.push(item);
260
+ messageArray.push({
261
+ title: messageTitle,
262
+ message: messageBody,
263
+ timestamp: messageTimestamp,
264
+ });
258
265
 
259
266
  // Update messages
260
267
  await this.prisma.integration.update({
261
268
  where: { id: integrationId },
262
269
  data: {
263
- [messageType]: messageArray.slice(-keepLast),
270
+ [messageType]: messageArray,
264
271
  },
265
272
  });
266
273
 
267
274
  return true; // Mongoose compatibility
268
275
  }
269
276
 
270
- /**
271
- * Find the stored messages of one type
272
- *
273
- * @param {string} integrationId - Integration ID
274
- * @param {string} messageType - Type of message (errors, warnings, info, logs)
275
- * @returns {Promise<Array>} The stored message items of that type, oldest first
276
- */
277
- async findIntegrationMessages(integrationId, messageType) {
278
- const integration = await this.prisma.integration.findUnique({
279
- where: { id: integrationId },
280
- select: { [messageType]: true },
281
- });
282
-
283
- if (!integration) {
284
- throw new Error(`Integration ${integrationId} not found`);
285
- }
286
-
287
- return messagesOfType(integration, messageType);
288
- }
289
-
290
277
  /**
291
278
  * Find all integrations whose entity set includes the given entity ID.
292
279
  *
@@ -351,6 +338,58 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
351
338
  };
352
339
  }
353
340
 
341
+ /**
342
+ * Attach entities to an existing integration. Entities already attached
343
+ * are left as they are.
344
+ *
345
+ * @param {string} integrationId - Integration ID
346
+ * @param {Array<string>} entityIds - Entity IDs to attach
347
+ * @returns {Promise<Object|null>} Updated integration, or null when the integration does not exist
348
+ */
349
+ async addEntitiesToIntegration(integrationId, entityIds) {
350
+
351
+ try {
352
+ await this.prisma.integration.update({
353
+ where: { id: integrationId },
354
+ data: {
355
+ entities: {
356
+ connect: entityIds.map((id) => ({ id })),
357
+ },
358
+ },
359
+ });
360
+ } catch (error) {
361
+ if (error.code === 'P2025') return null;
362
+ throw error;
363
+ }
364
+ return this.findIntegrationById(integrationId);
365
+ }
366
+
367
+ /**
368
+ * Detach entities from an integration. Entities that are not attached
369
+ * are ignored. The entities themselves are not deleted.
370
+ *
371
+ * @param {string} integrationId - Integration ID
372
+ * @param {Array<string>} entityIds - Entity IDs to detach
373
+ * @returns {Promise<Object|null>} Updated integration, or null when the integration does not exist
374
+ */
375
+ async removeEntitiesFromIntegration(integrationId, entityIds) {
376
+
377
+ try {
378
+ await this.prisma.integration.update({
379
+ where: { id: integrationId },
380
+ data: {
381
+ entities: {
382
+ disconnect: entityIds.map((id) => ({ id })),
383
+ },
384
+ },
385
+ });
386
+ } catch (error) {
387
+ if (error.code === 'P2025') return null;
388
+ throw error;
389
+ }
390
+ return this.findIntegrationById(integrationId);
391
+ }
392
+
354
393
  /**
355
394
  * Find integration by user ID (returns single integration)
356
395
  * Replaces: IntegrationModel.findOne({ user: userId }).populate('entities')
@@ -432,7 +471,7 @@ class IntegrationRepositoryMongo extends IntegrationRepositoryInterface {
432
471
  for (const [key, value] of Object.entries(patch)) {
433
472
  $set[`config.${key}`] = value;
434
473
  }
435
- $set.updatedAt = new Date();
474
+ $set.updatedAt = { $date: new Date().toISOString() };
436
475
 
437
476
  const result = await this.prisma.$runCommandRaw({
438
477
  findAndModify: 'Integration',