@friggframework/devtools 2.0.0-next.120 → 2.0.0-next.122

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 (59) hide show
  1. package/frigg-cli/README.md +77 -30
  2. package/frigg-cli/__tests__/unit/commands/deploy.test.js +30 -24
  3. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  4. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  5. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  6. package/frigg-cli/__tests__/unit/commands/install.test.js +601 -341
  7. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  8. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  9. package/frigg-cli/generate-command/index.js +1 -0
  10. package/frigg-cli/generate-iam-command.js +1 -0
  11. package/frigg-cli/index.js +9 -4
  12. package/frigg-cli/init-command/backend-first-handler.js +397 -554
  13. package/frigg-cli/init-command/deployment-modes.js +7 -0
  14. package/frigg-cli/init-command/index.js +82 -35
  15. package/frigg-cli/init-command/safe-path.js +58 -0
  16. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  17. package/frigg-cli/install-command/app-definition.js +174 -0
  18. package/frigg-cli/install-command/commit-changes.js +40 -8
  19. package/frigg-cli/install-command/environment-variables.js +15 -0
  20. package/frigg-cli/install-command/index.js +96 -21
  21. package/frigg-cli/install-command/install-package.js +77 -4
  22. package/frigg-cli/install-command/integration-file.js +20 -11
  23. package/frigg-cli/install-command/resolve-module.js +69 -0
  24. package/frigg-cli/install-command/template.js +102 -75
  25. package/frigg-cli/install-command/validate-package.js +36 -4
  26. package/frigg-cli/package.json +1 -1
  27. package/frigg-cli/templates/backend/README.md +267 -0
  28. package/frigg-cli/templates/backend/env.example +20 -0
  29. package/frigg-cli/templates/backend/gitignore +10 -0
  30. package/frigg-cli/templates/backend/index.js +114 -0
  31. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  32. package/frigg-cli/test/init-command.test.js +9 -2
  33. package/infrastructure/__tests__/postgres-config.test.js +241 -835
  34. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  35. package/infrastructure/__tests__/template-generation.test.js +36 -8
  36. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
  37. package/infrastructure/domains/database/aurora-builder.js +13 -2
  38. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  39. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  40. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  41. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  42. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  43. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  44. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  45. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  46. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  47. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  48. package/infrastructure/domains/networking/vpc-builder.test.js +26 -12
  49. package/infrastructure/domains/security/iam-generator.js +112 -5
  50. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  51. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  52. package/infrastructure/domains/shared/utilities/base-definition-factory.js +7 -2
  53. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +21 -0
  54. package/infrastructure/infrastructure-composer.test.js +268 -794
  55. package/infrastructure/scripts/build-prisma-layer.test.js +28 -7
  56. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  57. package/package.json +10 -8
  58. package/frigg-cli/index.test.js +0 -158
  59. package/infrastructure/integration.test.js +0 -381
@@ -1,400 +1,660 @@
1
1
  /**
2
- * Test suite for install command
2
+ * Tests for `frigg install <module>`
3
3
  *
4
- * Tests the ACTUAL Frigg implementation including:
5
- * - Package search and selection (mocked - external npm)
6
- * - Package installation via npm (mocked - external)
7
- * - Integration file creation (REAL - tests actual file generation)
8
- * - Backend.js updates (REAL - tests actual file parsing/updating)
9
- * - Git commits (mocked - external)
10
- * - Environment variable handling (mocked - interactive)
11
- * - Label sanitization (REAL - tests actual regex logic)
4
+ * Runs the real install flow against apps on disk (temp directories):
5
+ * - a `frigg init` app (index.js exports the Definition, no backend.js)
6
+ * - an older app with a backend.js
7
+ *
8
+ * Only the external boundaries are mocked: npm search/registry and the
9
+ * interactive picker (validate-package), `npm install` (simulated by writing
10
+ * the module into the app's node_modules), env-var prompts, and git (except
11
+ * in the dedicated commit tests).
12
12
  */
13
13
 
14
- // Mock ONLY external boundaries - let Frigg logic run!
15
- jest.mock('fs-extra'); // Mock at I/O level
14
+ const path = require('path');
15
+ const os = require('os');
16
+ const fs = require('fs-extra');
17
+ const { spawnSync } = require('child_process');
18
+
16
19
  jest.mock('../../../install-command/install-package', () => ({
17
- installPackage: jest.fn() // External: npm install
20
+ ...jest.requireActual('../../../install-command/install-package'),
21
+ installPackage: jest.fn(),
18
22
  }));
19
23
  jest.mock('../../../install-command/commit-changes', () => ({
20
- commitChanges: jest.fn() // External: git commands
24
+ commitChanges: jest.fn(),
21
25
  }));
22
26
  jest.mock('../../../install-command/environment-variables', () => ({
23
- handleEnvVariables: jest.fn() // External: interactive prompts
27
+ handleEnvVariables: jest.fn(),
24
28
  }));
25
29
  jest.mock('../../../install-command/validate-package', () => ({
26
- validatePackageExists: jest.fn(), // External: npm registry
27
- searchAndSelectPackage: jest.fn() // External: interactive selection
30
+ validatePackageExists: jest.fn(),
31
+ searchAndSelectPackage: jest.fn(),
28
32
  }));
29
- jest.mock('@friggframework/core', () => ({
30
- findNearestBackendPackageJson: jest.fn(),
31
- validateBackendPath: jest.fn()
33
+ jest.mock('@friggframework/core/utils', () => ({
34
+ findNearestBackendPackageJson: jest.fn(),
35
+ validateBackendPath: jest.fn((p) => {
36
+ if (!p) throw new Error('Could not find a backend package.json file.');
37
+ }),
32
38
  }));
33
39
 
34
- // DON'T mock these - let them run to test actual Frigg logic:
35
- // - createIntegrationFile (tests file generation)
36
- // - updateBackendJsFile (tests file parsing)
37
- // - logger (just console.log, we'll spy on console)
38
- // - getIntegrationTemplate (tests template generation)
39
-
40
- // Require after mocks
41
- const fs = require('fs-extra');
42
40
  const { installPackage } = require('../../../install-command/install-package');
43
41
  const { commitChanges } = require('../../../install-command/commit-changes');
44
- const { handleEnvVariables } = require('../../../install-command/environment-variables');
45
- const { validatePackageExists, searchAndSelectPackage } = require('../../../install-command/validate-package');
46
- const { findNearestBackendPackageJson, validateBackendPath } = require('@friggframework/core');
42
+ const {
43
+ handleEnvVariables,
44
+ } = require('../../../install-command/environment-variables');
45
+ const {
46
+ validatePackageExists,
47
+ searchAndSelectPackage,
48
+ } = require('../../../install-command/validate-package');
49
+ const { findNearestBackendPackageJson } = require('@friggframework/core/utils');
47
50
  const { installCommand } = require('../../../install-command');
48
51
 
49
- describe('CLI Command: install', () => {
50
- let processExitSpy;
51
- let consoleLogSpy;
52
- let consoleErrorSpy;
53
- const mockBackendPath = '/mock/backend/package.json';
54
- const mockBackendDir = '/mock/backend';
55
-
56
- beforeEach(() => {
57
- jest.clearAllMocks();
58
-
59
- // Mock process.exit to prevent actual exit
60
- processExitSpy = jest.spyOn(process, 'exit').mockImplementation();
61
-
62
- // Spy on console for logger (don't mock logger - test it!)
63
- consoleLogSpy = jest.spyOn(console, 'log').mockImplementation();
64
- consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();
65
-
66
- // Setup fs-extra mocks - Let Frigg code run, just mock I/O
67
- fs.ensureDirSync = jest.fn();
68
- fs.writeFileSync = jest.fn();
69
- fs.readFileSync = jest.fn().mockReturnValue(`
70
- // Sample backend.js file
71
- const integrations = [
72
- // Existing integrations
73
- ];
74
-
75
- module.exports = {
76
- integrations: []
77
- };
78
- `);
79
- fs.existsSync = jest.fn().mockReturnValue(true);
80
-
81
- // Setup default successful mocks for external boundaries
82
- searchAndSelectPackage.mockResolvedValue(['@friggframework/api-module-slack']);
83
- findNearestBackendPackageJson.mockReturnValue(mockBackendPath);
84
- validateBackendPath.mockReturnValue(true);
85
- validatePackageExists.mockResolvedValue(true);
86
- installPackage.mockReturnValue(undefined);
87
- handleEnvVariables.mockResolvedValue(undefined);
88
-
89
- // Mock the dynamic require() of installed package using jest.doMock
90
- const path = require('path');
91
- const slackModulePath = path.resolve(mockBackendPath, '../../node_modules/@friggframework/api-module-slack');
92
-
93
- jest.doMock(slackModulePath, () => ({
94
- Config: { label: 'Slack' },
95
- Api: class SlackApi {}
96
- }), { virtual: true });
97
- });
98
-
99
- afterEach(() => {
100
- processExitSpy.mockRestore();
101
- consoleLogSpy.mockRestore();
102
- consoleErrorSpy.mockRestore();
103
- jest.resetModules(); // Clear module cache after each test
104
- });
105
-
106
- describe('Success Cases', () => {
107
- it('should orchestrate complete installation workflow', async () => {
108
- await installCommand('slack');
109
-
110
- // Verify external boundaries called
111
- expect(searchAndSelectPackage).toHaveBeenCalledWith('slack');
112
- expect(findNearestBackendPackageJson).toHaveBeenCalled();
113
- expect(validateBackendPath).toHaveBeenCalledWith(mockBackendPath);
114
- expect(validatePackageExists).toHaveBeenCalledWith('@friggframework/api-module-slack');
115
- expect(installPackage).toHaveBeenCalledWith(mockBackendPath, '@friggframework/api-module-slack');
52
+ const TEMPLATE_DIR = path.join(__dirname, '../../../templates/backend');
53
+ const CORE_DIR = path.dirname(
54
+ require.resolve('@friggframework/core/package.json')
55
+ );
56
+ const HUBSPOT = '@friggframework/api-module-hubspot';
57
+
58
+ const makeTmpDir = () =>
59
+ fs.realpathSync(
60
+ fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-install-test-'))
61
+ );
62
+
63
+ /** Write a minimal Frigg API module into <dir>/node_modules/<name>. */
64
+ function writeFakeModule(
65
+ dir,
66
+ name,
67
+ { label, moduleName, withDefinition = true } = {}
68
+ ) {
69
+ const moduleDir = path.join(dir, 'node_modules', ...name.split('/'));
70
+ fs.ensureDirSync(moduleDir);
71
+ fs.writeJSONSync(path.join(moduleDir, 'package.json'), {
72
+ name,
73
+ version: '2.0.0-next.7',
74
+ main: 'index.js',
116
75
  });
117
-
118
- it('should create integration file with correct path and content', async () => {
119
- await installCommand('slack');
120
-
121
- // Verify directory creation
122
- expect(fs.ensureDirSync).toHaveBeenCalledWith(
123
- expect.stringMatching(/src\/integrations$/)
124
- );
125
-
126
- // Verify integration file written with correct path
127
- expect(fs.writeFileSync).toHaveBeenCalledWith(
128
- expect.stringMatching(/SlackIntegration\.js$/),
129
- expect.any(String)
130
- );
131
-
132
- // Get the actual content that was written
133
- const writeCall = fs.writeFileSync.mock.calls.find(call =>
134
- call[0].includes('SlackIntegration.js')
135
- );
136
-
137
- expect(writeCall).toBeDefined();
138
- const [filePath, content] = writeCall;
139
-
140
- // Verify file content contains valid integration class
141
- expect(content).toContain('class SlackIntegration extends IntegrationBase');
142
- expect(content).toContain('@friggframework/core');
143
- expect(content).toContain('@friggframework/api-module-slack');
76
+ fs.writeFileSync(
77
+ path.join(moduleDir, 'index.js'),
78
+ withDefinition
79
+ ? `class Api {}
80
+ const Definition = {
81
+ API: Api,
82
+ getName: () => ${JSON.stringify(moduleName)},
83
+ moduleName: ${JSON.stringify(moduleName)},
84
+ requiredAuthMethods: {},
85
+ env: {},
86
+ };
87
+ module.exports = {
88
+ Api,
89
+ Definition,
90
+ Config: {
91
+ name: ${JSON.stringify(moduleName)},
92
+ label: ${JSON.stringify(label)},
93
+ productUrl: 'https://example.com',
94
+ logoUrl: 'https://example.com/logo.png',
95
+ categories: ['CRM'],
96
+ description: 'An example module',
97
+ },
98
+ };
99
+ `
100
+ : 'module.exports = { Api: class {} };\n'
101
+ );
102
+ return moduleDir;
103
+ }
104
+
105
+ /** A `frigg init` app: the real template's index.js plus a package.json. */
106
+ function makeScaffoldedApp({
107
+ coreRange = '2.0.0-next.115',
108
+ installedCoreVersion,
109
+ } = {}) {
110
+ const dir = makeTmpDir();
111
+ fs.copySync(
112
+ path.join(TEMPLATE_DIR, 'index.js'),
113
+ path.join(dir, 'index.js')
114
+ );
115
+ fs.writeJSONSync(path.join(dir, 'package.json'), {
116
+ name: 'my-app',
117
+ dependencies: { '@friggframework/core': coreRange },
144
118
  });
119
+ fs.ensureDirSync(path.join(dir, 'node_modules', '@friggframework'));
120
+ if (installedCoreVersion) {
121
+ // A stand-in core with a chosen version.
122
+ fs.outputJSONSync(
123
+ path.join(dir, 'node_modules/@friggframework/core/package.json'),
124
+ { name: '@friggframework/core', version: installedCoreVersion }
125
+ );
126
+ return dir;
127
+ }
128
+ // Let the generated files load the real core.
129
+ fs.symlinkSync(
130
+ CORE_DIR,
131
+ path.join(dir, 'node_modules', '@friggframework', 'core')
132
+ );
133
+ return dir;
134
+ }
145
135
 
146
- it('should generate valid JavaScript template', async () => {
147
- await installCommand('slack');
148
-
149
- const writeCall = fs.writeFileSync.mock.calls.find(call =>
150
- call[0].includes('SlackIntegration.js')
151
- );
152
-
153
- const [, content] = writeCall;
154
-
155
- // Verify template has required structure
156
- expect(content).toMatch(/class \w+Integration extends IntegrationBase/);
157
- expect(content).toContain('static Config =');
158
- expect(content).toContain('static Options =');
159
- expect(content).toContain('static modules =');
160
-
161
- // Verify template is syntactically valid (no unclosed braces, etc)
162
- expect(content.split('{').length).toBe(content.split('}').length);
136
+ describe('CLI Command: install', () => {
137
+ let processExitSpy;
138
+ let consoleLogSpy;
139
+ let consoleErrorSpy;
140
+ let modules;
141
+
142
+ const output = () =>
143
+ [...consoleLogSpy.mock.calls, ...consoleErrorSpy.mock.calls]
144
+ .map((args) => args.join(' '))
145
+ .join('\n');
146
+
147
+ const useApp = (dir) => {
148
+ findNearestBackendPackageJson.mockReturnValue(
149
+ path.join(dir, 'package.json')
150
+ );
151
+ installPackage.mockImplementation((backendPath, spec) => {
152
+ const name = spec.replace(/@(next|latest)$/, '');
153
+ writeFakeModule(path.dirname(backendPath), name, modules[name]);
154
+ });
155
+ };
156
+
157
+ beforeEach(() => {
158
+ jest.clearAllMocks();
159
+ processExitSpy = jest.spyOn(process, 'exit').mockImplementation();
160
+ consoleLogSpy = jest.spyOn(console, 'log').mockImplementation();
161
+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation();
162
+ modules = {
163
+ [HUBSPOT]: { label: 'HubSpot', moduleName: 'hubspot' },
164
+ '@friggframework/api-module-google-drive': {
165
+ label: 'Google Drive',
166
+ moduleName: 'google-drive',
167
+ },
168
+ };
169
+ searchAndSelectPackage.mockResolvedValue([HUBSPOT]);
170
+ validatePackageExists.mockResolvedValue(true);
171
+ handleEnvVariables.mockResolvedValue(undefined);
163
172
  });
164
173
 
165
- it('should update backend.js with integration import', async () => {
166
- await installCommand('slack');
167
-
168
- // Verify backend.js was read
169
- expect(fs.readFileSync).toHaveBeenCalledWith(
170
- expect.stringMatching(/backend\.js$/),
171
- 'utf-8'
172
- );
173
-
174
- // Verify backend.js was written back with import
175
- const backendWriteCall = fs.writeFileSync.mock.calls.find(call =>
176
- call[0].includes('backend.js')
177
- );
178
-
179
- expect(backendWriteCall).toBeDefined();
180
- const [, updatedBackend] = backendWriteCall;
181
-
182
- // Verify import statement added
183
- expect(updatedBackend).toContain('const SlackIntegration = require');
184
- expect(updatedBackend).toContain('./src/integrations/SlackIntegration');
185
-
186
- // Verify integration added to array
187
- expect(updatedBackend).toContain('SlackIntegration,');
174
+ afterEach(() => {
175
+ jest.restoreAllMocks();
188
176
  });
189
177
 
190
- it('should commit changes after file operations', async () => {
191
- await installCommand('slack');
192
-
193
- expect(commitChanges).toHaveBeenCalledWith(mockBackendPath, 'Slack');
178
+ describe('in a `frigg init` app (index.js, no backend.js)', () => {
179
+ it('installs the module from the app directory with the next tag for a 2.x prerelease app', async () => {
180
+ const dir = makeScaffoldedApp();
181
+ useApp(dir);
182
+
183
+ await installCommand('hubspot');
184
+
185
+ expect(processExitSpy).not.toHaveBeenCalled();
186
+ expect(installPackage).toHaveBeenCalledWith(
187
+ path.join(dir, 'package.json'),
188
+ `${HUBSPOT}@next`
189
+ );
190
+ expect(handleEnvVariables).toHaveBeenCalledWith(
191
+ path.join(dir, 'package.json'),
192
+ path.join(
193
+ dir,
194
+ 'node_modules',
195
+ '@friggframework',
196
+ 'api-module-hubspot'
197
+ )
198
+ );
199
+ });
200
+
201
+ it('installs the default version for an app on a stable release', async () => {
202
+ const dir = makeScaffoldedApp({
203
+ coreRange: '^2.0.1',
204
+ installedCoreVersion: '2.0.1',
205
+ });
206
+ useApp(dir);
207
+
208
+ await installCommand('hubspot');
209
+
210
+ expect(installPackage).toHaveBeenCalledWith(
211
+ path.join(dir, 'package.json'),
212
+ HUBSPOT
213
+ );
214
+ });
215
+
216
+ it('creates src/integrations/<Label>Integration.js and registers it in index.js', async () => {
217
+ const dir = makeScaffoldedApp();
218
+ useApp(dir);
219
+
220
+ await installCommand('hubspot');
221
+
222
+ const integrationFile = path.join(
223
+ dir,
224
+ 'src/integrations/HubSpotIntegration.js'
225
+ );
226
+ expect(fs.existsSync(integrationFile)).toBe(true);
227
+ const index = fs.readFileSync(path.join(dir, 'index.js'), 'utf8');
228
+ expect(index).toContain(
229
+ "const HubSpotIntegration = require('./src/integrations/HubSpotIntegration');"
230
+ );
231
+ expect(index).toMatch(
232
+ /integrations: \[\n {8}HubSpotIntegration,\n/
233
+ );
234
+ expect(output()).toMatch(/Added HubSpotIntegration to index\.js/);
235
+ });
236
+
237
+ it('produces an app definition that loads, validates, and exposes the integration', async () => {
238
+ const dir = makeScaffoldedApp();
239
+ useApp(dir);
240
+
241
+ await installCommand('hubspot');
242
+
243
+ const { Definition } = require(path.join(dir, 'index.js'));
244
+ expect(Definition.integrations).toHaveLength(1);
245
+ const [Integration] = Definition.integrations;
246
+ const { IntegrationBase } = require('@friggframework/core');
247
+ expect(Object.getPrototypeOf(Integration)).toBe(IntegrationBase);
248
+ expect(Integration.Definition.name).toBe('hubspot');
249
+ expect(
250
+ Integration.Definition.modules.hubspot.definition.getName()
251
+ ).toBe('hubspot');
252
+ // The shape the Management API lists integrations with.
253
+ expect(Integration.getOptionDetails()).toMatchObject({
254
+ type: 'hubspot',
255
+ display: {
256
+ name: 'HubSpot',
257
+ icon: 'https://example.com/logo.png',
258
+ },
259
+ });
260
+ });
261
+
262
+ it('turns a label into a valid identifier', async () => {
263
+ const dir = makeScaffoldedApp();
264
+ useApp(dir);
265
+ searchAndSelectPackage.mockResolvedValue([
266
+ '@friggframework/api-module-google-drive',
267
+ ]);
268
+
269
+ await installCommand('google-drive');
270
+
271
+ const file = path.join(
272
+ dir,
273
+ 'src/integrations/GoogleDriveIntegration.js'
274
+ );
275
+ const content = fs.readFileSync(file, 'utf8');
276
+ expect(content).toContain(
277
+ 'class GoogleDriveIntegration extends IntegrationBase'
278
+ );
279
+ expect(content).toContain(
280
+ 'googleDrive: { definition: googleDriveModule.Definition }'
281
+ );
282
+ const { Definition } = require(path.join(dir, 'index.js'));
283
+ expect(Definition.integrations[0].Definition.name).toBe(
284
+ 'google-drive'
285
+ );
286
+ });
287
+
288
+ it('is idempotent: a second install keeps the file and does not register twice', async () => {
289
+ const dir = makeScaffoldedApp();
290
+ useApp(dir);
291
+ await installCommand('hubspot');
292
+ const file = path.join(
293
+ dir,
294
+ 'src/integrations/HubSpotIntegration.js'
295
+ );
296
+ fs.appendFileSync(file, '// my edits\n');
297
+ const indexAfterFirst = fs.readFileSync(
298
+ path.join(dir, 'index.js'),
299
+ 'utf8'
300
+ );
301
+
302
+ await installCommand('hubspot');
303
+
304
+ expect(fs.readFileSync(file, 'utf8')).toContain('// my edits');
305
+ expect(fs.readFileSync(path.join(dir, 'index.js'), 'utf8')).toBe(
306
+ indexAfterFirst
307
+ );
308
+ expect(output()).toMatch(
309
+ /HubSpotIntegration is already in index\.js/
310
+ );
311
+ });
312
+
313
+ it('prints the manual steps and leaves index.js alone when it cannot edit it safely', async () => {
314
+ const dir = makeScaffoldedApp();
315
+ const custom =
316
+ "const integrations = require('./list');\nmodule.exports = { Definition: { integrations } };\n";
317
+ fs.writeFileSync(path.join(dir, 'index.js'), custom);
318
+ useApp(dir);
319
+
320
+ await installCommand('hubspot');
321
+
322
+ expect(processExitSpy).not.toHaveBeenCalled();
323
+ expect(fs.readFileSync(path.join(dir, 'index.js'), 'utf8')).toBe(
324
+ custom
325
+ );
326
+ expect(
327
+ fs.existsSync(
328
+ path.join(dir, 'src/integrations/HubSpotIntegration.js')
329
+ )
330
+ ).toBe(true);
331
+ expect(output()).toContain(
332
+ "const HubSpotIntegration = require('./src/integrations/HubSpotIntegration');"
333
+ );
334
+ expect(output()).toContain('integrations: [HubSpotIntegration]');
335
+ });
336
+
337
+ it('passes every changed file to the commit step', async () => {
338
+ const dir = makeScaffoldedApp();
339
+ useApp(dir);
340
+
341
+ await installCommand('hubspot');
342
+
343
+ expect(commitChanges).toHaveBeenCalledWith(
344
+ path.join(dir, 'package.json'),
345
+ 'HubSpot',
346
+ [
347
+ path.join(dir, 'src/integrations/HubSpotIntegration.js'),
348
+ path.join(dir, 'index.js'),
349
+ path.join(dir, 'package.json'),
350
+ ]
351
+ );
352
+ });
194
353
  });
195
354
 
196
- it('should handle environment variables after installation', async () => {
197
- await installCommand('slack');
198
-
199
- expect(handleEnvVariables).toHaveBeenCalledWith(
200
- mockBackendPath,
201
- expect.stringContaining('@friggframework/api-module-slack')
202
- );
355
+ describe('in an older app with backend.js', () => {
356
+ it('registers the integration in backend.js and leaves index.js alone', async () => {
357
+ const root = makeTmpDir();
358
+ const dir = path.join(root, 'backend');
359
+ fs.ensureDirSync(dir);
360
+ fs.writeJSONSync(path.join(dir, 'package.json'), {
361
+ name: 'backend',
362
+ });
363
+ fs.writeFileSync(
364
+ path.join(dir, 'index.js'),
365
+ "module.exports = require('./backend');\n"
366
+ );
367
+ fs.writeFileSync(
368
+ path.join(dir, 'backend.js'),
369
+ 'const appDefinition = {\n integrations: [],\n};\nmodule.exports = appDefinition;\n'
370
+ );
371
+ // Hoisted node_modules at the workspace root still resolves.
372
+ // (Created up front: Jest's resolver caches missing directories.)
373
+ fs.ensureDirSync(path.join(root, 'node_modules'));
374
+ findNearestBackendPackageJson.mockReturnValue(
375
+ path.join(dir, 'package.json')
376
+ );
377
+ installPackage.mockImplementation((backendPath, spec) => {
378
+ const name = spec.replace(/@(next|latest)$/, '');
379
+ writeFakeModule(root, name, modules[name]);
380
+ });
381
+
382
+ await installCommand('hubspot');
383
+
384
+ expect(consoleErrorSpy.mock.calls).toEqual([]);
385
+ expect(processExitSpy).not.toHaveBeenCalled();
386
+ const backendJs = fs.readFileSync(
387
+ path.join(dir, 'backend.js'),
388
+ 'utf8'
389
+ );
390
+ expect(backendJs).toContain(
391
+ "const HubSpotIntegration = require('./src/integrations/HubSpotIntegration');"
392
+ );
393
+ expect(backendJs).toContain('HubSpotIntegration,');
394
+ expect(fs.readFileSync(path.join(dir, 'index.js'), 'utf8')).toBe(
395
+ "module.exports = require('./backend');\n"
396
+ );
397
+ expect(
398
+ fs.existsSync(
399
+ path.join(dir, 'src/integrations/HubSpotIntegration.js')
400
+ )
401
+ ).toBe(true);
402
+ });
203
403
  });
204
404
 
205
- it('should log info messages during installation', async () => {
206
- await installCommand('slack');
207
-
208
- // Verify logger actually logged (we spy on console)
209
- expect(consoleLogSpy).toHaveBeenCalledWith(
210
- expect.stringContaining('Successfully installed @friggframework/api-module-slack')
211
- );
405
+ describe('early exits and errors', () => {
406
+ it.each([[[]], [null], [undefined]])(
407
+ 'returns early when the selection is %p',
408
+ async (selection) => {
409
+ searchAndSelectPackage.mockResolvedValue(selection);
410
+
411
+ await installCommand('hubspot');
412
+
413
+ expect(findNearestBackendPackageJson).not.toHaveBeenCalled();
414
+ expect(installPackage).not.toHaveBeenCalled();
415
+ }
416
+ );
417
+
418
+ it('exits when no app package.json is found', async () => {
419
+ findNearestBackendPackageJson.mockReturnValue(null);
420
+
421
+ await installCommand('hubspot');
422
+
423
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
424
+ 'An error occurred:',
425
+ expect.any(Error)
426
+ );
427
+ expect(processExitSpy).toHaveBeenCalledWith(1);
428
+ });
429
+
430
+ it('exits when the package does not exist', async () => {
431
+ useApp(makeScaffoldedApp());
432
+ const error = new Error('Package not found');
433
+ validatePackageExists.mockRejectedValue(error);
434
+
435
+ await installCommand('hubspot');
436
+
437
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
438
+ 'An error occurred:',
439
+ error
440
+ );
441
+ expect(processExitSpy).toHaveBeenCalledWith(1);
442
+ });
443
+
444
+ it('exits when npm install fails', async () => {
445
+ useApp(makeScaffoldedApp());
446
+ const error = new Error('npm install exited with code 1');
447
+ installPackage.mockImplementation(() => {
448
+ throw error;
449
+ });
450
+
451
+ await installCommand('hubspot');
452
+
453
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
454
+ 'An error occurred:',
455
+ error
456
+ );
457
+ expect(processExitSpy).toHaveBeenCalledWith(1);
458
+ });
459
+
460
+ it('exits when the installed package is not a Frigg API module', async () => {
461
+ const dir = makeScaffoldedApp();
462
+ useApp(dir);
463
+ modules[HUBSPOT] = { withDefinition: false };
464
+
465
+ await installCommand('hubspot');
466
+
467
+ expect(output()).toMatch(/does not export a Definition/);
468
+ expect(processExitSpy).toHaveBeenCalledWith(1);
469
+ expect(fs.existsSync(path.join(dir, 'src/integrations'))).toBe(
470
+ false
471
+ );
472
+ });
212
473
  });
474
+ });
213
475
 
214
- it('should install multiple packages sequentially', async () => {
215
- searchAndSelectPackage.mockResolvedValue([
216
- '@friggframework/api-module-slack',
217
- '@friggframework/api-module-hubspot'
218
- ]);
219
-
220
- // Mock HubSpot module (Slack already mocked in beforeEach)
221
- const path = require('path');
222
- const hubspotPath = path.resolve(mockBackendPath, '../../node_modules/@friggframework/api-module-hubspot');
223
-
224
- jest.doMock(hubspotPath, () => ({
225
- Config: { label: 'HubSpot' },
226
- Api: class HubSpotApi {}
227
- }), { virtual: true });
228
-
229
- await installCommand('crm');
230
-
231
- expect(validatePackageExists).toHaveBeenCalledTimes(2);
232
- expect(installPackage).toHaveBeenCalledTimes(2);
233
-
234
- // Verify TWO integration files created
235
- const integrationFiles = fs.writeFileSync.mock.calls.filter(call =>
236
- call[0].includes('Integration.js') && !call[0].includes('backend.js')
237
- );
238
- expect(integrationFiles.length).toBe(2);
239
-
240
- // Verify both files have correct names
241
- expect(integrationFiles[0][0]).toContain('SlackIntegration.js');
242
- expect(integrationFiles[1][0]).toContain('HubSpotIntegration.js');
476
+ describe('registerIntegration', () => {
477
+ const {
478
+ registerIntegration,
479
+ } = require('../../../install-command/app-definition');
480
+ const write = (source) => {
481
+ const file = path.join(makeTmpDir(), 'index.js');
482
+ fs.writeFileSync(file, source);
483
+ return file;
484
+ };
485
+
486
+ it('adds the require after the last top-level require and the class to a non-empty array', () => {
487
+ const file = write(
488
+ "'use strict';\nconst A = require('./a');\n\nmodule.exports = { Definition: { integrations: [A] } };\n"
489
+ );
490
+
491
+ expect(
492
+ registerIntegration(
493
+ file,
494
+ 'BIntegration',
495
+ './src/integrations/BIntegration'
496
+ )
497
+ ).toEqual({
498
+ status: 'registered',
499
+ });
500
+ expect(fs.readFileSync(file, 'utf8')).toBe(
501
+ "'use strict';\nconst A = require('./a');\nconst BIntegration = require('./src/integrations/BIntegration');\n\n" +
502
+ 'module.exports = { Definition: { integrations: [\n BIntegration,\n A] } };\n'
503
+ );
243
504
  });
244
505
 
245
- it('should sanitize label by removing invalid characters', async () => {
246
- // Mock different package with special characters in label
247
- searchAndSelectPackage.mockResolvedValue(['@friggframework/api-module-google-drive']);
248
-
249
- const path = require('path');
250
- const googleDrivePath = path.resolve(mockBackendPath, '../../node_modules/@friggframework/api-module-google-drive');
251
-
252
- jest.doMock(googleDrivePath, () => ({
253
- Config: { label: 'Google<Drive>' }, // Has invalid characters
254
- Api: class GoogleDriveApi {}
255
- }), { virtual: true });
256
-
257
- await installCommand('google-drive');
258
-
259
- // Verify sanitized label used in file name
260
- const writeCall = fs.writeFileSync.mock.calls.find(call =>
261
- call[0].includes('Integration.js')
262
- );
263
-
264
- // Should be GoogleDrive, not Google<Drive>
265
- expect(writeCall[0]).toContain('GoogleDriveIntegration.js');
266
- expect(writeCall[0]).not.toContain('<');
267
- expect(writeCall[0]).not.toContain('>');
268
-
269
- // Verify content uses sanitized name
270
- expect(writeCall[1]).toContain('class GoogleDriveIntegration');
271
- expect(writeCall[1]).not.toContain('Google<Drive>');
506
+ it('handles a require that follows the definition', () => {
507
+ const file = write(
508
+ "const def = { integrations: [] };\nconst x = require('x');\nmodule.exports = def;\n"
509
+ );
510
+
511
+ expect(registerIntegration(file, 'BIntegration', './b').status).toBe(
512
+ 'registered'
513
+ );
514
+ expect(fs.readFileSync(file, 'utf8')).toBe(
515
+ "const def = { integrations: [\n BIntegration,\n] };\nconst x = require('x');\nconst BIntegration = require('./b');\nmodule.exports = def;\n"
516
+ );
272
517
  });
273
518
 
274
- it('should sanitize label by removing spaces', async () => {
275
- // Mock different package with spaces in label
276
- searchAndSelectPackage.mockResolvedValue(['@friggframework/api-module-google-calendar']);
519
+ it('refuses to guess when there are two integrations arrays', () => {
520
+ const source =
521
+ 'module.exports = { a: { integrations: [] }, b: { integrations: [] } };\n';
522
+ const file = write(source);
277
523
 
278
- const path = require('path');
279
- const googleCalendarPath = path.resolve(mockBackendPath, '../../node_modules/@friggframework/api-module-google-calendar');
280
-
281
- jest.doMock(googleCalendarPath, () => ({
282
- Config: { label: 'Google Calendar' }, // Has spaces
283
- Api: class GoogleCalendarApi {}
284
- }), { virtual: true });
285
-
286
- await installCommand('google-calendar');
287
-
288
- // Verify sanitized label used in file name (no spaces)
289
- const writeCall = fs.writeFileSync.mock.calls.find(call =>
290
- call[0].includes('Integration.js')
291
- );
292
-
293
- expect(writeCall[0]).toContain('GoogleCalendarIntegration.js');
294
- expect(writeCall[0]).not.toContain(' ');
295
-
296
- // Verify content uses sanitized name
297
- expect(writeCall[1]).toContain('class GoogleCalendarIntegration');
298
- expect(writeCall[1]).not.toMatch(/class Google Calendar/);
524
+ expect(registerIntegration(file, 'BIntegration', './b')).toMatchObject({
525
+ status: 'manual',
526
+ });
527
+ expect(fs.readFileSync(file, 'utf8')).toBe(source);
299
528
  });
300
- });
301
-
302
- describe('Early Exit Cases', () => {
303
- it('should return early when no packages selected', async () => {
304
- searchAndSelectPackage.mockResolvedValue([]);
305
529
 
306
- await installCommand('slack');
530
+ it('refuses a file that does not parse', () => {
531
+ const file = write('module.exports = { integrations: [ };\n');
307
532
 
308
- expect(findNearestBackendPackageJson).not.toHaveBeenCalled();
309
- expect(validatePackageExists).not.toHaveBeenCalled();
310
- expect(installPackage).not.toHaveBeenCalled();
533
+ expect(registerIntegration(file, 'BIntegration', './b')).toMatchObject({
534
+ status: 'manual',
535
+ reason: expect.stringMatching(/cannot parse/),
536
+ });
311
537
  });
312
538
 
313
- it('should return early when packages is null', async () => {
314
- searchAndSelectPackage.mockResolvedValue(null);
315
-
316
- await installCommand('slack');
539
+ it('refuses a partly registered class', () => {
540
+ const file = write(
541
+ 'module.exports = { integrations: [BIntegration] };\n'
542
+ );
317
543
 
318
- expect(findNearestBackendPackageJson).not.toHaveBeenCalled();
544
+ expect(registerIntegration(file, 'BIntegration', './b')).toMatchObject({
545
+ status: 'manual',
546
+ });
319
547
  });
548
+ });
320
549
 
321
- it('should return early when packages is undefined', async () => {
322
- searchAndSelectPackage.mockResolvedValue(undefined);
323
-
324
- await installCommand('slack');
325
-
326
- expect(findNearestBackendPackageJson).not.toHaveBeenCalled();
550
+ describe('getInstallSpec', () => {
551
+ const { getInstallSpec } = jest.requireActual(
552
+ '../../../install-command/install-package'
553
+ );
554
+ const appWith = (pkg) => {
555
+ const dir = makeTmpDir();
556
+ fs.writeJSONSync(path.join(dir, 'package.json'), pkg);
557
+ return dir;
558
+ };
559
+
560
+ it.each([
561
+ ['2.0.0-next.115', `${HUBSPOT}@next`],
562
+ ['2.0.0--canary.639.abc1234.0', `${HUBSPOT}@next`],
563
+ ['^2.0.1', HUBSPOT],
564
+ ['^1.2.2', HUBSPOT],
565
+ ])('core %s installs %s', (range, spec) => {
566
+ expect(
567
+ getInstallSpec(
568
+ HUBSPOT,
569
+ appWith({ dependencies: { '@friggframework/core': range } })
570
+ )
571
+ ).toBe(spec);
327
572
  });
328
- });
329
-
330
- describe('Error Handling', () => {
331
- it('should log error and exit on searchAndSelectPackage failure', async () => {
332
- const error = new Error('Search failed');
333
- searchAndSelectPackage.mockRejectedValue(error);
334
573
 
335
- await installCommand('slack');
336
-
337
- // Verify error logged via console.error (we spy on it)
338
- expect(consoleErrorSpy).toHaveBeenCalledWith('An error occurred:', error);
339
- expect(processExitSpy).toHaveBeenCalledWith(1);
574
+ it('uses the installed core version when the range is not semver (file:, link:)', () => {
575
+ const dir = appWith({
576
+ dependencies: { '@friggframework/core': 'file:../core.tgz' },
577
+ });
578
+ const coreDir = path.join(
579
+ dir,
580
+ 'node_modules',
581
+ '@friggframework',
582
+ 'core'
583
+ );
584
+ fs.ensureDirSync(coreDir);
585
+ fs.writeJSONSync(path.join(coreDir, 'package.json'), {
586
+ name: '@friggframework/core',
587
+ version: '2.0.0-next.0',
588
+ });
589
+
590
+ expect(getInstallSpec(HUBSPOT, dir)).toBe(`${HUBSPOT}@next`);
340
591
  });
341
592
 
342
- it('should log error and exit on validatePackageExists failure', async () => {
343
- const error = new Error('Package not found');
344
- validatePackageExists.mockRejectedValue(error);
345
-
346
- await installCommand('slack');
347
-
348
- expect(consoleErrorSpy).toHaveBeenCalledWith('An error occurred:', error);
349
- expect(processExitSpy).toHaveBeenCalledWith(1);
593
+ it('installs the default version without a readable package.json', () => {
594
+ expect(getInstallSpec(HUBSPOT, makeTmpDir())).toBe(HUBSPOT);
350
595
  });
596
+ });
351
597
 
352
- it('should log error and exit on installPackage failure', async () => {
353
- const error = new Error('Installation failed');
354
- installPackage.mockImplementation(() => {
355
- throw error;
356
- });
357
-
358
- await installCommand('slack');
359
-
360
- expect(consoleErrorSpy).toHaveBeenCalledWith('An error occurred:', error);
361
- expect(processExitSpy).toHaveBeenCalledWith(1);
598
+ describe('commitChanges', () => {
599
+ const { commitChanges: realCommit } = jest.requireActual(
600
+ '../../../install-command/commit-changes'
601
+ );
602
+ const env = { ...process.env };
603
+
604
+ beforeEach(() => {
605
+ jest.spyOn(console, 'log').mockImplementation();
606
+ // The CLI test setup replaces PATH; git lives on the real one.
607
+ process.env.PATH = '/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin';
608
+ process.env.GIT_AUTHOR_NAME = process.env.GIT_COMMITTER_NAME = 'Test';
609
+ process.env.GIT_AUTHOR_EMAIL = process.env.GIT_COMMITTER_EMAIL =
610
+ 'test@example.com';
362
611
  });
363
612
 
364
- it('should log error and exit on file write failure (createIntegrationFile)', async () => {
365
- // Make fs.writeFileSync throw - tests REAL error path
366
- const error = new Error('EACCES: permission denied');
367
- fs.writeFileSync.mockImplementation(() => {
368
- throw error;
369
- });
370
-
371
- await installCommand('slack');
372
-
373
- expect(consoleErrorSpy).toHaveBeenCalledWith('An error occurred:', expect.any(Error));
374
- expect(processExitSpy).toHaveBeenCalledWith(1);
613
+ afterEach(() => {
614
+ process.env = { ...env };
615
+ jest.restoreAllMocks();
375
616
  });
376
617
 
377
- it('should log error and exit on backend.js read failure', async () => {
378
- // Make fs.readFileSync throw - tests REAL error path
379
- const error = new Error('ENOENT: file not found');
380
- fs.readFileSync.mockImplementation(() => {
381
- throw error;
382
- });
383
-
384
- await installCommand('slack');
385
-
386
- expect(consoleErrorSpy).toHaveBeenCalledWith('An error occurred:', expect.any(Error));
387
- expect(processExitSpy).toHaveBeenCalledWith(1);
618
+ const git = (args, cwd) =>
619
+ spawnSync('git', args, { cwd, encoding: 'utf8', env: process.env });
620
+
621
+ it('commits only the given files and leaves other staged changes alone', () => {
622
+ const dir = makeTmpDir();
623
+ git(['init', '-q'], dir);
624
+ // commitChanges spawns git without an explicit env, so it sees the
625
+ // real process environment, not Jest's sandboxed process.env: the
626
+ // GIT_* identity set above never reaches it. Give the repo its own
627
+ // identity so the commit works on CI runners with no git user.
628
+ git(['config', 'user.name', 'Test'], dir);
629
+ git(['config', 'user.email', 'test@example.com'], dir);
630
+ git(['config', 'commit.gpgsign', 'false'], dir);
631
+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');
632
+ fs.writeFileSync(path.join(dir, 'unrelated.txt'), 'wip');
633
+ git(['add', 'unrelated.txt'], dir);
634
+
635
+ const committed = realCommit(
636
+ path.join(dir, 'package.json'),
637
+ 'HubSpot',
638
+ [path.join(dir, 'package.json')]
639
+ );
640
+
641
+ expect(committed).toBe(true);
642
+ expect(
643
+ git(['show', '--name-only', '--format=%s', 'HEAD'], dir).stdout
644
+ ).toBe('Add HubSpot integration\n\npackage.json\n');
645
+ expect(git(['diff', '--cached', '--name-only'], dir).stdout).toBe(
646
+ 'unrelated.txt\n'
647
+ );
388
648
  });
389
649
 
390
- it('should log error and exit on handleEnvVariables failure', async () => {
391
- const error = new Error('Env variables failed');
392
- handleEnvVariables.mockRejectedValue(error);
393
-
394
- await installCommand('slack');
650
+ it('does nothing outside a git repository', () => {
651
+ const dir = makeTmpDir();
652
+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');
395
653
 
396
- expect(consoleErrorSpy).toHaveBeenCalledWith('An error occurred:', error);
397
- expect(processExitSpy).toHaveBeenCalledWith(1);
654
+ expect(
655
+ realCommit(path.join(dir, 'package.json'), 'HubSpot', [
656
+ path.join(dir, 'package.json'),
657
+ ])
658
+ ).toBe(false);
398
659
  });
399
- });
400
660
  });