@friggframework/devtools 2.0.0--canary.667.f74cf3b.0 → 2.0.0--canary.710.7cfcf12.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 (62) 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/admin-scripts/admin-script-builder.js +6 -2
  38. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +30 -0
  39. package/infrastructure/domains/database/aurora-builder.js +13 -2
  40. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  41. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  42. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  43. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  44. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  45. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  46. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  47. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  48. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  49. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  50. package/infrastructure/domains/networking/vpc-builder.test.js +26 -12
  51. package/infrastructure/domains/security/iam-generator.js +112 -5
  52. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  53. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  54. package/infrastructure/domains/shared/utilities/base-definition-factory.js +7 -21
  55. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +22 -13
  56. package/infrastructure/infrastructure-composer.test.js +268 -794
  57. package/infrastructure/scripts/build-prisma-layer.test.js +28 -7
  58. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  59. package/package.json +10 -8
  60. package/frigg-cli/index.test.js +0 -158
  61. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -281
  62. package/infrastructure/integration.test.js +0 -381
@@ -143,14 +143,35 @@ describe('getMigrationsPackages()', () => {
143
143
  });
144
144
 
145
145
  describe('getMigrationSourcePath()', () => {
146
- it('should return correct source path for database type', () => {
147
- const searchPaths = ['/workspace/packages/core'];
148
- const dbType = 'postgresql';
146
+ // getMigrationSourcePath() returns the first search path whose
147
+ // prisma-<dbType>/migrations directory exists on disk, so the test needs a
148
+ // real directory rather than a made-up absolute path.
149
+ const fs = require('fs');
150
+ const os = require('os');
151
+ const path = require('path');
152
+ let tmpRoot;
153
+
154
+ beforeEach(() => {
155
+ tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-prisma-layer-'));
156
+ });
149
157
 
150
- const sourcePath = getMigrationSourcePath(searchPaths, dbType);
151
- expect(sourcePath).toBe(
152
- '/workspace/packages/core/prisma-postgresql/migrations'
153
- );
158
+ afterEach(() => {
159
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
160
+ });
161
+
162
+ it('should return the migrations path of the first search path that has one', () => {
163
+ const missing = path.join(tmpRoot, 'missing');
164
+ const core = path.join(tmpRoot, 'packages', 'core');
165
+ const expected = path.join(core, 'prisma-postgresql', 'migrations');
166
+ fs.mkdirSync(expected, { recursive: true });
167
+
168
+ const sourcePath = getMigrationSourcePath([missing, core], 'postgresql');
169
+ expect(sourcePath).toBe(expected);
170
+ });
171
+
172
+ it('should return null when no search path has migrations for the database type', () => {
173
+ const sourcePath = getMigrationSourcePath([tmpRoot], 'postgresql');
174
+ expect(sourcePath).toBeNull();
154
175
  });
155
176
  });
156
177
 
@@ -1,14 +1,29 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
- const { BuildTimeDiscovery, runBuildTimeDiscovery } = require('./build-time-discovery');
4
- const { AWSDiscovery } = require('./aws-discovery');
3
+
4
+ // SKIPPED: BuildTimeDiscovery lazily requires './aws-discovery', which was
5
+ // deleted in the hexagonal infrastructure refactor (7b36f0f4). Discovery now
6
+ // lives in domains/shared/resource-discovery.js + providers/aws-provider-adapter.js,
7
+ // and nothing in devtools, the CLI or the serverless plugin invokes
8
+ // build-time-discovery.js / run-discovery.js any more, so this suite cannot load
9
+ // its subject. Either port BuildTimeDiscovery to gatherDiscoveredResources() and
10
+ // rewrite these tests, or delete the dead module and this suite.
11
+ // Tracked in https://github.com/friggframework/frigg/issues/708
12
+ let BuildTimeDiscovery;
13
+ let runBuildTimeDiscovery;
14
+ let AWSDiscovery;
5
15
 
6
16
  // Mock dependencies
7
17
  jest.mock('fs');
8
18
  // Mock will be updated when tests are rewritten for new provider architecture
9
19
  // jest.mock('./aws-discovery');
10
20
 
11
- describe('BuildTimeDiscovery', () => {
21
+ describe.skip('BuildTimeDiscovery', () => {
22
+ beforeAll(() => {
23
+ ({ BuildTimeDiscovery, runBuildTimeDiscovery } = require('./build-time-discovery'));
24
+ ({ AWSDiscovery } = require('./aws-discovery'));
25
+ });
26
+
12
27
  let buildTimeDiscovery;
13
28
  let mockAWSDiscovery;
14
29
  const originalEnv = process.env;
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@friggframework/devtools",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.667.f74cf3b.0",
4
+ "version": "2.0.0--canary.710.7cfcf12.0",
5
5
  "bin": {
6
6
  "frigg": "./frigg-cli/index.js"
7
7
  },
8
8
  "files": [
9
9
  "frigg-cli/",
10
+ "frigg-cli/templates/",
10
11
  "infrastructure/",
11
12
  "migrations/",
12
13
  "management-ui/dist/",
@@ -18,6 +19,7 @@
18
19
  "@aws-sdk/client-cloudformation": "^3.705.0",
19
20
  "@aws-sdk/client-ec2": "^3.835.0",
20
21
  "@aws-sdk/client-kms": "^3.835.0",
22
+ "@aws-sdk/client-lambda": "^3.714.0",
21
23
  "@aws-sdk/client-rds": "^3.906.0",
22
24
  "@aws-sdk/client-s3": "^3.917.0",
23
25
  "@aws-sdk/client-secrets-manager": "^3.906.0",
@@ -26,9 +28,9 @@
26
28
  "@babel/eslint-parser": "^7.18.9",
27
29
  "@babel/parser": "^7.25.3",
28
30
  "@babel/traverse": "^7.25.3",
29
- "@friggframework/core": "2.0.0--canary.667.f74cf3b.0",
30
- "@friggframework/schemas": "2.0.0--canary.667.f74cf3b.0",
31
- "@friggframework/test": "2.0.0--canary.667.f74cf3b.0",
31
+ "@friggframework/core": "2.0.0--canary.710.7cfcf12.0",
32
+ "@friggframework/schemas": "2.0.0--canary.710.7cfcf12.0",
33
+ "@friggframework/test": "2.0.0--canary.710.7cfcf12.0",
32
34
  "@hapi/boom": "^10.0.1",
33
35
  "@inquirer/prompts": "^5.3.8",
34
36
  "axios": "^1.18.0",
@@ -56,12 +58,12 @@
56
58
  "validate-npm-package-name": "^5.0.0"
57
59
  },
58
60
  "devDependencies": {
59
- "@friggframework/eslint-config": "2.0.0--canary.667.f74cf3b.0",
60
- "@friggframework/prettier-config": "2.0.0--canary.667.f74cf3b.0",
61
+ "@friggframework/eslint-config": "2.0.0--canary.710.7cfcf12.0",
62
+ "@friggframework/prettier-config": "2.0.0--canary.710.7cfcf12.0",
61
63
  "aws-sdk-client-mock": "^4.1.0",
62
64
  "aws-sdk-client-mock-jest": "^4.1.0",
63
65
  "jest": "^30.1.3",
64
- "osls": "^3.58.0",
66
+ "osls": "^3.78.0",
65
67
  "prettier": "^2.7.1",
66
68
  "serverless-dotenv-plugin": "^6.0.0",
67
69
  "serverless-esbuild": "^1.54.3",
@@ -89,5 +91,5 @@
89
91
  "publishConfig": {
90
92
  "access": "public"
91
93
  },
92
- "gitHead": "f74cf3b1f04195508cb0ee6d4086b1cb2d70d913"
94
+ "gitHead": "7cfcf1267a412053163b99b7f9a123f7e4e1bde3"
93
95
  }
@@ -1,158 +0,0 @@
1
- const { Command } = require('commander');
2
- const { installCommand } = require('./index');
3
- const { validatePackageExists } = require('./install-command/validate-package');
4
- const { findNearestBackendPackageJson, validateBackendPath } = require('@friggframework/core');
5
- const { installPackage } = require('./install-command/install-package');
6
- const { createIntegrationFile } = require('./install-command/integration-file');
7
- const { updateBackendJsFile } = require('./install-command/backend-js');
8
- const { commitChanges } = require('./install-command/commit-changes');
9
- const { logInfo, logError } = require('./install-command/logger');
10
-
11
- describe('CLI Command Tests', () => {
12
- it('should successfully install an API module when all steps complete without errors', async () => {
13
- const mockApiModuleName = 'testModule';
14
- const mockPackageName = `@friggframework/api-module-${mockApiModuleName}`;
15
- const mockBackendPath = '/mock/backend/path';
16
-
17
- jest.mock('./install-command/validate-package', () => ({
18
- validatePackageExists: jest.fn().mockResolvedValue(true),
19
- }));
20
- jest.mock('./utils/backend-path', () => ({
21
- findNearestBackendPackageJson: jest
22
- .fn()
23
- .mockReturnValue(mockBackendPath),
24
- validateBackendPath: jest.fn().mockReturnValue(true),
25
- }));
26
- jest.mock('./install-command/install-package', () => ({
27
- installPackage: jest.fn().mockReturnValue(true),
28
- }));
29
- jest.mock('./install-command/integration-file', () => ({
30
- createIntegrationFile: jest.fn().mockReturnValue(true),
31
- }));
32
- jest.mock('./install-command/backend-js', () => ({
33
- updateBackendJsFile: jest.fn().mockReturnValue(true),
34
- }));
35
- jest.mock('./install-command/commit-changes', () => ({
36
- commitChanges: jest.fn().mockReturnValue(true),
37
- }));
38
- jest.mock('./install-command/logger', () => ({
39
- logInfo: jest.fn(),
40
- logError: jest.fn(),
41
- }));
42
-
43
- const program = new Command();
44
- program
45
- .command('install <apiModuleName>')
46
- .description('Install an API module')
47
- .action(installCommand);
48
-
49
- await program.parseAsync(['node', 'install', mockApiModuleName]);
50
-
51
- expect(validatePackageExists).toHaveBeenCalledWith(mockPackageName);
52
- expect(findNearestBackendPackageJson).toHaveBeenCalled();
53
- expect(validateBackendPath).toHaveBeenCalledWith(mockBackendPath);
54
- expect(installPackage).toHaveBeenCalledWith(
55
- mockBackendPath,
56
- mockPackageName
57
- );
58
- expect(createIntegrationFile).toHaveBeenCalledWith(
59
- mockBackendPath,
60
- mockApiModuleName
61
- );
62
- expect(updateBackendJsFile).toHaveBeenCalledWith(
63
- mockBackendPath,
64
- mockApiModuleName
65
- );
66
- expect(commitChanges).toHaveBeenCalledWith(
67
- mockBackendPath,
68
- mockApiModuleName
69
- );
70
- expect(logInfo).toHaveBeenCalledWith(
71
- `Successfully installed ${mockPackageName} and updated the project.`
72
- );
73
- });
74
-
75
- it('should log an error and exit with code 1 if the package does not exist', async () => {
76
- const mockExit = jest
77
- .spyOn(process, 'exit')
78
- .mockImplementation(() => {});
79
- const mockLogError = jest
80
- .spyOn(require('./install-command/logger'), 'logError')
81
- .mockImplementation(() => {});
82
- const mockValidatePackageExists = jest
83
- .spyOn(
84
- require('./install-command/validate-package'),
85
- 'validatePackageExists'
86
- )
87
- .mockImplementation(() => {
88
- throw new Error('Package not found');
89
- });
90
-
91
- const program = new Command();
92
- program
93
- .command('install <apiModuleName>')
94
- .description('Install an API module')
95
- .action(installCommand);
96
-
97
- await program.parseAsync(['node', 'install', 'nonexistent-package']);
98
-
99
- expect(mockValidatePackageExists).toHaveBeenCalledWith(
100
- '@friggframework/api-module-nonexistent-package'
101
- );
102
- expect(mockLogError).toHaveBeenCalledWith(
103
- 'An error occurred:',
104
- expect.any(Error)
105
- );
106
- expect(mockExit).toHaveBeenCalledWith(1);
107
-
108
- mockExit.mockRestore();
109
- mockLogError.mockRestore();
110
- mockValidatePackageExists.mockRestore();
111
- });
112
-
113
- it('should log an error and exit with code 1 if the backend path is invalid', async () => {
114
- const mockLogError = jest
115
- .spyOn(require('./install-command/logger'), 'logError')
116
- .mockImplementation(() => {});
117
- const mockProcessExit = jest
118
- .spyOn(process, 'exit')
119
- .mockImplementation(() => {});
120
- const mockValidatePackageExists = jest
121
- .spyOn(
122
- require('./install-command/validate-package'),
123
- 'validatePackageExists'
124
- )
125
- .mockResolvedValue(true);
126
- const mockFindNearestBackendPackageJson = jest
127
- .spyOn(
128
- require('./utils/backend-path'),
129
- 'findNearestBackendPackageJson'
130
- )
131
- .mockReturnValue('/invalid/path');
132
- const mockValidateBackendPath = jest
133
- .spyOn(require('./utils/backend-path'), 'validateBackendPath')
134
- .mockImplementation(() => {
135
- throw new Error('Invalid backend path');
136
- });
137
-
138
- const program = new Command();
139
- program
140
- .command('install <apiModuleName>')
141
- .description('Install an API module')
142
- .action(installCommand);
143
-
144
- await program.parseAsync(['node', 'install', 'test-module']);
145
-
146
- expect(mockLogError).toHaveBeenCalledWith(
147
- 'An error occurred:',
148
- expect.any(Error)
149
- );
150
- expect(mockProcessExit).toHaveBeenCalledWith(1);
151
-
152
- mockLogError.mockRestore();
153
- mockProcessExit.mockRestore();
154
- mockValidatePackageExists.mockRestore();
155
- mockFindNearestBackendPackageJson.mockRestore();
156
- mockValidateBackendPath.mockRestore();
157
- });
158
- });
@@ -1,281 +0,0 @@
1
- /**
2
- * Management API ↔ API Gateway route coverage
3
- *
4
- * The Management API is an Express app (core's createIntegrationRouter)
5
- * served by the `auth` Lambda. API Gateway HTTP APIs have no implicit
6
- * catch-all: a request whose path matches no declared route gets a gateway
7
- * 404 and never reaches Express. So every route the integration router
8
- * registers must be covered by an httpApi event on the `auth` function, and
9
- * no more-specific route on another function may shadow it.
10
- *
11
- * The Express routes are read from the live router (not a hard-coded list),
12
- * so a route added to core later fails this test until the gateway routes
13
- * are updated alongside it.
14
- */
15
-
16
- // Avoid AWS calls: hand the builders a fixed discovery result.
17
- jest.mock('../domains/shared/resource-discovery', () => {
18
- const actual = jest.requireActual('../domains/shared/resource-discovery');
19
- return {
20
- ...actual,
21
- gatherDiscoveredResources: jest.fn().mockResolvedValue({
22
- defaultVpcId: 'vpc-123456',
23
- vpcCidr: '172.31.0.0/16',
24
- defaultSecurityGroupId: 'sg-123456',
25
- privateSubnetId1: 'subnet-123456',
26
- privateSubnetId2: 'subnet-789012',
27
- publicSubnetId1: 'subnet-public-1',
28
- publicSubnetId2: 'subnet-public-2',
29
- defaultRouteTableId: 'rtb-123456',
30
- defaultKmsKeyId:
31
- 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012',
32
- existingNatGatewayId: 'nat-default123',
33
- auroraClusterEndpoint:
34
- 'test-cluster.cluster-abc123.us-east-1.rds.amazonaws.com',
35
- auroraPort: 5432,
36
- auroraEngine: 'aurora-postgresql',
37
- }),
38
- };
39
- });
40
-
41
- // createIntegrationRouter loads the app definition from the consuming
42
- // backend; give it an empty one so the router can be built in isolation.
43
- jest.mock('@friggframework/core/handlers/app-definition-loader', () => ({
44
- loadAppDefinition: () => ({ integrations: [], userConfig: {} }),
45
- }));
46
-
47
- const { composeServerlessDefinition } = require('../infrastructure-composer');
48
-
49
- // Routes the auth Lambda's handler (core/handlers/routers/auth.js) adds on
50
- // top of createIntegrationRouter().
51
- const AUTH_HANDLER_EXTRA_ROUTES = [
52
- { method: 'GET', path: '/api/integrations/redirect/:appId' },
53
- ];
54
-
55
- function getIntegrationRouterRoutes() {
56
- const { createIntegrationRouter } = require('@friggframework/core');
57
- // The repository factories pick an adapter from DB_TYPE (or the backend's
58
- // app definition, which doesn't exist here). Nothing connects.
59
- const previousDbType = process.env.DB_TYPE;
60
- process.env.DB_TYPE = 'postgresql';
61
- let app;
62
- try {
63
- app = createIntegrationRouter();
64
- } finally {
65
- if (previousDbType === undefined) delete process.env.DB_TYPE;
66
- else process.env.DB_TYPE = previousDbType;
67
- }
68
- const stack = (app._router || app.router).stack;
69
- const routes = [];
70
- for (const layer of stack) {
71
- if (!layer.route) continue;
72
- for (const method of Object.keys(layer.route.methods)) {
73
- routes.push({
74
- method: method === '_all' ? 'ANY' : method.toUpperCase(),
75
- path: layer.route.path,
76
- });
77
- }
78
- }
79
- return routes;
80
- }
81
-
82
- function getGatewayRoutes(definition) {
83
- const routes = [];
84
- for (const [functionName, fn] of Object.entries(definition.functions)) {
85
- for (const event of fn.events || []) {
86
- if (!event.httpApi) continue;
87
- routes.push({
88
- functionName,
89
- method: String(event.httpApi.method).toUpperCase(),
90
- path: event.httpApi.path,
91
- });
92
- }
93
- }
94
- return routes;
95
- }
96
-
97
- const segmentsOf = (p) => p.split('/').filter(Boolean);
98
-
99
- // Turn an Express path into a concrete request path, e.g.
100
- // /api/entities/:entityId/options -> /api/entities/sample-entityId/options
101
- const toConcretePath = (expressPath) =>
102
- expressPath.replace(/:([A-Za-z0-9_]+)/g, 'sample-$1');
103
-
104
- /**
105
- * HTTP API path matching: literal segments match exactly, {param} matches
106
- * one segment, a trailing {proxy+} greedily matches one or more segments.
107
- * Returns null on no match, otherwise a specificity descriptor.
108
- */
109
- function matchGatewayPath(gatewayPath, requestPath) {
110
- const g = segmentsOf(gatewayPath);
111
- const r = segmentsOf(requestPath);
112
- let literals = 0;
113
- for (let i = 0; i < g.length; i++) {
114
- const seg = g[i];
115
- if (/^\{[^}]+\+\}$/.test(seg)) {
116
- if (i !== g.length - 1 || r.length <= i) return null;
117
- return { greedy: true, literals, prefixLength: i };
118
- }
119
- if (i >= r.length) return null;
120
- if (/^\{[^}]+\}$/.test(seg)) continue;
121
- if (seg !== r[i]) return null;
122
- literals++;
123
- }
124
- if (g.length !== r.length) return null;
125
- return { greedy: false, literals, prefixLength: g.length };
126
- }
127
-
128
- /**
129
- * Select the route API Gateway would invoke: a non-greedy match beats a
130
- * greedy one, then more literal segments, then the longer greedy prefix,
131
- * then an explicit method beats ANY.
132
- */
133
- function selectGatewayRoute(gatewayRoutes, method, requestPath) {
134
- const candidates = gatewayRoutes
135
- .filter(
136
- (r) => r.method === 'ANY' || method === 'ANY' || r.method === method
137
- )
138
- .map((r) => ({
139
- route: r,
140
- match: matchGatewayPath(r.path, requestPath),
141
- }))
142
- .filter((c) => c.match);
143
- candidates.sort(
144
- (a, b) =>
145
- Number(a.match.greedy) - Number(b.match.greedy) ||
146
- b.match.literals - a.match.literals ||
147
- b.match.prefixLength - a.match.prefixLength ||
148
- Number(a.route.method === 'ANY') - Number(b.route.method === 'ANY')
149
- );
150
- return candidates.length ? candidates[0].route : null;
151
- }
152
-
153
- describe('Management API routes are reachable through API Gateway', () => {
154
- let gatewayRoutes;
155
- let managementRoutes;
156
- const originalArgv = process.argv;
157
-
158
- beforeAll(async () => {
159
- process.argv = ['node', 'test'];
160
- process.env.AWS_REGION = 'us-east-1';
161
- // The builders narrate their progress; keep the test output quiet.
162
- const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
163
- const warnSpy = jest
164
- .spyOn(console, 'warn')
165
- .mockImplementation(() => {});
166
- try {
167
- const definition = await composeServerlessDefinition({
168
- name: 'route-coverage-app',
169
- provider: 'aws',
170
- usePrismaLambdaLayer: false,
171
- database: { postgres: { enable: true } },
172
- websockets: { enable: true },
173
- adminScripts: [
174
- class ExampleScript {
175
- static Definition = { name: 'example-script' };
176
- },
177
- ],
178
- admin: { includeBuiltinReports: true },
179
- integrations: [
180
- {
181
- Definition: {
182
- name: 'acme',
183
- webhooks: true,
184
- extensions: {
185
- inbound: {
186
- extension: {
187
- routes: [
188
- { path: '/events', method: 'POST' },
189
- ],
190
- },
191
- },
192
- },
193
- },
194
- },
195
- // Integration names share the /api/ namespace with the
196
- // Management API; make sure they don't shadow it.
197
- { Definition: { name: 'entities' } },
198
- ],
199
- });
200
- gatewayRoutes = getGatewayRoutes(definition);
201
- } finally {
202
- logSpy.mockRestore();
203
- warnSpy.mockRestore();
204
- }
205
- managementRoutes = [
206
- ...getIntegrationRouterRoutes(),
207
- ...AUTH_HANDLER_EXTRA_ROUTES,
208
- ];
209
- });
210
-
211
- afterAll(() => {
212
- process.argv = originalArgv;
213
- delete process.env.AWS_REGION;
214
- });
215
-
216
- it('reads the Management API routes from the core integration router', () => {
217
- const paths = managementRoutes.map((r) => r.path);
218
- expect(paths).toEqual(
219
- expect.arrayContaining([
220
- '/api/integrations',
221
- '/api/authorize',
222
- '/api/entity',
223
- '/api/entity/options/:credentialId',
224
- '/api/entities/:entityId',
225
- ])
226
- );
227
- });
228
-
229
- it('routes every Management API route to the auth function', () => {
230
- const unreachable = managementRoutes
231
- .map(({ method, path: expressPath }) => {
232
- const requestPath = toConcretePath(expressPath);
233
- const selected = selectGatewayRoute(
234
- gatewayRoutes,
235
- method,
236
- requestPath
237
- );
238
- return {
239
- route: `${method} ${expressPath}`,
240
- reachedBy: selected
241
- ? `${selected.method} ${selected.path} -> ${selected.functionName}`
242
- : 'no API Gateway route',
243
- ok: selected && selected.functionName === 'auth',
244
- };
245
- })
246
- .filter((r) => !r.ok)
247
- .map(({ route, reachedBy }) => `${route} (${reachedBy})`);
248
-
249
- expect(unreachable).toEqual([]);
250
- });
251
-
252
- it.each([
253
- ['GET', '/api/v2/reports', 'reportRouter'],
254
- ['POST', '/api/v2/reports/daily/run', 'reportRouter'],
255
- ['GET', '/admin/scripts/example-script', 'adminScriptRouter'],
256
- ['POST', '/api/acme-integration/webhooks', 'acmeWebhook'],
257
- ['POST', '/api/acme-integration/inbound/events', 'acme__inbound'],
258
- ['GET', '/api/acme-integration/custom', 'acme'],
259
- ['GET', '/api/entities-integration/custom', 'entities'],
260
- ['POST', '/user/login', 'user'],
261
- ['GET', '/health/ready', 'health'],
262
- ])('leaves %s %s on %s', (method, requestPath, functionName) => {
263
- const selected = selectGatewayRoute(gatewayRoutes, method, requestPath);
264
- expect(selected && selected.functionName).toBe(functionName);
265
- });
266
-
267
- it('declares no method + path pair on more than one function', () => {
268
- const seen = new Map();
269
- const duplicates = [];
270
- for (const r of gatewayRoutes) {
271
- const key = `${r.method} ${r.path}`;
272
- if (seen.has(key) && seen.get(key) !== r.functionName) {
273
- duplicates.push(
274
- `${key}: ${seen.get(key)} and ${r.functionName}`
275
- );
276
- }
277
- seen.set(key, r.functionName);
278
- }
279
- expect(duplicates).toEqual([]);
280
- });
281
- });