@friggframework/core 2.0.0-next.40 → 2.0.0-next.42

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 (196) hide show
  1. package/CLAUDE.md +693 -0
  2. package/README.md +931 -50
  3. package/application/commands/README.md +421 -0
  4. package/application/commands/credential-commands.js +224 -0
  5. package/application/commands/entity-commands.js +315 -0
  6. package/application/commands/integration-commands.js +160 -0
  7. package/application/commands/integration-commands.test.js +123 -0
  8. package/application/commands/user-commands.js +213 -0
  9. package/application/index.js +69 -0
  10. package/core/CLAUDE.md +690 -0
  11. package/core/create-handler.js +0 -6
  12. package/credential/repositories/credential-repository-factory.js +47 -0
  13. package/credential/repositories/credential-repository-interface.js +98 -0
  14. package/credential/repositories/credential-repository-mongo.js +301 -0
  15. package/credential/repositories/credential-repository-postgres.js +307 -0
  16. package/credential/repositories/credential-repository.js +307 -0
  17. package/credential/use-cases/get-credential-for-user.js +21 -0
  18. package/credential/use-cases/update-authentication-status.js +15 -0
  19. package/database/config.js +117 -0
  20. package/database/encryption/README.md +683 -0
  21. package/database/encryption/encryption-integration.test.js +553 -0
  22. package/database/encryption/encryption-schema-registry.js +141 -0
  23. package/database/encryption/encryption-schema-registry.test.js +392 -0
  24. package/database/encryption/field-encryption-service.js +226 -0
  25. package/database/encryption/field-encryption-service.test.js +525 -0
  26. package/database/encryption/logger.js +79 -0
  27. package/database/encryption/mongo-decryption-fix-verification.test.js +348 -0
  28. package/database/encryption/postgres-decryption-fix-verification.test.js +371 -0
  29. package/database/encryption/postgres-relation-decryption.test.js +245 -0
  30. package/database/encryption/prisma-encryption-extension.js +222 -0
  31. package/database/encryption/prisma-encryption-extension.test.js +439 -0
  32. package/database/index.js +25 -12
  33. package/database/models/readme.md +1 -0
  34. package/database/prisma.js +162 -0
  35. package/database/repositories/health-check-repository-factory.js +38 -0
  36. package/database/repositories/health-check-repository-interface.js +86 -0
  37. package/database/repositories/health-check-repository-mongodb.js +72 -0
  38. package/database/repositories/health-check-repository-postgres.js +75 -0
  39. package/database/repositories/health-check-repository.js +108 -0
  40. package/database/use-cases/check-database-health-use-case.js +34 -0
  41. package/database/use-cases/check-encryption-health-use-case.js +82 -0
  42. package/database/use-cases/test-encryption-use-case.js +252 -0
  43. package/encrypt/Cryptor.js +20 -152
  44. package/encrypt/index.js +1 -2
  45. package/encrypt/test-encrypt.js +0 -2
  46. package/handlers/app-definition-loader.js +38 -0
  47. package/handlers/app-handler-helpers.js +0 -3
  48. package/handlers/auth-flow.integration.test.js +147 -0
  49. package/handlers/backend-utils.js +25 -45
  50. package/handlers/integration-event-dispatcher.js +54 -0
  51. package/handlers/integration-event-dispatcher.test.js +141 -0
  52. package/handlers/routers/HEALTHCHECK.md +103 -1
  53. package/handlers/routers/auth.js +3 -14
  54. package/handlers/routers/health.js +63 -424
  55. package/handlers/routers/health.test.js +7 -0
  56. package/handlers/routers/integration-defined-routers.js +8 -5
  57. package/handlers/routers/user.js +25 -5
  58. package/handlers/routers/websocket.js +5 -3
  59. package/handlers/use-cases/check-external-apis-health-use-case.js +81 -0
  60. package/handlers/use-cases/check-integrations-health-use-case.js +32 -0
  61. package/handlers/workers/integration-defined-workers.js +6 -3
  62. package/index.js +45 -22
  63. package/integrations/index.js +12 -10
  64. package/integrations/integration-base.js +224 -53
  65. package/integrations/integration-router.js +386 -178
  66. package/integrations/options.js +1 -1
  67. package/integrations/repositories/integration-mapping-repository-factory.js +50 -0
  68. package/integrations/repositories/integration-mapping-repository-interface.js +106 -0
  69. package/integrations/repositories/integration-mapping-repository-mongo.js +161 -0
  70. package/integrations/repositories/integration-mapping-repository-postgres.js +227 -0
  71. package/integrations/repositories/integration-mapping-repository.js +156 -0
  72. package/integrations/repositories/integration-repository-factory.js +44 -0
  73. package/integrations/repositories/integration-repository-interface.js +115 -0
  74. package/integrations/repositories/integration-repository-mongo.js +271 -0
  75. package/integrations/repositories/integration-repository-postgres.js +319 -0
  76. package/integrations/tests/doubles/dummy-integration-class.js +90 -0
  77. package/integrations/tests/doubles/test-integration-repository.js +99 -0
  78. package/integrations/tests/use-cases/create-integration.test.js +131 -0
  79. package/integrations/tests/use-cases/delete-integration-for-user.test.js +150 -0
  80. package/integrations/tests/use-cases/find-integration-context-by-external-entity-id.test.js +92 -0
  81. package/integrations/tests/use-cases/get-integration-for-user.test.js +150 -0
  82. package/integrations/tests/use-cases/get-integration-instance.test.js +176 -0
  83. package/integrations/tests/use-cases/get-integrations-for-user.test.js +176 -0
  84. package/integrations/tests/use-cases/get-possible-integrations.test.js +188 -0
  85. package/integrations/tests/use-cases/update-integration-messages.test.js +142 -0
  86. package/integrations/tests/use-cases/update-integration-status.test.js +103 -0
  87. package/integrations/tests/use-cases/update-integration.test.js +141 -0
  88. package/integrations/use-cases/create-integration.js +83 -0
  89. package/integrations/use-cases/delete-integration-for-user.js +73 -0
  90. package/integrations/use-cases/find-integration-context-by-external-entity-id.js +72 -0
  91. package/integrations/use-cases/get-integration-for-user.js +78 -0
  92. package/integrations/use-cases/get-integration-instance-by-definition.js +67 -0
  93. package/integrations/use-cases/get-integration-instance.js +83 -0
  94. package/integrations/use-cases/get-integrations-for-user.js +87 -0
  95. package/integrations/use-cases/get-possible-integrations.js +27 -0
  96. package/integrations/use-cases/index.js +11 -0
  97. package/integrations/use-cases/load-integration-context-full.test.js +329 -0
  98. package/integrations/use-cases/load-integration-context.js +71 -0
  99. package/integrations/use-cases/load-integration-context.test.js +114 -0
  100. package/integrations/use-cases/update-integration-messages.js +44 -0
  101. package/integrations/use-cases/update-integration-status.js +32 -0
  102. package/integrations/use-cases/update-integration.js +93 -0
  103. package/integrations/utils/map-integration-dto.js +36 -0
  104. package/jest-global-setup-noop.js +3 -0
  105. package/jest-global-teardown-noop.js +3 -0
  106. package/{module-plugin → modules}/entity.js +1 -0
  107. package/{module-plugin → modules}/index.js +0 -8
  108. package/modules/module-factory.js +56 -0
  109. package/modules/module-hydration.test.js +205 -0
  110. package/modules/module.js +221 -0
  111. package/modules/repositories/module-repository-factory.js +33 -0
  112. package/modules/repositories/module-repository-interface.js +129 -0
  113. package/modules/repositories/module-repository-mongo.js +386 -0
  114. package/modules/repositories/module-repository-postgres.js +437 -0
  115. package/modules/repositories/module-repository.js +327 -0
  116. package/{module-plugin → modules}/test/mock-api/api.js +8 -3
  117. package/{module-plugin → modules}/test/mock-api/definition.js +12 -8
  118. package/modules/tests/doubles/test-module-factory.js +16 -0
  119. package/modules/tests/doubles/test-module-repository.js +39 -0
  120. package/modules/use-cases/get-entities-for-user.js +32 -0
  121. package/modules/use-cases/get-entity-options-by-id.js +59 -0
  122. package/modules/use-cases/get-entity-options-by-type.js +34 -0
  123. package/modules/use-cases/get-module-instance-from-type.js +31 -0
  124. package/modules/use-cases/get-module.js +56 -0
  125. package/modules/use-cases/process-authorization-callback.js +121 -0
  126. package/modules/use-cases/refresh-entity-options.js +59 -0
  127. package/modules/use-cases/test-module-auth.js +55 -0
  128. package/modules/utils/map-module-dto.js +18 -0
  129. package/package.json +14 -6
  130. package/prisma-mongodb/schema.prisma +321 -0
  131. package/prisma-postgresql/migrations/20250930193005_init/migration.sql +315 -0
  132. package/prisma-postgresql/migrations/20251006135218_init/migration.sql +9 -0
  133. package/prisma-postgresql/migrations/migration_lock.toml +3 -0
  134. package/prisma-postgresql/schema.prisma +303 -0
  135. package/syncs/manager.js +468 -443
  136. package/syncs/repositories/sync-repository-factory.js +38 -0
  137. package/syncs/repositories/sync-repository-interface.js +109 -0
  138. package/syncs/repositories/sync-repository-mongo.js +239 -0
  139. package/syncs/repositories/sync-repository-postgres.js +319 -0
  140. package/syncs/sync.js +0 -1
  141. package/token/repositories/token-repository-factory.js +33 -0
  142. package/token/repositories/token-repository-interface.js +131 -0
  143. package/token/repositories/token-repository-mongo.js +212 -0
  144. package/token/repositories/token-repository-postgres.js +257 -0
  145. package/token/repositories/token-repository.js +219 -0
  146. package/types/integrations/index.d.ts +2 -6
  147. package/types/module-plugin/index.d.ts +5 -57
  148. package/types/syncs/index.d.ts +0 -2
  149. package/user/repositories/user-repository-factory.js +46 -0
  150. package/user/repositories/user-repository-interface.js +198 -0
  151. package/user/repositories/user-repository-mongo.js +250 -0
  152. package/user/repositories/user-repository-postgres.js +311 -0
  153. package/user/tests/doubles/test-user-repository.js +72 -0
  154. package/user/tests/use-cases/create-individual-user.test.js +24 -0
  155. package/user/tests/use-cases/create-organization-user.test.js +28 -0
  156. package/user/tests/use-cases/create-token-for-user-id.test.js +19 -0
  157. package/user/tests/use-cases/get-user-from-bearer-token.test.js +64 -0
  158. package/user/tests/use-cases/login-user.test.js +140 -0
  159. package/user/use-cases/create-individual-user.js +61 -0
  160. package/user/use-cases/create-organization-user.js +47 -0
  161. package/user/use-cases/create-token-for-user-id.js +30 -0
  162. package/user/use-cases/get-user-from-bearer-token.js +77 -0
  163. package/user/use-cases/login-user.js +122 -0
  164. package/user/user.js +77 -0
  165. package/websocket/repositories/websocket-connection-repository-factory.js +37 -0
  166. package/websocket/repositories/websocket-connection-repository-interface.js +106 -0
  167. package/websocket/repositories/websocket-connection-repository-mongo.js +155 -0
  168. package/websocket/repositories/websocket-connection-repository-postgres.js +195 -0
  169. package/websocket/repositories/websocket-connection-repository.js +160 -0
  170. package/database/models/State.js +0 -9
  171. package/database/models/Token.js +0 -70
  172. package/database/mongo.js +0 -171
  173. package/encrypt/Cryptor.test.js +0 -32
  174. package/encrypt/encrypt.js +0 -104
  175. package/encrypt/encrypt.test.js +0 -1069
  176. package/handlers/routers/middleware/loadUser.js +0 -15
  177. package/handlers/routers/middleware/requireLoggedInUser.js +0 -12
  178. package/integrations/create-frigg-backend.js +0 -31
  179. package/integrations/integration-factory.js +0 -251
  180. package/integrations/integration-mapping.js +0 -43
  181. package/integrations/integration-model.js +0 -46
  182. package/integrations/integration-user.js +0 -144
  183. package/integrations/test/integration-base.test.js +0 -144
  184. package/module-plugin/auther.js +0 -393
  185. package/module-plugin/credential.js +0 -22
  186. package/module-plugin/entity-manager.js +0 -70
  187. package/module-plugin/manager.js +0 -169
  188. package/module-plugin/module-factory.js +0 -61
  189. package/module-plugin/test/auther.test.js +0 -97
  190. /package/{module-plugin → modules}/ModuleConstants.js +0 -0
  191. /package/{module-plugin → modules}/requester/api-key.js +0 -0
  192. /package/{module-plugin → modules}/requester/basic.js +0 -0
  193. /package/{module-plugin → modules}/requester/oauth-2.js +0 -0
  194. /package/{module-plugin → modules}/requester/requester.js +0 -0
  195. /package/{module-plugin → modules}/requester/requester.test.js +0 -0
  196. /package/{module-plugin → modules}/test/mock-api/mocks/hubspot.js +0 -0
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Use case for retrieving all possible integration types that can be created.
3
+ * @class GetPossibleIntegrations
4
+ */
5
+ class GetPossibleIntegrations {
6
+ /**
7
+ * Creates a new GetPossibleIntegrations instance.
8
+ * @param {Object} params - Configuration parameters.
9
+ * @param {Array<import('../integration').Integration>} params.integrationClasses - Array of available integration classes.
10
+ */
11
+ constructor({ integrationClasses }) {
12
+ this.integrationClasses = integrationClasses;
13
+ }
14
+
15
+ /**
16
+ * Executes the retrieval of all possible integration types.
17
+ * @async
18
+ * @returns {Promise<Object[]>} Array of integration option details for all available integration types.
19
+ */
20
+ async execute() {
21
+ return this.integrationClasses.map((integrationClass) =>
22
+ integrationClass.getOptionDetails()
23
+ );
24
+ }
25
+ }
26
+
27
+ module.exports = { GetPossibleIntegrations };
@@ -0,0 +1,11 @@
1
+ const { GetIntegrationsForUser } = require('./get-integrations-for-user');
2
+ const { DeleteIntegrationForUser } = require('./delete-integration-for-user');
3
+ const { CreateIntegration } = require('./create-integration');
4
+ const { GetIntegration } = require('./get-integration');
5
+
6
+ module.exports = {
7
+ GetIntegrationsForUser,
8
+ DeleteIntegrationForUser,
9
+ CreateIntegration,
10
+ GetIntegration,
11
+ };
@@ -0,0 +1,329 @@
1
+ jest.mock('../../database/config', () => ({
2
+ DB_TYPE: 'mongodb',
3
+ getDatabaseType: jest.fn(() => 'mongodb'),
4
+ PRISMA_LOG_LEVEL: 'error,warn',
5
+ PRISMA_QUERY_LOGGING: false,
6
+ }));
7
+
8
+ const { LoadIntegrationContextUseCase } = require('./load-integration-context');
9
+ const { IntegrationBase } = require('../integration-base');
10
+ const { createIntegrationRepository } = require('../repositories/integration-repository-factory');
11
+ const { Module } = require('../../modules/module');
12
+ const { ModuleFactory } = require('../../modules/module-factory');
13
+ const { ModuleRepository } = require('../../modules/repositories/module-repository');
14
+
15
+ // Mock OAuth2 API class that extends requester pattern
16
+ class MockAsanaApi {
17
+ constructor(params) {
18
+ // Capture all injected params
19
+ this.client_id = params.client_id;
20
+ this.client_secret = params.client_secret;
21
+ this.redirect_uri = params.redirect_uri;
22
+ this.scope = params.scope;
23
+ this.access_token = params.access_token;
24
+ this.refresh_token = params.refresh_token;
25
+ this.delegate = params.delegate;
26
+ }
27
+
28
+ async getFolders() {
29
+ if (!this.access_token) {
30
+ throw new Error('No access token');
31
+ }
32
+ return {
33
+ folders: ['Marketing', 'Development', 'Design'],
34
+ usedToken: this.access_token
35
+ };
36
+ }
37
+
38
+ async listProjects() {
39
+ return {
40
+ projects: ['Q1 Launch', 'Website Redesign'],
41
+ clientId: this.client_id
42
+ };
43
+ }
44
+
45
+ getAuthorizationRequirements() {
46
+ return { type: 'oauth2', url: this.redirect_uri };
47
+ }
48
+ }
49
+
50
+ MockAsanaApi.requesterType = 'oauth2';
51
+
52
+ class MockFrontifyApi {
53
+ constructor(params) {
54
+ this.client_id = params.client_id;
55
+ this.client_secret = params.client_secret;
56
+ this.redirect_uri = params.redirect_uri;
57
+ this.scope = params.scope;
58
+ this.access_token = params.access_token;
59
+ this.refresh_token = params.refresh_token;
60
+ this.domain = params.domain;
61
+ }
62
+
63
+ async listBrands() {
64
+ return {
65
+ brands: ['Main Brand', 'Sub Brand'],
66
+ domain: this.domain,
67
+ token: this.access_token
68
+ };
69
+ }
70
+
71
+ async searchAssets(query) {
72
+ return {
73
+ query,
74
+ assets: ['logo.svg', 'guidelines.pdf'],
75
+ clientSecret: this.client_secret ? 'hidden' : null
76
+ };
77
+ }
78
+
79
+ getAuthorizationRequirements() {
80
+ return { type: 'oauth2', url: this.redirect_uri };
81
+ }
82
+ }
83
+
84
+ MockFrontifyApi.requesterType = 'oauth2';
85
+
86
+ // Module definitions with env variables
87
+ const asanaDefinition = {
88
+ moduleName: 'asana',
89
+ modelName: 'Asana',
90
+ API: MockAsanaApi,
91
+ requiredAuthMethods: {
92
+ getToken: async () => {},
93
+ getEntityDetails: async () => {},
94
+ getCredentialDetails: async () => {},
95
+ apiPropertiesToPersist: {
96
+ credential: ['access_token', 'refresh_token'],
97
+ entity: [],
98
+ },
99
+ testAuthRequest: async () => true,
100
+ },
101
+ env: {
102
+ client_id: 'ASANA_CLIENT_ID_FROM_ENV',
103
+ client_secret: 'ASANA_SECRET_FROM_ENV',
104
+ redirect_uri: 'https://app.example.com/auth/asana',
105
+ scope: 'default',
106
+ },
107
+ };
108
+
109
+ const frontifyDefinition = {
110
+ moduleName: 'frontify',
111
+ modelName: 'Frontify',
112
+ API: MockFrontifyApi,
113
+ requiredAuthMethods: {
114
+ getToken: async () => {},
115
+ getEntityDetails: async () => {},
116
+ getCredentialDetails: async () => {},
117
+ apiPropertiesToPersist: {
118
+ credential: ['access_token', 'refresh_token'],
119
+ entity: ['domain'],
120
+ },
121
+ testAuthRequest: async () => true,
122
+ },
123
+ env: {
124
+ client_id: 'FRONTIFY_CLIENT_ID_FROM_ENV',
125
+ client_secret: 'FRONTIFY_SECRET_FROM_ENV',
126
+ redirect_uri: 'https://app.example.com/auth/frontify',
127
+ scope: 'read write',
128
+ },
129
+ };
130
+
131
+ // Integration class similar to AsanaIntegration
132
+ class TestIntegration extends IntegrationBase {
133
+ static Definition = {
134
+ name: 'test-integration',
135
+ version: '1.0.0',
136
+ modules: {
137
+ asana: {
138
+ definition: asanaDefinition,
139
+ },
140
+ frontify: {
141
+ definition: frontifyDefinition,
142
+ },
143
+ },
144
+ };
145
+
146
+ async performBusinessLogic() {
147
+ // After hydration, this method can use API modules
148
+ const folders = await this.asana.api.getFolders();
149
+ const brands = await this.frontify.api.listBrands();
150
+ return { folders, brands };
151
+ }
152
+ }
153
+
154
+ describe('LoadIntegrationContextUseCase - Full Rounded Test', () => {
155
+ it('should load integration with working API modules that have env vars and credentials', async () => {
156
+ // Setup: Create entities with credentials (simulating DB records)
157
+ const entities = [
158
+ {
159
+ id: 'entity-asana-123',
160
+ moduleName: 'asana',
161
+ userId: 'user-789',
162
+ credential: {
163
+ data: {
164
+ access_token: 'asana_access_token_xyz',
165
+ refresh_token: 'asana_refresh_token_abc',
166
+ },
167
+ },
168
+ },
169
+ {
170
+ id: 'entity-frontify-456',
171
+ moduleName: 'frontify',
172
+ userId: 'user-789',
173
+ domain: 'customer.frontify.com',
174
+ credential: {
175
+ data: {
176
+ access_token: 'frontify_access_token_uvw',
177
+ refresh_token: 'frontify_refresh_token_def',
178
+ },
179
+ },
180
+ },
181
+ ];
182
+
183
+ // Mock repositories
184
+ const moduleRepository = {
185
+ findEntitiesByIds: jest.fn().mockResolvedValue(entities),
186
+ findEntityById: jest.fn().mockImplementation((id) =>
187
+ Promise.resolve(entities.find(e => e.id === id))
188
+ ),
189
+ };
190
+
191
+ // Create module factory with definitions
192
+ const moduleFactory = new ModuleFactory({
193
+ moduleRepository,
194
+ moduleDefinitions: [asanaDefinition, frontifyDefinition],
195
+ });
196
+
197
+ // Create the use case
198
+ const useCase = new LoadIntegrationContextUseCase({
199
+ integrationRepository: createIntegrationRepository(),
200
+ moduleRepository,
201
+ moduleFactory,
202
+ });
203
+
204
+ // Execute: Load integration context
205
+ const integrationRecord = {
206
+ id: 'integration-999',
207
+ userId: 'user-789',
208
+ entitiesIds: ['entity-asana-123', 'entity-frontify-456'],
209
+ status: 'active',
210
+ config: { someConfig: true },
211
+ };
212
+
213
+ const context = await useCase.execute({ integrationRecord });
214
+
215
+ // Verify: Context has modules
216
+ expect(context.modules).toHaveLength(2);
217
+
218
+ // Create integration instance and hydrate it
219
+ const integration = new TestIntegration();
220
+ integration.setIntegrationRecord(context);
221
+
222
+ // Verify: Integration has modules attached
223
+ expect(integration.asana).toBeDefined();
224
+ expect(integration.frontify).toBeDefined();
225
+ expect(integration.modules.asana).toBe(integration.asana);
226
+ expect(integration.modules.frontify).toBe(integration.frontify);
227
+
228
+ // CRITICAL TEST: Verify API instances have env vars from definition
229
+ expect(integration.asana.api.client_id).toBe('ASANA_CLIENT_ID_FROM_ENV');
230
+ expect(integration.asana.api.client_secret).toBe('ASANA_SECRET_FROM_ENV');
231
+ expect(integration.asana.api.redirect_uri).toBe('https://app.example.com/auth/asana');
232
+ expect(integration.asana.api.scope).toBe('default');
233
+
234
+ expect(integration.frontify.api.client_id).toBe('FRONTIFY_CLIENT_ID_FROM_ENV');
235
+ expect(integration.frontify.api.client_secret).toBe('FRONTIFY_SECRET_FROM_ENV');
236
+ expect(integration.frontify.api.redirect_uri).toBe('https://app.example.com/auth/frontify');
237
+ expect(integration.frontify.api.scope).toBe('read write');
238
+
239
+ // CRITICAL TEST: Verify API instances have credentials from entities
240
+ expect(integration.asana.api.access_token).toBe('asana_access_token_xyz');
241
+ expect(integration.asana.api.refresh_token).toBe('asana_refresh_token_abc');
242
+
243
+ expect(integration.frontify.api.access_token).toBe('frontify_access_token_uvw');
244
+ expect(integration.frontify.api.refresh_token).toBe('frontify_refresh_token_def');
245
+ expect(integration.frontify.api.domain).toBe('customer.frontify.com');
246
+
247
+ // CRITICAL TEST: Can call API methods successfully
248
+ const folders = await integration.asana.api.getFolders();
249
+ expect(folders.folders).toEqual(['Marketing', 'Development', 'Design']);
250
+ expect(folders.usedToken).toBe('asana_access_token_xyz');
251
+
252
+ const projects = await integration.asana.api.listProjects();
253
+ expect(projects.projects).toEqual(['Q1 Launch', 'Website Redesign']);
254
+ expect(projects.clientId).toBe('ASANA_CLIENT_ID_FROM_ENV');
255
+
256
+ const brands = await integration.frontify.api.listBrands();
257
+ expect(brands.brands).toEqual(['Main Brand', 'Sub Brand']);
258
+ expect(brands.domain).toBe('customer.frontify.com');
259
+ expect(brands.token).toBe('frontify_access_token_uvw');
260
+
261
+ const assets = await integration.frontify.api.searchAssets('logo');
262
+ expect(assets.query).toBe('logo');
263
+ expect(assets.assets).toEqual(['logo.svg', 'guidelines.pdf']);
264
+ expect(assets.clientSecret).toBe('hidden'); // Verifies secret exists
265
+
266
+ // CRITICAL TEST: Business logic methods can use hydrated APIs
267
+ const businessResult = await integration.performBusinessLogic();
268
+ expect(businessResult.folders.folders).toEqual(['Marketing', 'Development', 'Design']);
269
+ expect(businessResult.brands.brands).toEqual(['Main Brand', 'Sub Brand']);
270
+
271
+ // Verify the complete chain: env → Module → API → Integration
272
+ console.log('\n✅ Full Integration Test Results:');
273
+ console.log(' ENV vars injected: ✓');
274
+ console.log(' Credentials injected: ✓');
275
+ console.log(' API methods callable: ✓');
276
+ console.log(' Business logic works: ✓');
277
+ });
278
+
279
+ it('should handle missing credentials gracefully', async () => {
280
+ // Entity without credentials
281
+ const entities = [
282
+ {
283
+ id: 'entity-no-creds',
284
+ moduleName: 'asana',
285
+ userId: 'user-123',
286
+ credential: {
287
+ data: {
288
+ // Empty credential data - no access_token
289
+ },
290
+ },
291
+ },
292
+ ];
293
+
294
+ const moduleRepository = {
295
+ findEntitiesByIds: jest.fn().mockResolvedValue(entities),
296
+ findEntityById: jest.fn().mockResolvedValue(entities[0]),
297
+ };
298
+
299
+ const moduleFactory = new ModuleFactory({
300
+ moduleRepository,
301
+ moduleDefinitions: [asanaDefinition],
302
+ });
303
+
304
+ const useCase = new LoadIntegrationContextUseCase({
305
+ integrationRepository: createIntegrationRepository(),
306
+ moduleRepository,
307
+ moduleFactory,
308
+ });
309
+
310
+ const context = await useCase.execute({
311
+ integrationRecord: {
312
+ id: 'integration-1',
313
+ userId: 'user-123',
314
+ entitiesIds: ['entity-no-creds'],
315
+ },
316
+ });
317
+
318
+ const integration = new TestIntegration();
319
+ integration.setIntegrationRecord(context);
320
+
321
+ // Should have module with env vars but no credentials
322
+ expect(integration.asana).toBeDefined();
323
+ expect(integration.asana.api.client_id).toBe('ASANA_CLIENT_ID_FROM_ENV');
324
+ expect(integration.asana.api.access_token).toBeUndefined();
325
+
326
+ // API method should fail without token
327
+ await expect(integration.asana.api.getFolders()).rejects.toThrow('No access token');
328
+ });
329
+ });
@@ -0,0 +1,71 @@
1
+ class LoadIntegrationContextUseCase {
2
+ constructor({
3
+ integrationRepository,
4
+ moduleRepository,
5
+ moduleFactory,
6
+ }) {
7
+ if (!integrationRepository) {
8
+ throw new Error('integrationRepository is required');
9
+ }
10
+ if (!moduleRepository) {
11
+ throw new Error('moduleRepository is required');
12
+ }
13
+ if (!moduleFactory) {
14
+ throw new Error('moduleFactory is required');
15
+ }
16
+
17
+ this.integrationRepository = integrationRepository;
18
+ this.moduleRepository = moduleRepository;
19
+ this.moduleFactory = moduleFactory;
20
+ }
21
+
22
+ async execute({ integrationId, integrationRecord }) {
23
+ const record = integrationRecord
24
+ ? integrationRecord
25
+ : await this.integrationRepository.findIntegrationById(
26
+ integrationId
27
+ );
28
+
29
+ if (!record) {
30
+ const error = new Error('Integration record not found');
31
+ error.code = 'INTEGRATION_RECORD_NOT_FOUND';
32
+ throw error;
33
+ }
34
+
35
+ if (
36
+ !Array.isArray(record.entitiesIds) ||
37
+ record.entitiesIds.length === 0
38
+ ) {
39
+ return {
40
+ record: {
41
+ ...record,
42
+ entities: [],
43
+ },
44
+ modules: [],
45
+ };
46
+ }
47
+
48
+ const entities = await this.moduleRepository.findEntitiesByIds(
49
+ record.entitiesIds
50
+ );
51
+
52
+ const modules = [];
53
+ for (const entity of entities) {
54
+ const moduleInstance = await this.moduleFactory.getModuleInstance(
55
+ entity.id,
56
+ record.userId
57
+ );
58
+ modules.push(moduleInstance);
59
+ }
60
+
61
+ return {
62
+ record: {
63
+ ...record,
64
+ entities,
65
+ },
66
+ modules,
67
+ };
68
+ }
69
+ }
70
+
71
+ module.exports = { LoadIntegrationContextUseCase };
@@ -0,0 +1,114 @@
1
+ const { LoadIntegrationContextUseCase } = require('./load-integration-context');
2
+
3
+ class FakeIntegration {}
4
+ FakeIntegration.Definition = {
5
+ name: 'fake',
6
+ modules: {},
7
+ };
8
+
9
+ describe('LoadIntegrationContextUseCase', () => {
10
+ it('throws when neither integrationId nor integrationRecord resolve to a record', async () => {
11
+ const integrationRepository = {
12
+ findIntegrationById: jest.fn().mockResolvedValue(null),
13
+ };
14
+
15
+ const useCase = new LoadIntegrationContextUseCase({
16
+ integrationClass: FakeIntegration,
17
+ integrationRepository,
18
+ moduleRepository: { findEntitiesByIds: jest.fn() },
19
+ moduleFactory: { getModuleInstance: jest.fn() },
20
+ });
21
+
22
+ await expect(
23
+ useCase.execute({ integrationId: 'missing-id' })
24
+ ).rejects.toMatchObject({
25
+ message: 'Integration record not found',
26
+ code: 'INTEGRATION_RECORD_NOT_FOUND',
27
+ });
28
+ });
29
+
30
+ it('returns record with empty entities/modules when no entity ids provided', async () => {
31
+ const integrationRecord = {
32
+ id: 'integration-1',
33
+ userId: 'user-1',
34
+ entitiesIds: [],
35
+ };
36
+
37
+ const moduleRepository = { findEntitiesByIds: jest.fn() };
38
+ const moduleFactory = { getModuleInstance: jest.fn() };
39
+
40
+ const useCase = new LoadIntegrationContextUseCase({
41
+ integrationClass: FakeIntegration,
42
+ integrationRepository: {},
43
+ moduleRepository,
44
+ moduleFactory,
45
+ });
46
+
47
+ const result = await useCase.execute({ integrationRecord });
48
+
49
+ expect(result).toEqual({
50
+ record: {
51
+ ...integrationRecord,
52
+ entities: [],
53
+ },
54
+ modules: [],
55
+ });
56
+ expect(moduleRepository.findEntitiesByIds).not.toHaveBeenCalled();
57
+ expect(moduleFactory.getModuleInstance).not.toHaveBeenCalled();
58
+ });
59
+
60
+ it('hydrates modules and entities when entity ids are provided', async () => {
61
+ const integrationRecord = {
62
+ id: 'integration-2',
63
+ userId: 'user-2',
64
+ entitiesIds: ['entity-1', 'entity-2'],
65
+ };
66
+
67
+ const entities = [
68
+ { id: 'entity-1', name: 'First Entity' },
69
+ { id: 'entity-2', name: 'Second Entity' },
70
+ ];
71
+
72
+ const modules = [{ name: 'module-1' }, { name: 'module-2' }];
73
+
74
+ const moduleRepository = {
75
+ findEntitiesByIds: jest.fn().mockResolvedValue(entities),
76
+ };
77
+ const moduleFactory = {
78
+ getModuleInstance: jest
79
+ .fn()
80
+ .mockResolvedValueOnce(modules[0])
81
+ .mockResolvedValueOnce(modules[1]),
82
+ };
83
+
84
+ const useCase = new LoadIntegrationContextUseCase({
85
+ integrationClass: FakeIntegration,
86
+ integrationRepository: {},
87
+ moduleRepository,
88
+ moduleFactory,
89
+ });
90
+
91
+ const result = await useCase.execute({ integrationRecord });
92
+
93
+ expect(moduleRepository.findEntitiesByIds).toHaveBeenCalledWith(
94
+ integrationRecord.entitiesIds
95
+ );
96
+ expect(moduleFactory.getModuleInstance).toHaveBeenNthCalledWith(
97
+ 1,
98
+ 'entity-1',
99
+ integrationRecord.userId
100
+ );
101
+ expect(moduleFactory.getModuleInstance).toHaveBeenNthCalledWith(
102
+ 2,
103
+ 'entity-2',
104
+ integrationRecord.userId
105
+ );
106
+ expect(result).toEqual({
107
+ record: {
108
+ ...integrationRecord,
109
+ entities,
110
+ },
111
+ modules,
112
+ });
113
+ });
114
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Use case for updating messages associated with an integration.
3
+ * @class UpdateIntegrationMessages
4
+ */
5
+ class UpdateIntegrationMessages {
6
+ /**
7
+ * Creates a new UpdateIntegrationMessages instance.
8
+ * @param {Object} params - Configuration parameters.
9
+ * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository - Repository for integration data operations.
10
+ */
11
+ constructor({ integrationRepository }) {
12
+ this.integrationRepository = integrationRepository;
13
+ }
14
+
15
+ /**
16
+ * Executes the integration messages update.
17
+ * @async
18
+ * @param {string} integrationId - ID of the integration to update.
19
+ * @param {string} messageType - Type of message: 'errors', 'warnings', 'info', or 'logs'.
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.
23
+ * @returns {Promise<Object>} The updated integration record.
24
+ */
25
+ async execute(
26
+ integrationId,
27
+ messageType,
28
+ messageTitle,
29
+ messageBody,
30
+ messageTimestamp
31
+ ) {
32
+ const integration =
33
+ await this.integrationRepository.updateIntegrationMessages(
34
+ integrationId,
35
+ messageType,
36
+ messageTitle,
37
+ messageBody,
38
+ messageTimestamp
39
+ );
40
+ return integration;
41
+ }
42
+ }
43
+
44
+ module.exports = { UpdateIntegrationMessages };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Use case for updating the status of an integration.
3
+ * @class UpdateIntegrationStatus
4
+ */
5
+ class UpdateIntegrationStatus {
6
+ /**
7
+ * Creates a new UpdateIntegrationStatus instance.
8
+ * @param {Object} params - Configuration parameters.
9
+ * @param {import('../repositories/integration-repository-interface').IntegrationRepositoryInterface} params.integrationRepository - Repository for integration data operations.
10
+ */
11
+ constructor({ integrationRepository }) {
12
+ this.integrationRepository = integrationRepository;
13
+ }
14
+
15
+ /**
16
+ * Executes the integration status update.
17
+ * @async
18
+ * @param {string} integrationId - ID of the integration to update.
19
+ * @param {string} status - New status for the integration (e.g., 'ENABLED', 'DISABLED', 'ERROR').
20
+ * @returns {Promise<Object>} The updated integration record.
21
+ */
22
+ async execute(integrationId, status) {
23
+ const integration =
24
+ await this.integrationRepository.updateIntegrationStatus(
25
+ integrationId,
26
+ status
27
+ );
28
+ return integration;
29
+ }
30
+ }
31
+
32
+ module.exports = { UpdateIntegrationStatus };