@friggframework/devtools 2.0.0--canary.686.20eda6e.0 → 2.0.0--canary.710.9045bbc.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 (80) 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/build-command/index.js +1 -32
  10. package/frigg-cli/deploy-command/index.js +2 -50
  11. package/frigg-cli/doctor-command/index.js +0 -7
  12. package/frigg-cli/generate-command/index.js +1 -0
  13. package/frigg-cli/generate-iam-command.js +1 -7
  14. package/frigg-cli/index.js +9 -4
  15. package/frigg-cli/init-command/backend-first-handler.js +397 -554
  16. package/frigg-cli/init-command/deployment-modes.js +7 -0
  17. package/frigg-cli/init-command/index.js +82 -35
  18. package/frigg-cli/init-command/safe-path.js +58 -0
  19. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  20. package/frigg-cli/install-command/app-definition.js +174 -0
  21. package/frigg-cli/install-command/commit-changes.js +40 -8
  22. package/frigg-cli/install-command/environment-variables.js +15 -0
  23. package/frigg-cli/install-command/index.js +96 -21
  24. package/frigg-cli/install-command/install-package.js +77 -4
  25. package/frigg-cli/install-command/integration-file.js +20 -11
  26. package/frigg-cli/install-command/resolve-module.js +69 -0
  27. package/frigg-cli/install-command/template.js +102 -75
  28. package/frigg-cli/install-command/validate-package.js +36 -4
  29. package/frigg-cli/package.json +1 -1
  30. package/frigg-cli/repair-command/index.js +0 -7
  31. package/frigg-cli/start-command/index.js +0 -58
  32. package/frigg-cli/templates/backend/README.md +267 -0
  33. package/frigg-cli/templates/backend/env.example +20 -0
  34. package/frigg-cli/templates/backend/gitignore +10 -0
  35. package/frigg-cli/templates/backend/index.js +114 -0
  36. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  37. package/frigg-cli/test/init-command.test.js +9 -2
  38. package/infrastructure/README.md +2 -4
  39. package/infrastructure/__tests__/postgres-config.test.js +241 -835
  40. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  41. package/infrastructure/__tests__/template-generation.test.js +33 -12
  42. package/infrastructure/create-frigg-infrastructure.js +0 -14
  43. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
  44. package/infrastructure/domains/admin-scripts/admin-script-builder.js +6 -2
  45. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +30 -0
  46. package/infrastructure/domains/database/aurora-builder.js +13 -2
  47. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  48. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  49. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  50. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  51. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  52. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  53. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  54. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  55. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  56. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  57. package/infrastructure/domains/networking/vpc-builder.test.js +32 -13
  58. package/infrastructure/domains/parameters/offload-utils.js +0 -1
  59. package/infrastructure/domains/security/iam-generator.js +112 -5
  60. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  61. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  62. package/infrastructure/domains/shared/environment-builder.js +1 -12
  63. package/infrastructure/domains/shared/environment-builder.test.js +0 -20
  64. package/infrastructure/domains/shared/types/app-definition.js +1 -15
  65. package/infrastructure/domains/shared/utilities/base-definition-factory.js +17 -30
  66. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +22 -85
  67. package/infrastructure/infrastructure-composer.test.js +268 -801
  68. package/infrastructure/scripts/build-prisma-layer.js +5 -32
  69. package/infrastructure/scripts/build-prisma-layer.test.js +28 -42
  70. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  71. package/package.json +10 -8
  72. package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +0 -140
  73. package/frigg-cli/index.test.js +0 -158
  74. package/frigg-cli/utils/provider-helper.js +0 -80
  75. package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +0 -64
  76. package/infrastructure/__tests__/management-api-gateway-routes.test.js +0 -335
  77. package/infrastructure/integration.test.js +0 -381
  78. package/infrastructure/provider-build.js +0 -119
  79. package/test/npm-install-guard.js +0 -104
  80. package/test/npm-install-guard.test.js +0 -53
@@ -1,381 +0,0 @@
1
- const fs = require('fs');
2
- const { composeServerlessDefinition } = require('./serverless-template');
3
- const { AWSDiscovery } = require('./aws-discovery');
4
- const { BuildTimeDiscovery } = require('./build-time-discovery');
5
- const FriggServerlessPlugin = require('../../serverless-plugin/index');
6
-
7
- // Integration tests for end-to-end AWS discovery and serverless config generation
8
- describe('VPC/KMS/SSM Integration Tests', () => {
9
- let mockAWSDiscovery;
10
- let buildTimeDiscovery;
11
-
12
- const mockAWSResources = {
13
- defaultVpcId: 'vpc-12345678',
14
- defaultSecurityGroupId: 'sg-12345678',
15
- privateSubnetId1: 'subnet-private-1',
16
- privateSubnetId2: 'subnet-private-2',
17
- privateRouteTableId: 'rtb-12345678',
18
- defaultKmsKeyId: 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
19
- };
20
-
21
- beforeEach(() => {
22
- // Mock AWSDiscovery to return consistent test data
23
- mockAWSDiscovery = {
24
- discoverResources: jest.fn().mockResolvedValue(mockAWSResources),
25
- findDefaultVpc: jest.fn().mockResolvedValue({ VpcId: mockAWSResources.defaultVpcId }),
26
- findPrivateSubnets: jest.fn().mockResolvedValue([
27
- { SubnetId: mockAWSResources.privateSubnetId1 },
28
- { SubnetId: mockAWSResources.privateSubnetId2 }
29
- ]),
30
- findDefaultSecurityGroup: jest.fn().mockResolvedValue({ GroupId: mockAWSResources.defaultSecurityGroupId }),
31
- findPrivateRouteTable: jest.fn().mockResolvedValue({ RouteTableId: mockAWSResources.privateRouteTableId }),
32
- findDefaultKmsKey: jest.fn().mockResolvedValue(mockAWSResources.defaultKmsKeyId)
33
- };
34
-
35
- jest.doMock('./aws-discovery', () => ({
36
- AWSDiscovery: jest.fn(() => mockAWSDiscovery)
37
- }));
38
-
39
- buildTimeDiscovery = new BuildTimeDiscovery('us-east-1');
40
- });
41
-
42
- afterEach(() => {
43
- jest.clearAllMocks();
44
- jest.resetModules();
45
- });
46
-
47
- describe('End-to-End Serverless Configuration Generation', () => {
48
- it('should generate complete serverless config with VPC, KMS, and SSM enabled', async () => {
49
- const appDefinition = {
50
- name: 'test-frigg-app',
51
- vpc: { enable: true },
52
- encryption: { fieldLevelEncryptionMethod: 'kms' },
53
- ssm: { enable: true },
54
- integrations: [{
55
- Definition: {
56
- name: 'testIntegration'
57
- }
58
- }]
59
- };
60
-
61
- // Run AWS discovery
62
- const discoveredResources = await mockAWSDiscovery.discoverResources();
63
-
64
- // Set environment variables as would happen in build
65
- process.env.AWS_DISCOVERY_VPC_ID = discoveredResources.defaultVpcId;
66
- process.env.AWS_DISCOVERY_SECURITY_GROUP_ID = discoveredResources.defaultSecurityGroupId;
67
- process.env.AWS_DISCOVERY_SUBNET_ID_1 = discoveredResources.privateSubnetId1;
68
- process.env.AWS_DISCOVERY_SUBNET_ID_2 = discoveredResources.privateSubnetId2;
69
- process.env.AWS_DISCOVERY_ROUTE_TABLE_ID = discoveredResources.privateRouteTableId;
70
- process.env.AWS_DISCOVERY_KMS_KEY_ID =discoveredResources.defaultKmsKeyId;
71
-
72
- // Generate serverless configuration
73
- const serverlessConfig = composeServerlessDefinition(appDefinition);
74
-
75
- // Verify VPC configuration
76
- expect(serverlessConfig.provider.vpc).toBe('${self:custom.vpc.${self:provider.stage}}');
77
- expect(serverlessConfig.custom.vpc).toEqual({
78
- '${self:provider.stage}': {
79
- securityGroupIds: ['${env:AWS_DISCOVERY_SECURITY_GROUP_ID}'],
80
- subnetIds: [
81
- '${env:AWS_DISCOVERY_SUBNET_ID_1}',
82
- '${env:AWS_DISCOVERY_SUBNET_ID_2}'
83
- ]
84
- }
85
- });
86
-
87
- // Verify VPC Endpoint
88
- expect(serverlessConfig.resources.Resources.VPCEndpointS3).toEqual({
89
- Type: 'AWS::EC2::VPCEndpoint',
90
- Properties: {
91
- VpcId: '${env:AWS_DISCOVERY_VPC_ID}',
92
- ServiceName: 'com.amazonaws.${self:provider.region}.s3',
93
- VpcEndpointType: 'Gateway',
94
- RouteTableIds: ['${env:AWS_DISCOVERY_ROUTE_TABLE_ID}']
95
- }
96
- });
97
-
98
- // Verify KMS configuration
99
- expect(serverlessConfig.plugins).toContain('serverless-kms-grants');
100
- expect(serverlessConfig.provider.environment.KMS_KEY_ARN).toBe('${self:custom.kmsGrants.kmsKeyId}');
101
- expect(serverlessConfig.custom.kmsGrants).toEqual({
102
- kmsKeyId: '${env:AWS_DISCOVERY_KMS_KEY_ID}'
103
- });
104
-
105
- // Verify KMS IAM permissions
106
- const kmsPermission = serverlessConfig.provider.iamRoleStatements.find(
107
- statement => statement.Action.includes('kms:GenerateDataKey')
108
- );
109
- expect(kmsPermission).toBeDefined();
110
-
111
- // Verify SSM configuration (enabled without offload markers -> broad grant only)
112
- expect(serverlessConfig.provider.layers).toBeUndefined();
113
- expect(serverlessConfig.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
114
-
115
- // Verify SSM IAM permissions
116
- const ssmPermission = serverlessConfig.provider.iamRoleStatements.find(
117
- statement => statement.Action.includes('ssm:GetParameter')
118
- );
119
- expect(ssmPermission).toBeDefined();
120
-
121
- // Verify integration resources
122
- expect(serverlessConfig.functions.testIntegration).toBeDefined();
123
- expect(serverlessConfig.functions.testIntegrationQueueWorker).toBeDefined();
124
- expect(serverlessConfig.resources.Resources.TestIntegrationQueue).toBeDefined();
125
-
126
- // Clean up environment
127
- delete process.env.AWS_DISCOVERY_VPC_ID;
128
- delete process.env.AWS_DISCOVERY_SECURITY_GROUP_ID;
129
- delete process.env.AWS_DISCOVERY_SUBNET_ID_1;
130
- delete process.env.AWS_DISCOVERY_SUBNET_ID_2;
131
- delete process.env.AWS_DISCOVERY_ROUTE_TABLE_ID;
132
- delete process.env.AWS_DISCOVERY_KMS_KEY_ID;
133
- });
134
-
135
- it('should generate config with only VPC enabled', async () => {
136
- const appDefinition = {
137
- name: 'vpc-only-app',
138
- vpc: { enable: true },
139
- integrations: []
140
- };
141
-
142
- process.env.AWS_DISCOVERY_VPC_ID = mockAWSResources.defaultVpcId;
143
- process.env.AWS_DISCOVERY_SECURITY_GROUP_ID = mockAWSResources.defaultSecurityGroupId;
144
- process.env.AWS_DISCOVERY_SUBNET_ID_1 = mockAWSResources.privateSubnetId1;
145
- process.env.AWS_DISCOVERY_SUBNET_ID_2 = mockAWSResources.privateSubnetId2;
146
- process.env.AWS_DISCOVERY_ROUTE_TABLE_ID = mockAWSResources.privateRouteTableId;
147
-
148
- const serverlessConfig = composeServerlessDefinition(appDefinition);
149
-
150
- // Should have VPC config
151
- expect(serverlessConfig.provider.vpc).toBeDefined();
152
- expect(serverlessConfig.custom.vpc).toBeDefined();
153
- expect(serverlessConfig.resources.Resources.VPCEndpointS3).toBeDefined();
154
-
155
- // Should not have KMS config
156
- expect(serverlessConfig.plugins).not.toContain('serverless-kms-grants');
157
- expect(serverlessConfig.provider.environment.KMS_KEY_ARN).toBeUndefined();
158
-
159
- // Should not have SSM config
160
- expect(serverlessConfig.provider.layers).toBeUndefined();
161
- expect(serverlessConfig.provider.environment.SSM_PARAMETER_PREFIX).toBeUndefined();
162
-
163
- // Clean up
164
- delete process.env.AWS_DISCOVERY_VPC_ID;
165
- delete process.env.AWS_DISCOVERY_SECURITY_GROUP_ID;
166
- delete process.env.AWS_DISCOVERY_SUBNET_ID_1;
167
- delete process.env.AWS_DISCOVERY_SUBNET_ID_2;
168
- delete process.env.AWS_DISCOVERY_ROUTE_TABLE_ID;
169
- });
170
-
171
- it('should generate config with only KMS enabled', async () => {
172
- const appDefinition = {
173
- name: 'kms-only-app',
174
- encryption: { fieldLevelEncryptionMethod: 'kms' },
175
- integrations: []
176
- };
177
-
178
- process.env.AWS_DISCOVERY_KMS_KEY_ID =mockAWSResources.defaultKmsKeyId;
179
-
180
- const serverlessConfig = composeServerlessDefinition(appDefinition);
181
-
182
- // Should have KMS config
183
- expect(serverlessConfig.plugins).toContain('serverless-kms-grants');
184
- expect(serverlessConfig.custom.kmsGrants).toBeDefined();
185
-
186
- // Should not have VPC config
187
- expect(serverlessConfig.provider.vpc).toBeUndefined();
188
-
189
- // Should not have SSM config
190
- expect(serverlessConfig.provider.layers).toBeUndefined();
191
-
192
- delete process.env.AWS_DISCOVERY_KMS_KEY_ID;
193
- });
194
- });
195
-
196
- describe('Plugin Integration', () => {
197
- it('should trigger AWS discovery through serverless plugin', async () => {
198
- const mockServerless = {
199
- cli: { log: jest.fn() },
200
- service: {
201
- provider: {
202
- name: 'aws',
203
- region: 'us-east-1',
204
- vpc: '${self:custom.vpc.${self:provider.stage}}'
205
- },
206
- plugins: ['serverless-kms-grants'],
207
- custom: {},
208
- functions: {}
209
- },
210
- processedInput: { commands: [] },
211
- getProvider: jest.fn(() => ({})),
212
- extendConfiguration: jest.fn()
213
- };
214
-
215
- const plugin = new FriggServerlessPlugin(mockServerless, { stage: 'test' });
216
-
217
- // Mock BuildTimeDiscovery
218
- const mockBuildTimeDiscovery = {
219
- preBuildHook: jest.fn().mockResolvedValue(mockAWSResources)
220
- };
221
-
222
- jest.doMock('./build-time-discovery', () => ({
223
- BuildTimeDiscovery: jest.fn(() => mockBuildTimeDiscovery)
224
- }));
225
-
226
- // Test the beforePackageInitialize hook
227
- await plugin.beforePackageInitialize();
228
-
229
- expect(mockBuildTimeDiscovery.preBuildHook).toHaveBeenCalledWith(
230
- expect.objectContaining({
231
- vpc: { enable: true },
232
- encryption: { fieldLevelEncryptionMethod: 'kms' }
233
- }),
234
- 'us-east-1'
235
- );
236
-
237
- expect(mockServerless.cli.log).toHaveBeenCalledWith('AWS discovery completed successfully');
238
- });
239
-
240
- it('should handle plugin discovery failure gracefully', async () => {
241
- const mockServerless = {
242
- cli: { log: jest.fn() },
243
- service: {
244
- provider: {
245
- name: 'aws',
246
- region: 'us-east-1',
247
- vpc: '${self:custom.vpc}'
248
- },
249
- plugins: [],
250
- custom: {},
251
- functions: {}
252
- },
253
- processedInput: { commands: [] },
254
- getProvider: jest.fn(() => ({})),
255
- extendConfiguration: jest.fn()
256
- };
257
-
258
- const plugin = new FriggServerlessPlugin(mockServerless, { stage: 'test' });
259
-
260
- // Mock BuildTimeDiscovery to fail
261
- const mockBuildTimeDiscovery = {
262
- preBuildHook: jest.fn().mockRejectedValue(new Error('AWS API Error'))
263
- };
264
-
265
- jest.doMock('./build-time-discovery', () => ({
266
- BuildTimeDiscovery: jest.fn(() => mockBuildTimeDiscovery)
267
- }));
268
-
269
- await plugin.beforePackageInitialize();
270
-
271
- expect(mockServerless.cli.log).toHaveBeenCalledWith('AWS discovery failed, continuing with deployment...');
272
- expect(mockServerless.cli.log).toHaveBeenCalledWith('Using fallback values for AWS resources');
273
-
274
- // Verify fallback values are set
275
- expect(process.env.AWS_DISCOVERY_VPC_ID).toBe('vpc-fallback');
276
- expect(process.env.AWS_DISCOVERY_KMS_KEY_ID).toBe('arn:aws:kms:*:*:key/*');
277
- });
278
- });
279
-
280
- describe('Template Variable Replacement', () => {
281
- it('should replace environment variable placeholders with actual values', () => {
282
- const template = `
283
- provider:
284
- vpc:
285
- securityGroupIds:
286
- - \${env:AWS_DISCOVERY_SECURITY_GROUP_ID}
287
- subnetIds:
288
- - \${env:AWS_DISCOVERY_SUBNET_ID_1}
289
- - \${env:AWS_DISCOVERY_SUBNET_ID_2}
290
- environment:
291
- KMS_KEY_ARN: \${env:AWS_DISCOVERY_KMS_KEY_ID}
292
- resources:
293
- VPCEndpoint:
294
- Properties:
295
- VpcId: \${env:AWS_DISCOVERY_VPC_ID}
296
- `;
297
-
298
- // Set environment variables
299
- process.env.AWS_DISCOVERY_VPC_ID = mockAWSResources.defaultVpcId;
300
- process.env.AWS_DISCOVERY_SECURITY_GROUP_ID = mockAWSResources.defaultSecurityGroupId;
301
- process.env.AWS_DISCOVERY_SUBNET_ID_1 = mockAWSResources.privateSubnetId1;
302
- process.env.AWS_DISCOVERY_SUBNET_ID_2 = mockAWSResources.privateSubnetId2;
303
- process.env.AWS_DISCOVERY_KMS_KEY_ID =mockAWSResources.defaultKmsKeyId;
304
-
305
- // In a real deployment, serverless framework would resolve these environment variables
306
- // For testing, we can verify the placeholders are correctly formatted
307
- expect(template).toContain('${env:AWS_DISCOVERY_VPC_ID}');
308
- expect(template).toContain('${env:AWS_DISCOVERY_SECURITY_GROUP_ID}');
309
- expect(template).toContain('${env:AWS_DISCOVERY_SUBNET_ID_1}');
310
- expect(template).toContain('${env:AWS_DISCOVERY_SUBNET_ID_2}');
311
- expect(template).toContain('${env:AWS_DISCOVERY_KMS_KEY_ID}');
312
-
313
- // Clean up
314
- delete process.env.AWS_DISCOVERY_VPC_ID;
315
- delete process.env.AWS_DISCOVERY_SECURITY_GROUP_ID;
316
- delete process.env.AWS_DISCOVERY_SUBNET_ID_1;
317
- delete process.env.AWS_DISCOVERY_SUBNET_ID_2;
318
- delete process.env.AWS_DISCOVERY_KMS_KEY_ID;
319
- });
320
- });
321
-
322
- describe('Error Scenarios', () => {
323
- it('should handle AWS discovery timeout gracefully', async () => {
324
- const mockFailingDiscovery = {
325
- discoverResources: jest.fn().mockRejectedValue(new Error('Request timeout'))
326
- };
327
-
328
- jest.doMock('./aws-discovery', () => ({
329
- AWSDiscovery: jest.fn(() => mockFailingDiscovery)
330
- }));
331
-
332
- const appDefinition = {
333
- vpc: { enable: true },
334
- integrations: []
335
- };
336
-
337
- await expect(buildTimeDiscovery.preBuildHook(appDefinition, 'us-east-1')).rejects.toThrow('Request timeout');
338
- });
339
-
340
- it('should handle partial AWS resource discovery', async () => {
341
- const partialResources = {
342
- defaultVpcId: 'vpc-12345678',
343
- defaultSecurityGroupId: 'sg-12345678',
344
- privateSubnetId1: 'subnet-1',
345
- privateSubnetId2: 'subnet-1', // Same subnet used twice
346
- privateRouteTableId: 'rtb-12345678',
347
- defaultKmsKeyId: '*' // Fallback KMS key
348
- };
349
-
350
- mockAWSDiscovery.discoverResources.mockResolvedValue(partialResources);
351
-
352
- const appDefinition = {
353
- vpc: { enable: true },
354
- encryption: { fieldLevelEncryptionMethod: 'kms' },
355
- integrations: []
356
- };
357
-
358
- const result = await buildTimeDiscovery.preBuildHook(appDefinition, 'us-east-1');
359
-
360
- expect(result).toEqual(partialResources);
361
- expect(result.privateSubnetId2).toBe(result.privateSubnetId1); // Should handle single subnet scenario
362
- expect(result.defaultKmsKeyId).toBe('*'); // Should handle KMS fallback
363
- });
364
- });
365
-
366
- describe('Multi-Region Support', () => {
367
- it('should support different AWS regions', async () => {
368
- const appDefinition = {
369
- vpc: { enable: true },
370
- integrations: []
371
- };
372
-
373
- const euWestDiscovery = new BuildTimeDiscovery('eu-west-1');
374
-
375
- await euWestDiscovery.preBuildHook(appDefinition, 'eu-west-1');
376
-
377
- // Verify that AWSDiscovery was instantiated with correct region
378
- expect(mockAWSDiscovery.discoverResources).toHaveBeenCalled();
379
- });
380
- });
381
- });
@@ -1,119 +0,0 @@
1
- /**
2
- * Build for a non-AWS provider (friggframework/frigg#545, 302ab9ba /
3
- * c8705715).
4
- *
5
- * Instead of the serverless/CloudFormation pipeline, the provider plugin
6
- * (resolved from appDefinition.provider) does the build:
7
- * 1. validate(appDefinition) - errors abort, warnings print
8
- * 2. generateConfig(appDefinition) - e.g. netlify.toml
9
- * 3. getFunctionEntryPoints(appDefinition) - written to <project>/netlify/functions
10
- * 4. getLibEntryPoints(appDefinition) - written to <project>/netlify/lib
11
- *
12
- * <project> is the directory that holds backend/: the generated entry points
13
- * require '../../backend/...', so they must sit beside it. #545 had two
14
- * copies of this, and the CLI one wrote into the backend directory itself,
15
- * where those relative requires do not resolve.
16
- *
17
- * Shared by createFriggInfrastructure() (`node infrastructure.js package`,
18
- * what a backend's `npm run build` runs) and `frigg build`.
19
- */
20
- const path = require('path');
21
- const fs = require('fs');
22
-
23
- const CONFIG_FILE_NAMES = { netlify: 'netlify.toml' };
24
-
25
- /**
26
- * @param {Object} params
27
- * @param {Object} params.appDefinition
28
- * @param {string} params.backendDir - directory containing the backend's index.js
29
- * @param {Object} [params.provider] - resolved plugin; defaults to resolveProvider(appDefinition)
30
- * @param {boolean} [params.verbose]
31
- * @param {Function} [params.exit] - called with 1 on validation errors (default process.exit)
32
- * @returns {{ projectDir: string, written: string[] }}
33
- */
34
- function buildWithProvider({
35
- appDefinition,
36
- backendDir,
37
- provider,
38
- verbose = false,
39
- exit = (code) => process.exit(code),
40
- }) {
41
- const providerName = appDefinition.provider;
42
- const plugin =
43
- provider ||
44
- require('@friggframework/core/providers/resolve-provider').resolveProvider(
45
- appDefinition
46
- );
47
- const projectDir = path.dirname(path.resolve(backendDir));
48
- const written = [];
49
-
50
- console.log(`Building for ${providerName} provider (skipping AWS infrastructure)...`);
51
-
52
- if (typeof plugin.validate === 'function') {
53
- const validation = plugin.validate(appDefinition);
54
- if (validation.errors?.length > 0) {
55
- console.error(`\nValidation errors for ${providerName}:`);
56
- for (const error of validation.errors) {
57
- console.error(` - ${error}`);
58
- }
59
- exit(1);
60
- return { projectDir, written };
61
- }
62
- for (const warning of validation.warnings || []) {
63
- console.warn(` Warning: ${warning}`);
64
- }
65
- }
66
-
67
- const write = (filePath, content) => {
68
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
69
- fs.writeFileSync(filePath, content, 'utf-8');
70
- written.push(filePath);
71
- if (verbose) console.log(` Written ${path.relative(projectDir, filePath)}`);
72
- };
73
-
74
- if (typeof plugin.generateConfig === 'function') {
75
- const fileName = CONFIG_FILE_NAMES[providerName] || `${providerName}.config`;
76
- write(path.join(projectDir, fileName), plugin.generateConfig(appDefinition));
77
- console.log(` Written ${fileName}`);
78
- }
79
-
80
- if (typeof plugin.getFunctionEntryPoints === 'function') {
81
- const entryPoints = plugin.getFunctionEntryPoints(appDefinition);
82
- for (const [fileName, content] of Object.entries(entryPoints)) {
83
- write(path.join(projectDir, 'netlify', 'functions', fileName), content);
84
- }
85
- console.log(` Generated ${Object.keys(entryPoints).length} function entry points`);
86
- }
87
-
88
- if (typeof plugin.getLibEntryPoints === 'function') {
89
- const libEntryPoints = plugin.getLibEntryPoints(appDefinition);
90
- for (const [fileName, content] of Object.entries(libEntryPoints)) {
91
- write(path.join(projectDir, 'netlify', 'lib', fileName), content);
92
- }
93
- console.log(` Generated ${Object.keys(libEntryPoints).length} lib entry points`);
94
- }
95
-
96
- if (typeof plugin.generateEnvTemplate === 'function') {
97
- const missing = Object.entries(plugin.generateEnvTemplate(appDefinition)).filter(
98
- ([key]) => !process.env[key]
99
- );
100
- if (missing.length > 0) {
101
- console.log('\n Environment variables not set locally (configure them on the platform):');
102
- for (const [key] of missing) console.log(` - ${key}`);
103
- }
104
- }
105
-
106
- console.log(`\nBuild complete for ${providerName}.`);
107
- return { projectDir, written };
108
- }
109
-
110
- /**
111
- * True when the app definition names a provider other than AWS.
112
- * @param {Object} [appDefinition]
113
- */
114
- function isNonAwsProvider(appDefinition) {
115
- const name = appDefinition?.provider;
116
- return Boolean(name) && name !== 'aws';
117
- }
118
-
119
- module.exports = { buildWithProvider, isNonAwsProvider };
@@ -1,104 +0,0 @@
1
- /**
2
- * Jest setup: no test may run a package-manager command that rewrites a
3
- * node_modules tree outside the OS temp directory.
4
- *
5
- * Why: two infrastructure tests composed a serverless definition in parallel,
6
- * each building the real Prisma layer under packages/devtools/layers/prisma.
7
- * One cleaned the layer while the other's `npm install --omit=dev` was
8
- * starting, npm found no package.json in its cwd, walked up into the
9
- * monorepo workspace and pruned the devDependencies (jest, jest-util) out of
10
- * the repository's root node_modules. Every later workspace then failed with
11
- * `jest: not found`.
12
- *
13
- * The guard wraps the real child_process functions. A test that mocks
14
- * child_process (jest.mock) gets its mock and is unaffected; anything that
15
- * reaches the real module with, for example, `npm install` in a repository
16
- * directory throws instead of running.
17
- */
18
- const childProcess = require('child_process');
19
- const fs = require('fs');
20
- const os = require('os');
21
- const path = require('path');
22
-
23
- const PACKAGE_MANAGERS = new Set(['npm', 'npx', 'yarn', 'pnpm']);
24
- const MUTATING = new Set([
25
- 'install', 'i', 'in', 'ci', 'add', 'prune', 'uninstall', 'remove', 'rm', 'r', 'un',
26
- 'update', 'up', 'upgrade', 'dedupe', 'link', 'rebuild',
27
- ]);
28
-
29
- function realpathOrSelf(p) {
30
- try {
31
- return fs.realpathSync(p);
32
- } catch {
33
- return path.resolve(p);
34
- }
35
- }
36
-
37
- const TMP = realpathOrSelf(os.tmpdir());
38
- // The monorepo root (packages/devtools/test -> ../../..). A checkout can
39
- // itself live under the temp directory, so "under tmp" alone is not enough.
40
- const REPO_ROOT = realpathOrSelf(path.resolve(__dirname, '..', '..', '..'));
41
-
42
- const within = (dir, root) => dir === root || dir.startsWith(root + path.sep);
43
-
44
- /** True only for a scratch directory: under tmp and outside this repository. */
45
- function insideTmp(dir) {
46
- const real = realpathOrSelf(dir);
47
- return within(real, TMP) && !within(real, REPO_ROOT);
48
- }
49
-
50
- /** @returns {string|null} the offending command, or null when allowed */
51
- function offending(tokens, cwd) {
52
- const [bin, ...args] = tokens;
53
- if (!bin || !PACKAGE_MANAGERS.has(path.basename(String(bin)))) return null;
54
- const sub = args.find((a) => !String(a).startsWith('-'));
55
- // npx <pkg> runs a package; only installs/prunes rewrite node_modules.
56
- if (path.basename(String(bin)) === 'npx' || !MUTATING.has(sub)) return null;
57
- const prefixAt = args.indexOf('--prefix');
58
- const target = prefixAt >= 0 ? args[prefixAt + 1] : cwd;
59
- if (insideTmp(target || process.cwd())) return null;
60
- return tokens.join(' ');
61
- }
62
-
63
- const GUARDED = Symbol.for('frigg.devtools.npmInstallGuard');
64
-
65
- function guard(name, fn, toTokens) {
66
- // setupFiles runs once per test file in a shared worker: wrap once.
67
- if (fn[GUARDED]) return fn;
68
- const guarded = function guarded(...callArgs) {
69
- const { tokens, cwd } = toTokens(callArgs);
70
- const bad = offending(tokens, cwd);
71
- if (bad) {
72
- throw new Error(
73
- `Test tried to run "${bad}" outside the temp directory (cwd ${cwd || process.cwd()}); ` +
74
- 'it would rewrite a real node_modules. Mock it or run it in a temp dir.'
75
- );
76
- }
77
- return fn.apply(this, callArgs);
78
- };
79
- guarded[GUARDED] = true;
80
- return guarded;
81
- }
82
-
83
- const fromString = ([command, options]) => ({
84
- tokens: String(command).trim().split(/\s+/),
85
- cwd: options?.cwd,
86
- });
87
- const fromFile = ([file, args, options]) =>
88
- Array.isArray(args)
89
- ? { tokens: [file, ...args], cwd: options?.cwd }
90
- : { tokens: [file], cwd: args?.cwd };
91
-
92
- for (const name of ['execSync', 'exec']) {
93
- childProcess[name] = guard(name, childProcess[name], fromString);
94
- }
95
- for (const name of ['execFileSync', 'execFile', 'spawn', 'spawnSync']) {
96
- const original = childProcess[name];
97
- childProcess[name] = guard(name, original, (callArgs) => {
98
- const opts = Array.isArray(callArgs[1]) ? callArgs[2] : callArgs[1];
99
- if (opts?.shell && !Array.isArray(callArgs[1])) return fromString([callArgs[0], opts]);
100
- return fromFile(callArgs);
101
- });
102
- }
103
-
104
- module.exports = { offending, insideTmp };
@@ -1,53 +0,0 @@
1
- const os = require('os');
2
- const path = require('path');
3
- const childProcess = require('child_process');
4
- // Read before this file loads the guard itself: jest's setupFiles must have
5
- // installed it already, for every test file.
6
- const guardedBySetup = Boolean(childProcess.execSync[Symbol.for('frigg.devtools.npmInstallGuard')]);
7
- const { offending } = require('./npm-install-guard');
8
-
9
- const repoDir = path.resolve(__dirname, '..');
10
-
11
- describe('npm install guard (jest setupFiles)', () => {
12
- // Every command here is a --dry-run, so even a broken guard that let it
13
- // through could not rewrite this repository's node_modules.
14
- it('is installed by jest setupFiles, before any test code runs', () => {
15
- expect(guardedBySetup).toBe(true);
16
- });
17
-
18
- it('blocks installs and prunes on the real child_process', () => {
19
- expect(() =>
20
- childProcess.execSync('npm install --dry-run --omit=dev', { cwd: repoDir, stdio: 'ignore' })
21
- ).toThrow(/outside the temp directory/);
22
- expect(() =>
23
- childProcess.spawnSync('npm', ['prune', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
24
- ).toThrow(/outside the temp directory/);
25
- expect(() =>
26
- childProcess.execFileSync('/usr/bin/npm', ['ci', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
27
- ).toThrow(/outside the temp directory/);
28
- });
29
-
30
- it('treats a temp dir inside this repository as part of the repository', () => {
31
- // A checkout may itself live under os.tmpdir() (as in some sandboxes).
32
- expect(offending(['npm', 'install'], path.join(repoDir, 'layers/prisma/nodejs'))).not.toBeNull();
33
- });
34
-
35
- it.each([
36
- [['npm', 'install', '--omit=dev'], repoDir, true],
37
- [['npm', 'ci'], repoDir, true],
38
- [['yarn', 'add', 'x'], repoDir, true],
39
- [['npm', 'install', '--prefix', repoDir], os.tmpdir(), true],
40
- [['npm', 'install'], os.tmpdir(), false],
41
- [['npm', 'install', '--prefix', path.join(os.tmpdir(), 'layer')], repoDir, false],
42
- [['npm', 'root'], repoDir, false],
43
- [['npm', 'run', 'build'], repoDir, false],
44
- [['npx', 'netlify-cli', 'deploy'], repoDir, false],
45
- [['git', 'install'], repoDir, false],
46
- ])('%j in %s -> blocked %s', (tokens, cwd, blocked) => {
47
- expect(offending(tokens, cwd) !== null).toBe(blocked);
48
- });
49
-
50
- it('lets harmless commands through', () => {
51
- expect(childProcess.execSync('node -e "process.stdout.write(\'ok\')"', { encoding: 'utf8' })).toBe('ok');
52
- });
53
- });