@friggframework/devtools 2.0.0-next.45 → 2.0.0-next.47

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 (212) hide show
  1. package/infrastructure/ARCHITECTURE.md +487 -0
  2. package/infrastructure/HEALTH.md +468 -0
  3. package/infrastructure/README.md +51 -0
  4. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  5. package/infrastructure/__tests__/template-generation.test.js +687 -0
  6. package/infrastructure/create-frigg-infrastructure.js +1 -1
  7. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +630 -0
  8. package/infrastructure/{DEPLOYMENT-INSTRUCTIONS.md → docs/deployment-instructions.md} +3 -3
  9. package/infrastructure/{IAM-POLICY-TEMPLATES.md → docs/iam-policy-templates.md} +9 -10
  10. package/infrastructure/domains/database/aurora-builder.js +809 -0
  11. package/infrastructure/domains/database/aurora-builder.test.js +950 -0
  12. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  13. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  14. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  15. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  16. package/infrastructure/domains/database/migration-builder.js +695 -0
  17. package/infrastructure/domains/database/migration-builder.test.js +294 -0
  18. package/infrastructure/domains/database/migration-resolver.js +163 -0
  19. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  20. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  21. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  22. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  23. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  24. package/infrastructure/domains/health/application/ports/index.js +26 -0
  25. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  26. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  27. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  28. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  29. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  30. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  31. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  32. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  33. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  34. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  35. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  36. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  37. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  38. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  39. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  40. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  41. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  42. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  43. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  44. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  45. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  46. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  47. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  48. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  49. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  50. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  51. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  52. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  53. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  54. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  55. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  56. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  57. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  58. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  59. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  60. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  61. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  62. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  63. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  64. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  65. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  66. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  67. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  68. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  69. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  70. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  71. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  72. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  73. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  74. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  75. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  76. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  77. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  78. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  79. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  80. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  81. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  82. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  83. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  84. package/infrastructure/domains/integration/integration-builder.js +397 -0
  85. package/infrastructure/domains/integration/integration-builder.test.js +593 -0
  86. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  87. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  88. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  89. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  90. package/infrastructure/domains/networking/vpc-builder.js +1829 -0
  91. package/infrastructure/domains/networking/vpc-builder.test.js +1262 -0
  92. package/infrastructure/domains/networking/vpc-discovery.js +177 -0
  93. package/infrastructure/domains/networking/vpc-discovery.test.js +350 -0
  94. package/infrastructure/domains/networking/vpc-resolver.js +324 -0
  95. package/infrastructure/domains/networking/vpc-resolver.test.js +501 -0
  96. package/infrastructure/domains/parameters/ssm-builder.js +79 -0
  97. package/infrastructure/domains/parameters/ssm-builder.test.js +189 -0
  98. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  99. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  100. package/infrastructure/{iam-generator.js → domains/security/iam-generator.js} +2 -2
  101. package/infrastructure/domains/security/kms-builder.js +366 -0
  102. package/infrastructure/domains/security/kms-builder.test.js +374 -0
  103. package/infrastructure/domains/security/kms-discovery.js +80 -0
  104. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  105. package/infrastructure/domains/security/kms-resolver.js +96 -0
  106. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  107. package/infrastructure/domains/shared/base-builder.js +112 -0
  108. package/infrastructure/domains/shared/base-resolver.js +186 -0
  109. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  110. package/infrastructure/domains/shared/builder-orchestrator.js +212 -0
  111. package/infrastructure/domains/shared/builder-orchestrator.test.js +213 -0
  112. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  113. package/infrastructure/domains/shared/cloudformation-discovery.js +375 -0
  114. package/infrastructure/domains/shared/cloudformation-discovery.test.js +590 -0
  115. package/infrastructure/domains/shared/environment-builder.js +119 -0
  116. package/infrastructure/domains/shared/environment-builder.test.js +247 -0
  117. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +544 -0
  118. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +377 -0
  119. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  120. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  121. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  122. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  123. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  124. package/infrastructure/domains/shared/resource-discovery.js +192 -0
  125. package/infrastructure/domains/shared/resource-discovery.test.js +552 -0
  126. package/infrastructure/domains/shared/types/app-definition.js +205 -0
  127. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  128. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  129. package/infrastructure/domains/shared/types/index.js +46 -0
  130. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  131. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  132. package/infrastructure/domains/shared/utilities/base-definition-factory.js +380 -0
  133. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +338 -0
  134. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +248 -0
  135. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  136. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  137. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +55 -0
  138. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +138 -0
  139. package/infrastructure/{env-validator.js → domains/shared/validation/env-validator.js} +2 -1
  140. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  141. package/infrastructure/esbuild.config.js +53 -0
  142. package/infrastructure/infrastructure-composer.js +87 -0
  143. package/infrastructure/{serverless-template.test.js → infrastructure-composer.test.js} +115 -24
  144. package/infrastructure/scripts/build-prisma-layer.js +553 -0
  145. package/infrastructure/scripts/build-prisma-layer.test.js +102 -0
  146. package/infrastructure/{build-time-discovery.js → scripts/build-time-discovery.js} +80 -48
  147. package/infrastructure/{build-time-discovery.test.js → scripts/build-time-discovery.test.js} +5 -4
  148. package/layers/prisma/nodejs/package.json +8 -0
  149. package/management-ui/server/utils/cliIntegration.js +1 -1
  150. package/management-ui/server/utils/environment/awsParameterStore.js +29 -18
  151. package/package.json +11 -11
  152. package/frigg-cli/.eslintrc.js +0 -141
  153. package/frigg-cli/__tests__/unit/commands/build.test.js +0 -251
  154. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +0 -548
  155. package/frigg-cli/__tests__/unit/commands/install.test.js +0 -400
  156. package/frigg-cli/__tests__/unit/commands/ui.test.js +0 -346
  157. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +0 -366
  158. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +0 -304
  159. package/frigg-cli/__tests__/unit/utils/prisma-runner.test.js +0 -486
  160. package/frigg-cli/__tests__/utils/mock-factory.js +0 -270
  161. package/frigg-cli/__tests__/utils/prisma-mock.js +0 -194
  162. package/frigg-cli/__tests__/utils/test-fixtures.js +0 -463
  163. package/frigg-cli/__tests__/utils/test-setup.js +0 -287
  164. package/frigg-cli/build-command/index.js +0 -65
  165. package/frigg-cli/db-setup-command/index.js +0 -193
  166. package/frigg-cli/deploy-command/index.js +0 -175
  167. package/frigg-cli/generate-command/__tests__/generate-command.test.js +0 -301
  168. package/frigg-cli/generate-command/azure-generator.js +0 -43
  169. package/frigg-cli/generate-command/gcp-generator.js +0 -47
  170. package/frigg-cli/generate-command/index.js +0 -332
  171. package/frigg-cli/generate-command/terraform-generator.js +0 -555
  172. package/frigg-cli/generate-iam-command.js +0 -118
  173. package/frigg-cli/index.js +0 -75
  174. package/frigg-cli/index.test.js +0 -158
  175. package/frigg-cli/init-command/backend-first-handler.js +0 -756
  176. package/frigg-cli/init-command/index.js +0 -93
  177. package/frigg-cli/init-command/template-handler.js +0 -143
  178. package/frigg-cli/install-command/backend-js.js +0 -33
  179. package/frigg-cli/install-command/commit-changes.js +0 -16
  180. package/frigg-cli/install-command/environment-variables.js +0 -127
  181. package/frigg-cli/install-command/environment-variables.test.js +0 -136
  182. package/frigg-cli/install-command/index.js +0 -54
  183. package/frigg-cli/install-command/install-package.js +0 -13
  184. package/frigg-cli/install-command/integration-file.js +0 -30
  185. package/frigg-cli/install-command/logger.js +0 -12
  186. package/frigg-cli/install-command/template.js +0 -90
  187. package/frigg-cli/install-command/validate-package.js +0 -75
  188. package/frigg-cli/jest.config.js +0 -124
  189. package/frigg-cli/package.json +0 -54
  190. package/frigg-cli/start-command/index.js +0 -149
  191. package/frigg-cli/start-command/start-command.test.js +0 -297
  192. package/frigg-cli/test/init-command.test.js +0 -180
  193. package/frigg-cli/test/npm-registry.test.js +0 -319
  194. package/frigg-cli/ui-command/index.js +0 -154
  195. package/frigg-cli/utils/app-resolver.js +0 -319
  196. package/frigg-cli/utils/backend-path.js +0 -25
  197. package/frigg-cli/utils/database-validator.js +0 -161
  198. package/frigg-cli/utils/error-messages.js +0 -257
  199. package/frigg-cli/utils/npm-registry.js +0 -167
  200. package/frigg-cli/utils/prisma-runner.js +0 -280
  201. package/frigg-cli/utils/process-manager.js +0 -199
  202. package/frigg-cli/utils/repo-detection.js +0 -405
  203. package/infrastructure/aws-discovery.js +0 -1176
  204. package/infrastructure/aws-discovery.test.js +0 -1220
  205. package/infrastructure/serverless-template.js +0 -2094
  206. /package/infrastructure/{WEBSOCKET-CONFIGURATION.md → docs/WEBSOCKET-CONFIGURATION.md} +0 -0
  207. /package/infrastructure/{GENERATE-IAM-DOCS.md → docs/generate-iam-command.md} +0 -0
  208. /package/infrastructure/{iam-generator.test.js → domains/security/iam-generator.test.js} +0 -0
  209. /package/infrastructure/{frigg-deployment-iam-stack.yaml → domains/security/templates/frigg-deployment-iam-stack.yaml} +0 -0
  210. /package/infrastructure/{iam-policy-basic.json → domains/security/templates/iam-policy-basic.json} +0 -0
  211. /package/infrastructure/{iam-policy-full.json → domains/security/templates/iam-policy-full.json} +0 -0
  212. /package/infrastructure/{run-discovery.js → scripts/run-discovery.js} +0 -0
@@ -0,0 +1,695 @@
1
+ /**
2
+ * Migration Infrastructure Builder
3
+ *
4
+ * Domain Layer - Hexagonal Architecture
5
+ *
6
+ * Responsible for:
7
+ * - SQS queue for migration jobs
8
+ * - Migration worker Lambda function (triggered by SQS)
9
+ * - Migration router Lambda function (HTTP API)
10
+ * - IAM permissions for SQS
11
+ *
12
+ * Only creates infrastructure when PostgreSQL is enabled.
13
+ * MongoDB uses `db push` which doesn't require migration queue/worker.
14
+ */
15
+
16
+ const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
17
+ const { MigrationResourceResolver } = require('./migration-resolver');
18
+ const { createEmptyDiscoveryResult, ResourceOwnership } = require('../shared/types');
19
+
20
+ class MigrationBuilder extends InfrastructureBuilder {
21
+ constructor() {
22
+ super();
23
+ this.name = 'MigrationBuilder';
24
+ }
25
+
26
+ shouldExecute(appDefinition) {
27
+ // Only create migration infrastructure for PostgreSQL
28
+ // MongoDB uses `db push` which doesn't need queue/worker
29
+ // Skip in local mode
30
+ if (process.env.FRIGG_SKIP_AWS_DISCOVERY === 'true') {
31
+ return false;
32
+ }
33
+
34
+ // Default to true if not explicitly disabled
35
+ return appDefinition.database?.postgres?.enable !== false;
36
+ }
37
+
38
+ getDependencies() {
39
+ return []; // No dependencies - migrations can run independently
40
+ }
41
+
42
+ validate(appDefinition) {
43
+ const result = new ValidationResult();
44
+
45
+ // No specific validation needed - PostgreSQL builder handles DB validation
46
+ // This builder just creates the migration infrastructure
47
+
48
+ return result;
49
+ }
50
+
51
+ /**
52
+ * Build migration infrastructure using ownership-based architecture
53
+ */
54
+ async build(appDefinition, discoveredResources) {
55
+ console.log(`\n[${this.name}] Configuring database migration infrastructure...`);
56
+
57
+ // Backwards compatibility: Translate old schema to new ownership schema
58
+ appDefinition = this.translateLegacyConfig(appDefinition, discoveredResources);
59
+
60
+ const result = {
61
+ functions: {}, // Lambda function definitions
62
+ resources: {},
63
+ iamStatements: [],
64
+ environment: {},
65
+ };
66
+
67
+ // Get structured discovery result
68
+ const discovery = discoveredResources._structured || this.convertFlatDiscoveryToStructured(discoveredResources, appDefinition);
69
+
70
+ // Use MigrationResourceResolver to make ownership decisions
71
+ const resolver = new MigrationResourceResolver();
72
+ const decisions = resolver.resolveAll(appDefinition, discovery);
73
+
74
+ console.log('\n 📋 Resource Ownership Decisions:');
75
+ console.log(` Bucket: ${decisions.bucket.ownership} - ${decisions.bucket.reason}`);
76
+ console.log(` Queue: ${decisions.queue.ownership} - ${decisions.queue.reason}`);
77
+
78
+ // Build resources based on ownership decisions
79
+ await this.buildFromDecisions(decisions, appDefinition, discoveredResources, result);
80
+
81
+ console.log(`[${this.name}] ✅ Migration infrastructure configuration completed`);
82
+ return result;
83
+ }
84
+
85
+ /**
86
+ * Convert flat discovery to structured discovery
87
+ * Provides backwards compatibility for tests
88
+ */
89
+ convertFlatDiscoveryToStructured(flatDiscovery, appDefinition = {}) {
90
+ const discovery = createEmptyDiscoveryResult();
91
+
92
+ if (!flatDiscovery) {
93
+ return discovery;
94
+ }
95
+
96
+ // Check if resources are from CloudFormation stack
97
+ const isManagedIsolated = appDefinition.managementMode === 'managed' &&
98
+ (appDefinition.vpcIsolation === 'isolated' || !appDefinition.vpcIsolation);
99
+ const hasExistingStackResources = isManagedIsolated &&
100
+ (flatDiscovery.migrationStatusBucket || flatDiscovery.migrationQueueUrl);
101
+
102
+ if (flatDiscovery.fromCloudFormationStack || hasExistingStackResources) {
103
+ discovery.fromCloudFormation = true;
104
+ discovery.stackName = flatDiscovery.stackName || 'assumed-stack';
105
+
106
+ // Add stack-managed resources
107
+ let existingLogicalIds = flatDiscovery.existingLogicalIds || [];
108
+
109
+ // Infer logical IDs from physical IDs if needed
110
+ if (hasExistingStackResources && existingLogicalIds.length === 0) {
111
+ if (flatDiscovery.migrationStatusBucket) existingLogicalIds.push('FriggMigrationStatusBucket');
112
+ if (flatDiscovery.migrationQueueUrl) existingLogicalIds.push('DbMigrationQueue');
113
+ }
114
+
115
+ existingLogicalIds.forEach(logicalId => {
116
+ let resourceType = '';
117
+ let physicalId = '';
118
+
119
+ if (logicalId === 'FriggMigrationStatusBucket') {
120
+ resourceType = 'AWS::S3::Bucket';
121
+ physicalId = flatDiscovery.migrationStatusBucket;
122
+ } else if (logicalId === 'DbMigrationQueue') {
123
+ resourceType = 'AWS::SQS::Queue';
124
+ physicalId = flatDiscovery.migrationQueueUrl;
125
+ }
126
+
127
+ if (physicalId && typeof physicalId === 'string') {
128
+ discovery.stackManaged.push({
129
+ logicalId,
130
+ physicalId,
131
+ resourceType
132
+ });
133
+ }
134
+ });
135
+ } else {
136
+ // Resources discovered from AWS API (external)
137
+ if (flatDiscovery.migrationStatusBucket && typeof flatDiscovery.migrationStatusBucket === 'string') {
138
+ discovery.external.push({
139
+ physicalId: flatDiscovery.migrationStatusBucket,
140
+ resourceType: 'AWS::S3::Bucket',
141
+ source: 'aws-discovery'
142
+ });
143
+ }
144
+
145
+ if (flatDiscovery.migrationQueueUrl && typeof flatDiscovery.migrationQueueUrl === 'string') {
146
+ discovery.external.push({
147
+ physicalId: flatDiscovery.migrationQueueUrl,
148
+ resourceType: 'AWS::SQS::Queue',
149
+ source: 'aws-discovery'
150
+ });
151
+ }
152
+ }
153
+
154
+ return discovery;
155
+ }
156
+
157
+ /**
158
+ * Translate legacy configuration to ownership-based configuration
159
+ * Provides backwards compatibility
160
+ */
161
+ translateLegacyConfig(appDefinition, discoveredResources) {
162
+ // If already using ownership schema, return as-is
163
+ if (appDefinition.migration?.ownership) {
164
+ return appDefinition;
165
+ }
166
+
167
+ const translated = JSON.parse(JSON.stringify(appDefinition));
168
+
169
+ // Initialize ownership sections
170
+ if (!translated.migration) translated.migration = {};
171
+ if (!translated.migration.ownership) {
172
+ translated.migration.ownership = {};
173
+ }
174
+
175
+ // Handle top-level managementMode
176
+ const globalMode = appDefinition.managementMode || 'discover';
177
+ const vpcIsolation = appDefinition.vpcIsolation || 'shared';
178
+
179
+ if (globalMode === 'managed') {
180
+ if (vpcIsolation === 'isolated') {
181
+ const hasStackResources = discoveredResources?.migrationStatusBucket ||
182
+ discoveredResources?.migrationQueueUrl;
183
+
184
+ if (hasStackResources) {
185
+ translated.migration.ownership.bucket = 'auto';
186
+ translated.migration.ownership.queue = 'auto';
187
+ console.log(` managementMode='managed' + vpcIsolation='isolated' → stack has migration resources, reusing`);
188
+ } else {
189
+ translated.migration.ownership.bucket = 'stack';
190
+ translated.migration.ownership.queue = 'stack';
191
+ console.log(` managementMode='managed' + vpcIsolation='isolated' → no stack migration resources, creating new`);
192
+ }
193
+ } else {
194
+ translated.migration.ownership.bucket = 'auto';
195
+ translated.migration.ownership.queue = 'auto';
196
+ console.log(` managementMode='managed' + vpcIsolation='shared' → discovering migration resources`);
197
+ }
198
+ } else {
199
+ // Default to creating resources (current behavior)
200
+ translated.migration.ownership.bucket = 'stack';
201
+ translated.migration.ownership.queue = 'stack';
202
+ }
203
+
204
+ return translated;
205
+ }
206
+
207
+ /**
208
+ * Build migration resources based on ownership decisions
209
+ */
210
+ async buildFromDecisions(decisions, appDefinition, discoveredResources, result) {
211
+ // Determine if we need to create resources or use existing ones
212
+ const shouldCreateBucket = decisions.bucket.ownership === ResourceOwnership.STACK;
213
+ const shouldCreateQueue = decisions.queue.ownership === ResourceOwnership.STACK;
214
+
215
+ if (shouldCreateBucket && shouldCreateQueue && !decisions.bucket.physicalId && !decisions.queue.physicalId) {
216
+ // Create all new migration infrastructure
217
+ console.log(' → Creating new migration infrastructure in stack');
218
+ await this.createMigrationInfrastructure(appDefinition, result);
219
+ } else if ((decisions.bucket.ownership === ResourceOwnership.STACK && decisions.bucket.physicalId) ||
220
+ (decisions.queue.ownership === ResourceOwnership.STACK && decisions.queue.physicalId)) {
221
+ // Resources exist in stack - add definitions (CloudFormation idempotency)
222
+ console.log(' → Adding migration definitions to template (existing in stack)');
223
+ await this.createMigrationInfrastructure(appDefinition, result);
224
+ } else {
225
+ // Use external resources
226
+ console.log(' → Using external migration resources');
227
+ await this.useExternalMigrationResources(decisions, appDefinition, result);
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Create Lambda function definitions for database migrations
233
+ * Based on refactor/add-better-support-for-commands branch implementation
234
+ */
235
+ async createFunctionDefinitions(result) {
236
+ console.log(' 🔍 DEBUG: createFunctionDefinitions called');
237
+ console.log(' 🔍 DEBUG: result.functions is:', typeof result.functions, result.functions);
238
+ // Migration WORKER package config (needs Prisma CLI WASM files)
239
+ const migrationWorkerPackageConfig = {
240
+ individually: true,
241
+ exclude: [
242
+ // Exclude Prisma runtime client - it's in the Lambda Layer
243
+ 'node_modules/@prisma/client/**',
244
+ 'node_modules/.prisma/**',
245
+ 'node_modules/@friggframework/core/generated/**',
246
+ // But KEEP node_modules/prisma/** (the CLI with WASM)
247
+
248
+ // Exclude ALL nested node_modules
249
+ 'node_modules/**/node_modules/**',
250
+
251
+ // Exclude AWS SDK (provided by Lambda runtime)
252
+ 'node_modules/aws-sdk/**',
253
+ 'node_modules/@aws-sdk/**',
254
+
255
+ // Exclude build tools
256
+ 'node_modules/esbuild/**',
257
+ 'node_modules/@esbuild/**',
258
+ 'node_modules/typescript/**',
259
+ 'node_modules/webpack/**',
260
+ 'node_modules/osls/**',
261
+ 'node_modules/serverless-esbuild/**',
262
+ 'node_modules/serverless-jetpack/**',
263
+ 'node_modules/serverless-offline/**',
264
+ 'node_modules/serverless-offline-sqs/**',
265
+ 'node_modules/serverless-dotenv-plugin/**',
266
+ 'node_modules/serverless-kms-grants/**',
267
+
268
+ // Exclude dev dependencies
269
+ 'node_modules/@friggframework/test/**',
270
+ 'node_modules/@friggframework/eslint-config/**',
271
+ 'node_modules/@friggframework/prettier-config/**',
272
+ 'node_modules/@friggframework/devtools/**',
273
+ 'node_modules/@friggframework/serverless-plugin/**',
274
+ 'node_modules/jest/**',
275
+ 'node_modules/prettier/**',
276
+ 'node_modules/eslint/**',
277
+
278
+ // Exclude non-essential Frigg core modules
279
+ 'node_modules/@friggframework/core/generated/prisma-mongodb/**',
280
+ 'node_modules/@friggframework/core/integrations/**',
281
+ 'node_modules/@friggframework/core/user/**',
282
+
283
+ // Exclude other handlers we don't need (keep db-migration worker)
284
+ 'node_modules/@friggframework/core/handlers/routers/auth.js',
285
+ 'node_modules/@friggframework/core/handlers/routers/health.js',
286
+ 'node_modules/@friggframework/core/handlers/routers/user.js',
287
+ 'node_modules/@friggframework/core/handlers/routers/websocket.js',
288
+ 'node_modules/@friggframework/core/handlers/routers/integration-*.js',
289
+ 'node_modules/@friggframework/core/handlers/workers/integration-*.js',
290
+
291
+ // Exclude wrong OS binaries
292
+ '**/query-engine-darwin*',
293
+ '**/schema-engine-darwin*',
294
+ '**/libquery_engine-darwin*',
295
+ '**/*-darwin-arm64*',
296
+ '**/*-darwin*',
297
+
298
+ // Migration worker DOES need Prisma CLI WASM files (for migrate deploy)
299
+ // Only exclude runtime engine WASM (query engine internals)
300
+ '**/runtime/*.wasm',
301
+
302
+ // Additional size optimizations
303
+ '**/*.map',
304
+ '**/*.md',
305
+ '**/LICENSE*',
306
+ '**/*.d.ts',
307
+ '**/*.d.mts',
308
+ '**/examples/**',
309
+ '**/docs/**',
310
+ 'src/**',
311
+ 'test/**',
312
+ 'layers/**',
313
+ 'coverage/**',
314
+ 'deploy.log',
315
+ '.env.backup',
316
+ 'docker-compose.yml',
317
+ 'jest.config.js',
318
+ 'jest.unit.config.js',
319
+ 'package-lock.json',
320
+ '**/*.test.js',
321
+ '**/*.spec.js',
322
+ '**/.claude-flow/**',
323
+ '**/.swarm/**',
324
+ ],
325
+ };
326
+
327
+ // Migration ROUTER package config (lighter, no Prisma CLI needed)
328
+ const migrationRouterPackageConfig = {
329
+ individually: true,
330
+ exclude: [
331
+ // Exclude Prisma runtime client - it's in the Lambda Layer
332
+ 'node_modules/@prisma/client/**',
333
+ 'node_modules/.prisma/**',
334
+ 'node_modules/@friggframework/core/generated/**',
335
+
336
+ // Router doesn't need Prisma CLI at all
337
+ 'node_modules/prisma/**',
338
+
339
+ // Exclude ALL nested node_modules
340
+ 'node_modules/**/node_modules/**',
341
+
342
+ // Exclude AWS SDK (provided by Lambda runtime)
343
+ 'node_modules/aws-sdk/**',
344
+ 'node_modules/@aws-sdk/**',
345
+
346
+ // Exclude build tools
347
+ 'node_modules/esbuild/**',
348
+ 'node_modules/@esbuild/**',
349
+ 'node_modules/typescript/**',
350
+ 'node_modules/webpack/**',
351
+ 'node_modules/osls/**',
352
+ 'node_modules/serverless-esbuild/**',
353
+ 'node_modules/serverless-jetpack/**',
354
+ 'node_modules/serverless-offline/**',
355
+ 'node_modules/serverless-offline-sqs/**',
356
+ 'node_modules/serverless-dotenv-plugin/**',
357
+ 'node_modules/serverless-kms-grants/**',
358
+
359
+ // Exclude dev dependencies
360
+ 'node_modules/@friggframework/test/**',
361
+ 'node_modules/@friggframework/eslint-config/**',
362
+ 'node_modules/@friggframework/prettier-config/**',
363
+ 'node_modules/@friggframework/devtools/**',
364
+ 'node_modules/@friggframework/serverless-plugin/**',
365
+ 'node_modules/jest/**',
366
+ 'node_modules/prettier/**',
367
+ 'node_modules/eslint/**',
368
+
369
+ // Exclude non-essential Frigg core modules
370
+ 'node_modules/@friggframework/core/generated/prisma-mongodb/**',
371
+ 'node_modules/@friggframework/core/integrations/**',
372
+ 'node_modules/@friggframework/core/user/**',
373
+
374
+ // Exclude other handlers we don't need (keep db-migration router)
375
+ 'node_modules/@friggframework/core/handlers/routers/auth.js',
376
+ 'node_modules/@friggframework/core/handlers/routers/health.js',
377
+ 'node_modules/@friggframework/core/handlers/routers/user.js',
378
+ 'node_modules/@friggframework/core/handlers/routers/websocket.js',
379
+ 'node_modules/@friggframework/core/handlers/routers/integration-*.js',
380
+ 'node_modules/@friggframework/core/handlers/workers/**',
381
+
382
+ // Exclude wrong OS binaries
383
+ '**/query-engine-darwin*',
384
+ '**/schema-engine-darwin*',
385
+ '**/libquery_engine-darwin*',
386
+ '**/*-darwin-arm64*',
387
+ '**/*-darwin*',
388
+
389
+ // Router doesn't run migrations - exclude ALL WASM files
390
+ '**/runtime/*.wasm',
391
+ '**/*.wasm*',
392
+
393
+ // Additional size optimizations
394
+ '**/*.map',
395
+ '**/*.md',
396
+ '**/LICENSE*',
397
+ '**/*.d.ts',
398
+ '**/*.d.mts',
399
+ '**/test/**',
400
+ '**/tests/**',
401
+ '**/__tests__/**',
402
+ '**/examples/**',
403
+ '**/docs/**',
404
+ 'src/**',
405
+ 'test/**',
406
+ 'layers/**',
407
+ 'coverage/**',
408
+ 'deploy.log',
409
+ '.env.backup',
410
+ 'docker-compose.yml',
411
+ 'jest.config.js',
412
+ 'jest.unit.config.js',
413
+ 'package-lock.json',
414
+ '**/*.test.js',
415
+ '**/*.spec.js',
416
+ '**/.claude-flow/**',
417
+ '**/.swarm/**',
418
+ ],
419
+ };
420
+
421
+ // Create migration worker Lambda (triggered by SQS)
422
+ console.log(' 🔍 DEBUG: About to create dbMigrationWorker...');
423
+ result.functions.dbMigrationWorker = {
424
+ handler: 'node_modules/@friggframework/core/handlers/workers/db-migration.handler',
425
+ layers: [{ Ref: 'PrismaLambdaLayer' }], // Use layer for Prisma client runtime
426
+ skipEsbuild: true,
427
+ timeout: 900, // 15 minutes for long migrations
428
+ memorySize: 1024, // Extra memory for Prisma operations
429
+ reservedConcurrency: 1, // Process one migration at a time (critical for safety)
430
+ description: 'Database migration worker (triggered by SQS queue)',
431
+ package: migrationWorkerPackageConfig,
432
+ environment: {
433
+ // Ensure migration functions get DATABASE_URL from provider.environment
434
+ // Note: Serverless will merge this with provider.environment
435
+ },
436
+ events: [
437
+ {
438
+ sqs: {
439
+ arn: { 'Fn::GetAtt': ['DbMigrationQueue', 'Arn'] },
440
+ batchSize: 1, // Process one migration at a time
441
+ },
442
+ },
443
+ ],
444
+ };
445
+ console.log(' ✓ Created dbMigrationWorker function');
446
+ console.log(' 🔍 DEBUG: result.functions.dbMigrationWorker is:', !!result.functions.dbMigrationWorker);
447
+
448
+ // Create migration router Lambda (HTTP API)
449
+ console.log(' 🔍 DEBUG: About to create dbMigrationRouter...');
450
+ result.functions.dbMigrationRouter = {
451
+ handler: 'node_modules/@friggframework/core/handlers/routers/db-migration.handler',
452
+ // No Prisma layer needed - router doesn't access database
453
+ skipEsbuild: true,
454
+ timeout: 30, // Router just queues jobs, doesn't run migrations
455
+ memorySize: 512,
456
+ description: 'Database migration HTTP API (POST to trigger, GET to check status)',
457
+ package: migrationRouterPackageConfig,
458
+ environment: {
459
+ // Ensure migration functions get DATABASE_URL from provider.environment
460
+ // Note: Serverless will merge this with provider.environment
461
+ },
462
+ events: [
463
+ { httpApi: { path: '/db-migrate/status', method: 'GET' } },
464
+ { httpApi: { path: '/db-migrate', method: 'POST' } },
465
+ { httpApi: { path: '/db-migrate/{processId}', method: 'GET' } },
466
+ ],
467
+ };
468
+ console.log(' ✓ Created dbMigrationRouter function');
469
+
470
+ // Add worker function name to router environment (for Lambda invocation)
471
+ // Router needs this to invoke worker for database state checks
472
+ if (!result.functions.dbMigrationRouter.environment) {
473
+ result.functions.dbMigrationRouter.environment = {};
474
+ }
475
+ result.functions.dbMigrationRouter.environment.WORKER_FUNCTION_NAME = {
476
+ Ref: 'DbMigrationWorkerLambdaFunction',
477
+ };
478
+ console.log(' ✓ Added WORKER_FUNCTION_NAME environment variable to router');
479
+ console.log(' 🔍 DEBUG: result.functions keys:', Object.keys(result.functions));
480
+ console.log(' 🔍 DEBUG: Exiting createFunctionDefinitions');
481
+ }
482
+
483
+ /**
484
+ * Create migration infrastructure CloudFormation resources
485
+ * Creates S3 bucket, SQS queue, and Lambda function definitions
486
+ */
487
+ async createMigrationInfrastructure(appDefinition, result) {
488
+ console.log(' 🔍 DEBUG: createMigrationInfrastructure called');
489
+ console.log(' 🔍 DEBUG: result object before createFunctionDefinitions:', Object.keys(result));
490
+
491
+ // Create Lambda function definitions first (they reference the queue)
492
+ await this.createFunctionDefinitions(result);
493
+
494
+ console.log(' 🔍 DEBUG: result.functions after createFunctionDefinitions:', Object.keys(result.functions || {}));
495
+
496
+ // Create S3 bucket for migration status tracking
497
+ result.resources.FriggMigrationStatusBucket = {
498
+ Type: 'AWS::S3::Bucket',
499
+ DeletionPolicy: 'Retain', // Protect migration history during stack rollbacks/deletions
500
+ UpdateReplacePolicy: 'Retain', // Protect during stack updates that require replacement
501
+ Properties: {
502
+ // Let CloudFormation auto-generate bucket name for global uniqueness
503
+ // Result: ${StackName}-friggmigrationstatusbucket-${randomHash}
504
+ // Example: quo-integrations-prod-friggmigrationstatusbucket-abc123xyz
505
+ // This ensures no conflicts across accounts/regions/stages
506
+ // BucketName: undefined (CloudFormation generates unique name)
507
+ VersioningConfiguration: {
508
+ Status: 'Enabled', // Enable versioning for audit trail
509
+ },
510
+ LifecycleConfiguration: {
511
+ Rules: [
512
+ {
513
+ Id: 'DeleteOldMigrations',
514
+ Status: 'Enabled',
515
+ ExpirationInDays: 90, // Keep migration history for 90 days
516
+ },
517
+ ],
518
+ },
519
+ PublicAccessBlockConfiguration: {
520
+ BlockPublicAcls: true,
521
+ BlockPublicPolicy: true,
522
+ IgnorePublicAcls: true,
523
+ RestrictPublicBuckets: true,
524
+ },
525
+ Tags: [
526
+ { Key: 'ManagedBy', Value: 'Frigg' },
527
+ { Key: 'Purpose', Value: 'MigrationStatusTracking' },
528
+ ],
529
+ },
530
+ };
531
+
532
+ console.log(' ✓ Created FriggMigrationStatusBucket resource');
533
+
534
+ // Create SQS queue for migration jobs
535
+ result.resources.DbMigrationQueue = {
536
+ Type: 'AWS::SQS::Queue',
537
+ Properties: {
538
+ QueueName: '${self:service}-${self:provider.stage}-DbMigrationQueue',
539
+ VisibilityTimeout: 900, // 15 minutes for long-running migrations
540
+ MessageRetentionPeriod: 1209600, // 14 days
541
+ ReceiveMessageWaitTimeSeconds: 20, // Long polling
542
+ },
543
+ };
544
+
545
+ console.log(' ✓ Created DbMigrationQueue resource');
546
+
547
+ // Add S3 bucket name to environment (for migration Lambda functions)
548
+ result.environment.S3_BUCKET_NAME = { Ref: 'FriggMigrationStatusBucket' };
549
+ result.environment.MIGRATION_STATUS_BUCKET = { Ref: 'FriggMigrationStatusBucket' };
550
+
551
+ // Add queue URL to environment
552
+ result.environment.DB_MIGRATION_QUEUE_URL = { Ref: 'DbMigrationQueue' };
553
+
554
+ // Hardcode DB_TYPE for PostgreSQL-only migrations
555
+ result.environment.DB_TYPE = 'postgresql';
556
+
557
+ console.log(' ✓ Added S3_BUCKET_NAME, DB_MIGRATION_QUEUE_URL, and DB_TYPE environment variables');
558
+
559
+ // Add IAM permissions for SQS (for Lambda functions)
560
+ result.iamStatements.push({
561
+ Effect: 'Allow',
562
+ Action: [
563
+ 'sqs:SendMessage',
564
+ 'sqs:GetQueueUrl',
565
+ 'sqs:GetQueueAttributes',
566
+ ],
567
+ Resource: { 'Fn::GetAtt': ['DbMigrationQueue', 'Arn'] },
568
+ });
569
+
570
+ console.log(' ✓ Added SQS IAM permissions');
571
+
572
+ // Add IAM permissions for S3 (migration status storage)
573
+ // Object-level permissions (put, get, delete)
574
+ result.iamStatements.push({
575
+ Effect: 'Allow',
576
+ Action: [
577
+ 's3:PutObject',
578
+ 's3:GetObject',
579
+ 's3:DeleteObject',
580
+ ],
581
+ Resource: {
582
+ 'Fn::Join': [
583
+ '',
584
+ [
585
+ { 'Fn::GetAtt': ['FriggMigrationStatusBucket', 'Arn'] },
586
+ '/migrations/*',
587
+ ],
588
+ ],
589
+ },
590
+ });
591
+
592
+ // Bucket-level permissions (list objects)
593
+ result.iamStatements.push({
594
+ Effect: 'Allow',
595
+ Action: ['s3:ListBucket'],
596
+ Resource: { 'Fn::GetAtt': ['FriggMigrationStatusBucket', 'Arn'] },
597
+ });
598
+
599
+ console.log(' ✓ Added S3 IAM permissions for migration status tracking');
600
+
601
+ // Add IAM permission for router to invoke worker Lambda
602
+ result.iamStatements.push({
603
+ Effect: 'Allow',
604
+ Action: ['lambda:InvokeFunction'],
605
+ Resource: {
606
+ 'Fn::Sub': 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${AWS::StackName}-dbMigrationWorker',
607
+ },
608
+ });
609
+
610
+ console.log(' ✓ Added Lambda invocation permissions for router → worker');
611
+ }
612
+
613
+ /**
614
+ * Use external migration resources (S3 bucket and SQS queue)
615
+ * Only references external resources - Lambda functions are defined in serverless.yml
616
+ */
617
+ async useExternalMigrationResources(decisions, appDefinition, result) {
618
+ // Reference external bucket
619
+ const bucketName = decisions.bucket.physicalId;
620
+ if (!bucketName) {
621
+ throw new Error('External bucket specified but no migrationStatusBucket discovered');
622
+ }
623
+
624
+ // Reference external queue
625
+ const queueUrl = decisions.queue.physicalId;
626
+ if (!queueUrl) {
627
+ throw new Error('External queue specified but no migrationQueueUrl discovered');
628
+ }
629
+
630
+ console.log(` ✓ Using external S3 bucket: ${bucketName}`);
631
+ console.log(` ✓ Using external SQS queue: ${queueUrl}`);
632
+
633
+ // Extract queue ARN from queue URL for IAM permissions
634
+ const queueArn = queueUrl.replace('https://sqs.', 'arn:aws:sqs:')
635
+ .replace('.amazonaws.com/', ':')
636
+ .replace(/\//g, ':');
637
+
638
+ // Add environment variables (using external resource names/URLs)
639
+ result.environment.S3_BUCKET_NAME = bucketName;
640
+ result.environment.MIGRATION_STATUS_BUCKET = bucketName;
641
+ result.environment.DB_MIGRATION_QUEUE_URL = queueUrl;
642
+ result.environment.DB_TYPE = 'postgresql';
643
+
644
+ console.log(' ✓ Added S3_BUCKET_NAME, DB_MIGRATION_QUEUE_URL, and DB_TYPE environment variables');
645
+
646
+ // Add IAM permissions for external SQS queue
647
+ result.iamStatements.push({
648
+ Effect: 'Allow',
649
+ Action: [
650
+ 'sqs:SendMessage',
651
+ 'sqs:GetQueueUrl',
652
+ 'sqs:GetQueueAttributes',
653
+ ],
654
+ Resource: queueArn,
655
+ });
656
+
657
+ console.log(' ✓ Added SQS IAM permissions');
658
+
659
+ // Add IAM permissions for external S3 bucket
660
+ const bucketArn = `arn:aws:s3:::${bucketName}`;
661
+ result.iamStatements.push({
662
+ Effect: 'Allow',
663
+ Action: [
664
+ 's3:PutObject',
665
+ 's3:GetObject',
666
+ 's3:DeleteObject',
667
+ ],
668
+ Resource: `${bucketArn}/migrations/*`,
669
+ });
670
+
671
+ result.iamStatements.push({
672
+ Effect: 'Allow',
673
+ Action: ['s3:ListBucket'],
674
+ Resource: bucketArn,
675
+ });
676
+
677
+ console.log(' ✓ Added S3 IAM permissions for migration status tracking');
678
+
679
+ // Add IAM permission for router to invoke worker Lambda
680
+ result.iamStatements.push({
681
+ Effect: 'Allow',
682
+ Action: ['lambda:InvokeFunction'],
683
+ Resource: {
684
+ 'Fn::Sub': 'arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${AWS::StackName}-dbMigrationWorker',
685
+ },
686
+ });
687
+
688
+ console.log(' ✓ Added Lambda invocation permissions for router → worker');
689
+ }
690
+ }
691
+
692
+ module.exports = {
693
+ MigrationBuilder,
694
+ };
695
+