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

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 (247) hide show
  1. package/frigg-cli/README.md +1289 -0
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +279 -0
  3. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +649 -0
  4. package/frigg-cli/__tests__/unit/commands/deploy.test.js +320 -0
  5. package/frigg-cli/__tests__/unit/commands/doctor.test.js +309 -0
  6. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +97 -0
  7. package/frigg-cli/__tests__/unit/commands/install.test.js +400 -0
  8. package/frigg-cli/__tests__/unit/commands/ui.test.js +346 -0
  9. package/frigg-cli/__tests__/unit/dependencies.test.js +74 -0
  10. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +397 -0
  11. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +345 -0
  12. package/frigg-cli/__tests__/unit/version-detection.test.js +171 -0
  13. package/frigg-cli/__tests__/utils/mock-factory.js +270 -0
  14. package/frigg-cli/__tests__/utils/prisma-mock.js +194 -0
  15. package/frigg-cli/__tests__/utils/test-fixtures.js +463 -0
  16. package/frigg-cli/__tests__/utils/test-setup.js +287 -0
  17. package/frigg-cli/auth-command/CLAUDE.md +293 -0
  18. package/frigg-cli/auth-command/README.md +450 -0
  19. package/frigg-cli/auth-command/api-key-flow.js +153 -0
  20. package/frigg-cli/auth-command/auth-tester.js +344 -0
  21. package/frigg-cli/auth-command/credential-storage.js +182 -0
  22. package/frigg-cli/auth-command/index.js +256 -0
  23. package/frigg-cli/auth-command/json-schema-form.js +67 -0
  24. package/frigg-cli/auth-command/module-loader.js +172 -0
  25. package/frigg-cli/auth-command/oauth-callback-server.js +431 -0
  26. package/frigg-cli/auth-command/oauth-flow.js +195 -0
  27. package/frigg-cli/auth-command/utils/browser.js +30 -0
  28. package/frigg-cli/build-command/index.js +17 -3
  29. package/frigg-cli/db-setup-command/index.js +246 -0
  30. package/frigg-cli/deploy-command/SPEC-DEPLOY-DRY-RUN.md +981 -0
  31. package/frigg-cli/deploy-command/index.js +339 -23
  32. package/frigg-cli/doctor-command/index.js +335 -0
  33. package/frigg-cli/generate-command/__tests__/generate-command.test.js +301 -0
  34. package/frigg-cli/generate-command/azure-generator.js +43 -0
  35. package/frigg-cli/generate-command/gcp-generator.js +47 -0
  36. package/frigg-cli/generate-command/index.js +333 -0
  37. package/frigg-cli/generate-command/terraform-generator.js +555 -0
  38. package/frigg-cli/generate-iam-command.js +119 -0
  39. package/frigg-cli/index.js +188 -1
  40. package/frigg-cli/index.test.js +1 -4
  41. package/frigg-cli/init-command/backend-first-handler.js +756 -0
  42. package/frigg-cli/init-command/index.js +93 -0
  43. package/frigg-cli/init-command/template-handler.js +143 -0
  44. package/frigg-cli/install-command/index.js +1 -4
  45. package/frigg-cli/jest.config.js +124 -0
  46. package/frigg-cli/package.json +63 -0
  47. package/frigg-cli/repair-command/index.js +564 -0
  48. package/frigg-cli/ssm-command/index.js +308 -0
  49. package/frigg-cli/ssm-command/index.test.js +318 -0
  50. package/frigg-cli/start-command/index.js +118 -5
  51. package/frigg-cli/start-command/start-command.test.js +297 -0
  52. package/frigg-cli/test/init-command.test.js +180 -0
  53. package/frigg-cli/test/npm-registry.test.js +319 -0
  54. package/frigg-cli/ui-command/index.js +154 -0
  55. package/frigg-cli/utils/app-resolver.js +319 -0
  56. package/frigg-cli/utils/backend-path.js +16 -17
  57. package/frigg-cli/utils/database-validator.js +167 -0
  58. package/frigg-cli/utils/error-messages.js +329 -0
  59. package/frigg-cli/utils/npm-registry.js +167 -0
  60. package/frigg-cli/utils/process-manager.js +199 -0
  61. package/frigg-cli/utils/repo-detection.js +405 -0
  62. package/infrastructure/ARCHITECTURE.md +487 -0
  63. package/infrastructure/CLAUDE.md +481 -0
  64. package/infrastructure/HEALTH.md +468 -0
  65. package/infrastructure/README.md +540 -0
  66. package/infrastructure/__tests__/fixtures/mock-aws-resources.js +391 -0
  67. package/infrastructure/__tests__/helpers/test-utils.js +275 -0
  68. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  69. package/infrastructure/__tests__/scoped-environment.test.js +126 -0
  70. package/infrastructure/__tests__/ssm-preload-node-options.test.js +79 -0
  71. package/infrastructure/__tests__/template-generation.test.js +687 -0
  72. package/infrastructure/create-frigg-infrastructure.js +129 -20
  73. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +630 -0
  74. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +1317 -0
  75. package/infrastructure/docs/WEBSOCKET-CONFIGURATION.md +105 -0
  76. package/infrastructure/docs/deployment-instructions.md +268 -0
  77. package/infrastructure/docs/generate-iam-command.md +278 -0
  78. package/infrastructure/docs/iam-policy-templates.md +193 -0
  79. package/infrastructure/domains/admin-scripts/admin-script-builder.js +571 -0
  80. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +1047 -0
  81. package/infrastructure/domains/admin-scripts/index.js +5 -0
  82. package/infrastructure/domains/database/aurora-builder.js +857 -0
  83. package/infrastructure/domains/database/aurora-builder.test.js +960 -0
  84. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  85. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  86. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  87. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  88. package/infrastructure/domains/database/migration-builder.js +757 -0
  89. package/infrastructure/domains/database/migration-builder.test.js +454 -0
  90. package/infrastructure/domains/database/migration-resolver.js +163 -0
  91. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  92. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  93. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  94. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  95. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  96. package/infrastructure/domains/health/application/ports/index.js +26 -0
  97. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  98. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  99. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  100. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  101. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  102. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  103. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  104. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  105. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  106. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  107. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  108. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  109. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  110. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  111. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  112. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  113. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  114. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  115. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  116. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  117. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  118. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  119. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  120. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  121. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  122. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  123. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  124. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  125. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  126. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  127. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  128. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  129. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  130. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  131. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  132. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  133. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  134. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  135. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  136. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  137. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  138. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  139. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  140. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  141. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  142. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  143. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  144. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  145. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  146. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  147. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  148. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  149. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  150. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  151. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  152. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  153. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  154. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  155. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  156. package/infrastructure/domains/integration/integration-builder.js +668 -0
  157. package/infrastructure/domains/integration/integration-builder.test.js +1116 -0
  158. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  159. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  160. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  161. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  162. package/infrastructure/domains/networking/vpc-builder.js +2101 -0
  163. package/infrastructure/domains/networking/vpc-builder.test.js +2001 -0
  164. package/infrastructure/domains/networking/vpc-discovery.js +184 -0
  165. package/infrastructure/domains/networking/vpc-discovery.test.js +368 -0
  166. package/infrastructure/domains/networking/vpc-resolver.js +514 -0
  167. package/infrastructure/domains/networking/vpc-resolver.test.js +841 -0
  168. package/infrastructure/domains/parameters/offload-utils.js +197 -0
  169. package/infrastructure/domains/parameters/offload-utils.test.js +206 -0
  170. package/infrastructure/domains/parameters/ssm-builder.js +132 -0
  171. package/infrastructure/domains/parameters/ssm-builder.test.js +346 -0
  172. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  173. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  174. package/infrastructure/domains/scheduler/scheduler-builder.js +247 -0
  175. package/infrastructure/domains/scheduler/scheduler-builder.test.js +118 -0
  176. package/infrastructure/domains/security/iam-generator.js +852 -0
  177. package/infrastructure/domains/security/iam-generator.test.js +316 -0
  178. package/infrastructure/domains/security/kms-builder.js +415 -0
  179. package/infrastructure/domains/security/kms-builder.test.js +392 -0
  180. package/infrastructure/domains/security/kms-discovery.js +80 -0
  181. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  182. package/infrastructure/domains/security/kms-resolver.js +96 -0
  183. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  184. package/infrastructure/domains/security/templates/frigg-deployment-iam-stack.yaml +419 -0
  185. package/infrastructure/domains/security/templates/iam-policy-basic.json +219 -0
  186. package/infrastructure/domains/security/templates/iam-policy-full.json +294 -0
  187. package/infrastructure/domains/shared/base-builder.js +112 -0
  188. package/infrastructure/domains/shared/base-resolver.js +186 -0
  189. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  190. package/infrastructure/domains/shared/builder-orchestrator.js +226 -0
  191. package/infrastructure/domains/shared/builder-orchestrator.test.js +258 -0
  192. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  193. package/infrastructure/domains/shared/cloudformation-discovery.js +681 -0
  194. package/infrastructure/domains/shared/cloudformation-discovery.test.js +1320 -0
  195. package/infrastructure/domains/shared/environment-builder.js +222 -0
  196. package/infrastructure/domains/shared/environment-builder.test.js +648 -0
  197. package/infrastructure/domains/shared/function-environments.js +97 -0
  198. package/infrastructure/domains/shared/function-environments.test.js +146 -0
  199. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +579 -0
  200. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +416 -0
  201. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  202. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  203. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  204. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  205. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  206. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +306 -0
  207. package/infrastructure/domains/shared/resource-discovery.js +256 -0
  208. package/infrastructure/domains/shared/resource-discovery.test.js +757 -0
  209. package/infrastructure/domains/shared/types/app-definition.js +225 -0
  210. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  211. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  212. package/infrastructure/domains/shared/types/index.js +46 -0
  213. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  214. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  215. package/infrastructure/domains/shared/utilities/base-definition-factory.js +412 -0
  216. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +370 -0
  217. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  218. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  219. package/infrastructure/domains/shared/utilities/logging-config.js +82 -0
  220. package/infrastructure/domains/shared/utilities/logging-config.test.js +52 -0
  221. package/infrastructure/domains/shared/utilities/nested-node-modules.js +53 -0
  222. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +61 -0
  223. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +159 -0
  224. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +444 -0
  225. package/infrastructure/domains/shared/validation/env-validator.js +78 -0
  226. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  227. package/infrastructure/domains/shared/validation/plugin-validator.js +187 -0
  228. package/infrastructure/domains/shared/validation/plugin-validator.test.js +323 -0
  229. package/infrastructure/esbuild.config.js +53 -0
  230. package/infrastructure/infrastructure-composer.js +168 -0
  231. package/infrastructure/infrastructure-composer.test.js +2086 -0
  232. package/infrastructure/integration.test.js +381 -0
  233. package/infrastructure/scripts/build-prisma-layer.js +701 -0
  234. package/infrastructure/scripts/build-prisma-layer.test.js +170 -0
  235. package/infrastructure/scripts/build-time-discovery.js +238 -0
  236. package/infrastructure/scripts/build-time-discovery.test.js +379 -0
  237. package/infrastructure/scripts/run-discovery.js +110 -0
  238. package/infrastructure/scripts/verify-prisma-layer.js +72 -0
  239. package/management-ui/README.md +203 -0
  240. package/package.json +47 -16
  241. package/test/index.js +2 -4
  242. package/test/mock-api.js +1 -3
  243. package/test/mock-integration.js +4 -14
  244. package/.eslintrc.json +0 -3
  245. package/CHANGELOG.md +0 -132
  246. package/infrastructure/serverless-template.js +0 -279
  247. package/test/auther-definition-tester.js +0 -125
@@ -0,0 +1,668 @@
1
+ /**
2
+ * Integration Builder
3
+ *
4
+ * Domain Layer - Hexagonal Architecture
5
+ *
6
+ * Responsible for:
7
+ * - Creating SQS queues for each integration (CloudFormation resources)
8
+ * - Creating InternalErrorQueue (dead letter queue)
9
+ * - Creating Lambda function definitions (serverless template code)
10
+ * - Creating queue worker Lambda functions
11
+ * - Creating webhook handler functions
12
+ * - Configuring integration-specific routes and handlers
13
+ *
14
+ * Uses ownership-based architecture to support both stack-managed
15
+ * and externally-provided SQS queues.
16
+ */
17
+
18
+ const {
19
+ InfrastructureBuilder,
20
+ ValidationResult,
21
+ } = require('../shared/base-builder');
22
+ const IntegrationResourceResolver = require('./integration-resolver');
23
+ const {
24
+ createEmptyDiscoveryResult,
25
+ ResourceOwnership,
26
+ } = require('../shared/types');
27
+ const {
28
+ isScopedEnvironmentActive,
29
+ getIntegrationFunctionNames,
30
+ getAdminFunctionNames,
31
+ } = require('../shared/function-environments');
32
+ const {
33
+ nestedNodeModulesExcludes,
34
+ } = require('../shared/utilities/nested-node-modules');
35
+ const {
36
+ INTEGRATION_QUEUE_MAX_RECEIVE_COUNT,
37
+ QUEUE_MAX_RECEIVE_COUNT_ENV,
38
+ } = require('@friggframework/core/queues/queue-delivery');
39
+
40
+ class IntegrationBuilder extends InfrastructureBuilder {
41
+ constructor() {
42
+ super();
43
+ this.name = 'IntegrationBuilder';
44
+ }
45
+
46
+ shouldExecute(appDefinition) {
47
+ return (
48
+ Array.isArray(appDefinition.integrations) &&
49
+ appDefinition.integrations.length > 0
50
+ );
51
+ }
52
+
53
+ getDependencies() {
54
+ return []; // No dependencies - integrations can run independently
55
+ }
56
+
57
+ validate(appDefinition) {
58
+ const result = new ValidationResult();
59
+
60
+ if (!appDefinition.integrations) {
61
+ return result; // Not an error, just no integrations
62
+ }
63
+
64
+ if (!Array.isArray(appDefinition.integrations)) {
65
+ result.addError('integrations must be an array');
66
+ return result;
67
+ }
68
+
69
+ // Validate each integration
70
+ appDefinition.integrations.forEach((integration, index) => {
71
+ if (!integration?.Definition?.name) {
72
+ result.addError(
73
+ `Integration at index ${index} is missing Definition or name`
74
+ );
75
+ }
76
+ });
77
+
78
+ return result;
79
+ }
80
+
81
+ /**
82
+ * Build integration infrastructure using ownership-based architecture
83
+ */
84
+ async build(appDefinition, discoveredResources) {
85
+ console.log(`\n[${this.name}] Configuring integrations...`);
86
+ console.log(
87
+ ` Processing ${appDefinition.integrations.length} integrations...`
88
+ );
89
+
90
+ const usePrismaLayer = appDefinition.usePrismaLambdaLayer !== false;
91
+
92
+ const result = {
93
+ functions: {},
94
+ resources: {},
95
+ environment: {},
96
+ custom: {},
97
+ iamStatements: [],
98
+ };
99
+
100
+ // Get structured discovery result
101
+ const discovery =
102
+ discoveredResources._structured ||
103
+ this.convertFlatDiscoveryToStructured(discoveredResources);
104
+
105
+ // Use IntegrationResourceResolver to make ownership decisions
106
+ const resolver = new IntegrationResourceResolver();
107
+ const decisions = resolver.resolveAll(appDefinition, discovery);
108
+
109
+ console.log('\n 📋 Resource Ownership Decisions:');
110
+ console.log(
111
+ ` InternalErrorQueue: ${decisions.internalErrorQueue.ownership} - ${decisions.internalErrorQueue.reason}`
112
+ );
113
+
114
+ // Log per-integration decisions
115
+ Object.keys(decisions.integrations).forEach((integrationName) => {
116
+ const queueDecision = decisions.integrations[integrationName].queue;
117
+ console.log(
118
+ ` ${integrationName}Queue: ${queueDecision.ownership} - ${queueDecision.reason}`
119
+ );
120
+ });
121
+
122
+ // Build resources based on ownership decisions
123
+ await this.buildFromDecisions(
124
+ decisions,
125
+ appDefinition,
126
+ result,
127
+ usePrismaLayer
128
+ );
129
+
130
+ console.log(`[${this.name}] ✅ Integration configuration completed`);
131
+ return result;
132
+ }
133
+
134
+ /**
135
+ * Convert flat discovery to structured discovery
136
+ * Provides backwards compatibility
137
+ */
138
+ convertFlatDiscoveryToStructured(flatDiscovery) {
139
+ const discovery = createEmptyDiscoveryResult();
140
+
141
+ if (!flatDiscovery) {
142
+ return discovery;
143
+ }
144
+
145
+ // Check if resources are from CloudFormation stack
146
+ if (flatDiscovery.fromCloudFormationStack) {
147
+ discovery.fromCloudFormation = true;
148
+ discovery.stackName = flatDiscovery.stackName || 'assumed-stack';
149
+
150
+ // Add stack-managed resources from existingLogicalIds
151
+ const existingLogicalIds = flatDiscovery.existingLogicalIds || [];
152
+ existingLogicalIds.forEach((logicalId) => {
153
+ let resourceType = '';
154
+ let physicalId = '';
155
+
156
+ // Determine resource type and physical ID
157
+ if (logicalId === 'InternalErrorQueue') {
158
+ resourceType = 'AWS::SQS::Queue';
159
+ physicalId = flatDiscovery.internalErrorQueueUrl;
160
+ } else if (logicalId.endsWith('Queue')) {
161
+ // Integration-specific queue (e.g., SlackQueue, HubspotQueue)
162
+ resourceType = 'AWS::SQS::Queue';
163
+ const integrationName = logicalId
164
+ .replace('Queue', '')
165
+ .toLowerCase();
166
+ physicalId = flatDiscovery[`${integrationName}QueueUrl`];
167
+ }
168
+
169
+ if (physicalId && typeof physicalId === 'string') {
170
+ discovery.stackManaged.push({
171
+ logicalId,
172
+ physicalId,
173
+ resourceType,
174
+ });
175
+ }
176
+ });
177
+ }
178
+
179
+ return discovery;
180
+ }
181
+
182
+ /**
183
+ * Build integration resources based on ownership decisions
184
+ */
185
+ async buildFromDecisions(
186
+ decisions,
187
+ appDefinition,
188
+ result,
189
+ usePrismaLayer = true
190
+ ) {
191
+ // Create package config first — needed by all Lambda functions including DLQ processor
192
+ const functionPackageConfig = this.createFunctionPackageConfig(
193
+ usePrismaLayer,
194
+ appDefinition
195
+ );
196
+
197
+ // Create InternalErrorQueue if ownership = STACK
198
+ const shouldCreateInternalErrorQueue =
199
+ decisions.internalErrorQueue.ownership === ResourceOwnership.STACK;
200
+
201
+ if (shouldCreateInternalErrorQueue) {
202
+ console.log(' → Creating InternalErrorQueue in stack');
203
+ this.createInternalErrorQueue(result, functionPackageConfig);
204
+ } else {
205
+ console.log(' → Using external InternalErrorQueue');
206
+ this.useExternalInternalErrorQueue(
207
+ decisions.internalErrorQueue,
208
+ result,
209
+ functionPackageConfig
210
+ );
211
+ }
212
+
213
+ for (const integration of appDefinition.integrations) {
214
+ const integrationName = integration.Definition.name;
215
+ const queueDecision = decisions.integrations[integrationName].queue;
216
+
217
+ console.log(`\n Adding integration: ${integrationName}`);
218
+
219
+ // Create Lambda function definitions (serverless template code)
220
+ await this.createFunctionDefinitions(
221
+ integration,
222
+ functionPackageConfig,
223
+ result,
224
+ usePrismaLayer
225
+ );
226
+
227
+ // Create or reference SQS queue based on ownership decision
228
+ const shouldCreateQueue =
229
+ queueDecision.ownership === ResourceOwnership.STACK;
230
+
231
+ if (shouldCreateQueue) {
232
+ console.log(
233
+ ` ✓ Creating ${integrationName}Queue in stack`
234
+ );
235
+ this.createIntegrationQueue(
236
+ integrationName,
237
+ result,
238
+ appDefinition
239
+ );
240
+ } else {
241
+ console.log(` ✓ Using external ${integrationName}Queue`);
242
+ this.useExternalIntegrationQueue(
243
+ integrationName,
244
+ queueDecision,
245
+ result,
246
+ appDefinition
247
+ );
248
+ }
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Create function package exclusion configuration
254
+ */
255
+ createFunctionPackageConfig(usePrismaLayer = true, appDefinition = {}) {
256
+ return {
257
+ exclude: [
258
+ // Exclude AWS SDK (provided by Lambda runtime)
259
+ 'node_modules/aws-sdk/**',
260
+ 'node_modules/@aws-sdk/**',
261
+
262
+ // Exclude Prisma (provided via Lambda Layer)
263
+ ...(usePrismaLayer
264
+ ? [
265
+ 'node_modules/@prisma/**',
266
+ 'node_modules/.prisma/**',
267
+ 'node_modules/prisma/**',
268
+ 'node_modules/@friggframework/core/generated/**',
269
+ ]
270
+ : []),
271
+
272
+ ...nestedNodeModulesExcludes(appDefinition, usePrismaLayer),
273
+
274
+ // Exclude build tools (not needed at runtime)
275
+ 'node_modules/esbuild/**',
276
+ 'node_modules/@esbuild/**',
277
+ 'node_modules/typescript/**',
278
+ 'node_modules/webpack/**',
279
+ 'node_modules/osls/**',
280
+ 'node_modules/serverless-esbuild/**',
281
+ 'node_modules/serverless-jetpack/**',
282
+ 'node_modules/serverless-offline/**',
283
+ 'node_modules/serverless-offline-sqs/**',
284
+ 'node_modules/serverless-dotenv-plugin/**',
285
+ 'node_modules/serverless-kms-grants/**',
286
+ // Note: DO NOT exclude serverless-http - it's a runtime dependency!
287
+
288
+ // Exclude dev/test dependencies
289
+ 'node_modules/@friggframework/test/**',
290
+ 'node_modules/@friggframework/eslint-config/**',
291
+ 'node_modules/@friggframework/prettier-config/**',
292
+ 'node_modules/jest/**',
293
+ 'node_modules/prettier/**',
294
+ 'node_modules/eslint/**',
295
+
296
+ // Exclude local dev files
297
+ 'deploy.log',
298
+ '.env.backup',
299
+ 'docker-compose.yml',
300
+ 'jest.config.js',
301
+ 'jest.unit.config.js',
302
+ '.eslintrc.json',
303
+ '.prettierrc',
304
+ '.prettierignore',
305
+ '.markdownlintignore',
306
+ 'package-lock.json',
307
+
308
+ // Exclude development/test files (keep src/ - needed for integrations and api-modules)
309
+ 'coverage/**',
310
+ 'test/**',
311
+ 'layers/**',
312
+ // Note: DO NOT exclude src/** - handlers need src/integrations and src/api-modules at runtime
313
+ '**/*.test.js',
314
+ '**/*.spec.js',
315
+ '**/.claude-flow/**',
316
+ '**/.swarm/**',
317
+ ],
318
+ };
319
+ }
320
+
321
+ /**
322
+ * Create Lambda function definitions for an integration
323
+ * These are serverless framework template function definitions
324
+ */
325
+ async createFunctionDefinitions(
326
+ integration,
327
+ functionPackageConfig,
328
+ result,
329
+ usePrismaLayer = true
330
+ ) {
331
+ const integrationName = integration.Definition.name;
332
+
333
+ // Add webhook handler if enabled (BEFORE catch-all proxy route)
334
+ // CRITICAL: Webhook routes must be defined before the catch-all {proxy+} route
335
+ // to ensure proper route matching in AWS API Gateway/HTTP API
336
+ const webhookConfig = integration.Definition.webhooks;
337
+ if (
338
+ webhookConfig &&
339
+ (webhookConfig === true || webhookConfig.enabled === true)
340
+ ) {
341
+ const webhookFunctionName = `${integrationName}Webhook`;
342
+
343
+ result.functions[webhookFunctionName] = {
344
+ handler: `node_modules/@friggframework/core/handlers/routers/integration-webhook-routers.handlers.${integrationName}Webhook.handler`,
345
+ skipEsbuild: true, // Nested exports in node_modules - skip esbuild bundling
346
+ package: functionPackageConfig,
347
+ ...(usePrismaLayer && {
348
+ layers: [{ Ref: 'PrismaLambdaLayer' }],
349
+ }), // Webhook handlers need Prisma for credential lookups
350
+ events: [
351
+ {
352
+ httpApi: {
353
+ path: `/api/${integrationName}-integration/webhooks`,
354
+ method: 'POST',
355
+ },
356
+ },
357
+ {
358
+ httpApi: {
359
+ path: `/api/${integrationName}-integration/webhooks/{integrationId}`,
360
+ method: 'POST',
361
+ },
362
+ },
363
+ ],
364
+ };
365
+ console.log(` ✓ Webhook handler function defined`);
366
+ }
367
+
368
+ // Create HTTP API handler for integration (catch-all route AFTER
369
+ // webhooks). Extension routes get their own functions below.
370
+ result.functions[integrationName] = {
371
+ handler: `node_modules/@friggframework/core/handlers/routers/integration-defined-routers.handlers.${integrationName}.handler`,
372
+ skipEsbuild: true, // Nested exports in node_modules - skip esbuild bundling
373
+ package: functionPackageConfig,
374
+ ...(usePrismaLayer && { layers: [{ Ref: 'PrismaLambdaLayer' }] }), // HTTP handlers need Prisma for integration queries
375
+ events: [
376
+ {
377
+ httpApi: {
378
+ path: `/api/${integrationName}-integration/{proxy+}`,
379
+ method: 'ANY',
380
+ },
381
+ },
382
+ ],
383
+ };
384
+ console.log(` ✓ HTTP handler function defined`);
385
+
386
+ // One serverless function per extension binding, namespaced under
387
+ // /{bindingKey}. Prisma layer attached only when useDatabase is true.
388
+ const sanitizeBindingKey = (name) =>
389
+ String(name).replace(/[^A-Za-z0-9]/g, '');
390
+ const extensionEntries = Object.entries(
391
+ integration.Definition.extensions || {}
392
+ );
393
+ for (const [bindingKey, binding] of extensionEntries) {
394
+ const extension = binding && binding.extension;
395
+ const routes = (extension && extension.routes) || [];
396
+ if (routes.length === 0) continue;
397
+ const useDatabase =
398
+ binding.useDatabase ??
399
+ (extension && extension.useDatabase) ??
400
+ false;
401
+ // Wire contract: core's integration-defined-routers derives the
402
+ // identical handler key. Keep both in sync.
403
+ const fnName = `${integrationName}__${sanitizeBindingKey(
404
+ bindingKey
405
+ )}`;
406
+ // Distinct binding keys can sanitize to the same fnName — fail loud rather than overwrite.
407
+ if (
408
+ Object.prototype.hasOwnProperty.call(result.functions, fnName)
409
+ ) {
410
+ throw new Error(
411
+ `Integration "${integrationName}" extension function conflict: ` +
412
+ `binding "${bindingKey}" sanitizes to "${fnName}", which is already taken. ` +
413
+ `Use binding keys that are distinct after stripping non-alphanumeric characters.`
414
+ );
415
+ }
416
+ result.functions[fnName] = {
417
+ handler: `node_modules/@friggframework/core/handlers/routers/integration-defined-routers.handlers.${fnName}.handler`,
418
+ skipEsbuild: true,
419
+ package: functionPackageConfig,
420
+ ...(usePrismaLayer &&
421
+ useDatabase && { layers: [{ Ref: 'PrismaLambdaLayer' }] }),
422
+ events: routes.map((route) => ({
423
+ httpApi: {
424
+ path: `/api/${integrationName}-integration/${bindingKey}${route.path}`,
425
+ method: route.method,
426
+ },
427
+ })),
428
+ };
429
+ console.log(
430
+ ` ✓ Extension handler function defined: ${fnName} (useDatabase: ${useDatabase})`
431
+ );
432
+ }
433
+
434
+ // Create Queue Worker function
435
+ const queueWorkerName = `${integrationName}QueueWorker`;
436
+ result.functions[queueWorkerName] = {
437
+ handler: `node_modules/@friggframework/core/handlers/workers/integration-defined-workers.handlers.${integrationName}.queueWorker`,
438
+ skipEsbuild: true, // Nested exports in node_modules - skip esbuild bundling
439
+ package: functionPackageConfig,
440
+ ...(usePrismaLayer && { layers: [{ Ref: 'PrismaLambdaLayer' }] }), // Queue workers need Prisma for database operations
441
+ reservedConcurrency: 20,
442
+ events: [
443
+ {
444
+ sqs: {
445
+ arn: {
446
+ 'Fn::GetAtt': [
447
+ `${this.capitalizeFirst(integrationName)}Queue`,
448
+ 'Arn',
449
+ ],
450
+ },
451
+ batchSize: 1,
452
+ functionResponseType: 'ReportBatchItemFailures',
453
+ },
454
+ },
455
+ ],
456
+ timeout: 900, // 15 minutes max for queue workers (Lambda maximum)
457
+ };
458
+ console.log(` ✓ Queue worker function defined`);
459
+ }
460
+
461
+ /**
462
+ * Create InternalErrorQueue CloudFormation resource
463
+ */
464
+ createInternalErrorQueue(result, functionPackageConfig) {
465
+ const queueName =
466
+ '${self:service}-${self:provider.stage}-InternalErrorQueue';
467
+
468
+ result.custom.InternalErrorQueue = queueName;
469
+
470
+ result.resources.InternalErrorQueue = {
471
+ Type: 'AWS::SQS::Queue',
472
+ Properties: {
473
+ QueueName: '${self:custom.InternalErrorQueue}',
474
+ MessageRetentionPeriod: 1209600, // 14 days
475
+ VisibilityTimeout: 300, // 5 minutes — must be >= 6x DLQ processor Lambda timeout (30s × 6 = 180s)
476
+ },
477
+ };
478
+
479
+ this.createDLQObservability(
480
+ result,
481
+ functionPackageConfig,
482
+ {
483
+ 'Fn::GetAtt': ['InternalErrorQueue', 'Arn'],
484
+ },
485
+ {
486
+ 'Fn::GetAtt': ['InternalErrorQueue', 'QueueName'],
487
+ }
488
+ );
489
+
490
+ console.log(' ✓ Created InternalErrorQueue resource');
491
+ }
492
+
493
+ /**
494
+ * Use external InternalErrorQueue
495
+ */
496
+ useExternalInternalErrorQueue(decision, result, functionPackageConfig) {
497
+ // Add ARN to environment for Lambda functions
498
+ result.environment.INTERNAL_ERROR_QUEUE_ARN = decision.physicalId;
499
+
500
+ // Extract queue name from ARN for CloudWatch dimensions
501
+ const arnParts = decision.physicalId.split(':');
502
+ const queueName = arnParts[arnParts.length - 1];
503
+
504
+ this.createDLQObservability(
505
+ result,
506
+ functionPackageConfig,
507
+ decision.physicalId,
508
+ queueName
509
+ );
510
+
511
+ console.log(
512
+ ` ✓ Using external InternalErrorQueue: ${decision.physicalId}`
513
+ );
514
+ }
515
+
516
+ /**
517
+ * Create DLQ observability resources (alarm + processor Lambda).
518
+ * Called for both stack-owned and external InternalErrorQueues.
519
+ */
520
+ createDLQObservability(result, functionPackageConfig, queueArn, queueName) {
521
+ // CloudWatch Alarm: fires when any message lands in the DLQ
522
+ result.resources.DLQMessageAlarm = {
523
+ Type: 'AWS::CloudWatch::Alarm',
524
+ Properties: {
525
+ AlarmDescription:
526
+ 'Messages in dead-letter queue — integration queue processing failures',
527
+ Namespace: 'AWS/SQS',
528
+ MetricName: 'ApproximateNumberOfMessagesVisible',
529
+ Statistic: 'Maximum',
530
+ Threshold: 500,
531
+ ComparisonOperator: 'GreaterThanThreshold',
532
+ EvaluationPeriods: 1,
533
+ Period: 300,
534
+ AlarmActions: [{ Ref: 'InternalErrorBridgeTopic' }],
535
+ Dimensions: [{ Name: 'QueueName', Value: queueName }],
536
+ },
537
+ };
538
+
539
+ // DLQ processor Lambda: logs failed messages with structured context
540
+ result.functions.dlqProcessor = {
541
+ handler:
542
+ 'node_modules/@friggframework/core/handlers/workers/dlq-processor.dlqProcessor',
543
+ skipEsbuild: true,
544
+ package: functionPackageConfig,
545
+ reservedConcurrency: 1,
546
+ timeout: 30,
547
+ events: [
548
+ {
549
+ sqs: {
550
+ arn: queueArn,
551
+ batchSize: 10,
552
+ functionResponseType: 'ReportBatchItemFailures',
553
+ },
554
+ },
555
+ ],
556
+ };
557
+
558
+ console.log(' ✓ Created DLQ CloudWatch alarm');
559
+ console.log(' ✓ Created DLQ processor Lambda');
560
+ }
561
+
562
+ /**
563
+ * Create integration-specific SQS queue CloudFormation resource
564
+ */
565
+ createIntegrationQueue(integrationName, result, appDefinition) {
566
+ const queueReference = `${this.capitalizeFirst(integrationName)}Queue`;
567
+ const queueName = `\${self:service}--\${self:provider.stage}-${queueReference}`;
568
+
569
+ result.resources[queueReference] = {
570
+ Type: 'AWS::SQS::Queue',
571
+ Properties: {
572
+ QueueName: `\${self:custom.${queueReference}}`,
573
+ MessageRetentionPeriod: 345600, // 4 days (SQS default)
574
+ VisibilityTimeout: 1800,
575
+ RedrivePolicy: {
576
+ maxReceiveCount: INTEGRATION_QUEUE_MAX_RECEIVE_COUNT,
577
+ deadLetterTargetArn: {
578
+ 'Fn::GetAtt': ['InternalErrorQueue', 'Arn'],
579
+ },
580
+ },
581
+ },
582
+ };
583
+
584
+ const queueWorker = result.functions[`${integrationName}QueueWorker`];
585
+ queueWorker.environment = {
586
+ ...queueWorker.environment,
587
+ [QUEUE_MAX_RECEIVE_COUNT_ENV]: String(
588
+ INTEGRATION_QUEUE_MAX_RECEIVE_COUNT
589
+ ),
590
+ };
591
+
592
+ // Add queue URL to environment
593
+ this.setQueueUrlEnvironment(
594
+ integrationName,
595
+ { Ref: queueReference },
596
+ result,
597
+ appDefinition
598
+ );
599
+
600
+ // Add queue name to custom section
601
+ result.custom[queueReference] = queueName;
602
+
603
+ console.log(` ✓ Created ${queueReference} resource`);
604
+ }
605
+
606
+ /**
607
+ * Use external integration queue
608
+ */
609
+ useExternalIntegrationQueue(
610
+ integrationName,
611
+ decision,
612
+ result,
613
+ appDefinition
614
+ ) {
615
+ // Add queue URL to environment for Lambda functions
616
+ this.setQueueUrlEnvironment(
617
+ integrationName,
618
+ decision.physicalId,
619
+ result,
620
+ appDefinition
621
+ );
622
+
623
+ console.log(` ✓ Using external queue: ${decision.physicalId}`);
624
+ }
625
+
626
+ /**
627
+ * Broadcast the queue URL app-wide, or — with lambda.scopedEnvironment —
628
+ * scope it to the functions that can actually enqueue: the shared auth
629
+ * router (dispatches integration actions synchronously), the admin-script
630
+ * functions (instantiate arbitrary integrations), and the owning
631
+ * integration's own functions.
632
+ */
633
+ setQueueUrlEnvironment(integrationName, value, result, appDefinition) {
634
+ const key = `${integrationName.toUpperCase()}_QUEUE_URL`;
635
+
636
+ if (!isScopedEnvironmentActive(appDefinition)) {
637
+ result.environment[key] = value;
638
+ return;
639
+ }
640
+
641
+ const integration = appDefinition.integrations.find(
642
+ (entry) => entry.Definition.name === integrationName
643
+ );
644
+ const targets = [
645
+ 'auth',
646
+ ...getAdminFunctionNames(appDefinition),
647
+ ...getIntegrationFunctionNames(integration),
648
+ ];
649
+
650
+ result.functionEnvironments = result.functionEnvironments || {};
651
+ for (const fnName of targets) {
652
+ result.functionEnvironments[fnName] = {
653
+ ...result.functionEnvironments[fnName],
654
+ [key]: value,
655
+ };
656
+ }
657
+ console.log(` ✓ Scoped ${key} to: ${targets.join(', ')}`);
658
+ }
659
+
660
+ /**
661
+ * Capitalize first letter of string (e.g., 'slack' -> 'Slack')
662
+ */
663
+ capitalizeFirst(str) {
664
+ return str.charAt(0).toUpperCase() + str.slice(1);
665
+ }
666
+ }
667
+
668
+ module.exports = { IntegrationBuilder };