@friggframework/devtools 2.0.0--canary.658.e11f3b0.0 → 2.0.0--canary.737.83b4e17.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 (102) hide show
  1. package/frigg-cli/README.md +115 -31
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +3 -0
  3. package/frigg-cli/__tests__/unit/commands/deploy.test.js +33 -24
  4. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  5. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  6. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  7. package/frigg-cli/__tests__/unit/commands/install.test.js +601 -341
  8. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  9. package/frigg-cli/__tests__/unit/commands/validate-wiring.test.js +92 -0
  10. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  11. package/frigg-cli/build-command/index.js +6 -0
  12. package/frigg-cli/deploy-command/index.js +6 -0
  13. package/frigg-cli/generate-command/index.js +1 -0
  14. package/frigg-cli/generate-iam-command.js +1 -0
  15. package/frigg-cli/index.js +22 -5
  16. package/frigg-cli/init-command/backend-first-handler.js +395 -551
  17. package/frigg-cli/init-command/deployment-modes.js +7 -0
  18. package/frigg-cli/init-command/index.js +82 -35
  19. package/frigg-cli/init-command/safe-path.js +58 -0
  20. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  21. package/frigg-cli/install-command/app-definition.js +174 -0
  22. package/frigg-cli/install-command/commit-changes.js +40 -8
  23. package/frigg-cli/install-command/environment-variables.js +15 -0
  24. package/frigg-cli/install-command/index.js +96 -21
  25. package/frigg-cli/install-command/install-package.js +77 -4
  26. package/frigg-cli/install-command/integration-file.js +20 -11
  27. package/frigg-cli/install-command/resolve-module.js +69 -0
  28. package/frigg-cli/install-command/template.js +102 -75
  29. package/frigg-cli/install-command/validate-package.js +36 -4
  30. package/frigg-cli/package.json +1 -1
  31. package/frigg-cli/start-command/index.js +4 -0
  32. package/frigg-cli/start-command/start-command.test.js +3 -0
  33. package/frigg-cli/templates/backend/README.md +267 -0
  34. package/frigg-cli/templates/backend/env.example +20 -0
  35. package/frigg-cli/templates/backend/gitignore +10 -0
  36. package/frigg-cli/templates/backend/index.js +114 -0
  37. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  38. package/frigg-cli/test/init-command.test.js +9 -2
  39. package/frigg-cli/validate-command/__tests__/init-validation.test.js +63 -0
  40. package/frigg-cli/validate-command/__tests__/integrations-checks.test.js +133 -0
  41. package/frigg-cli/validate-command/__tests__/validate-app-definition.test.js +443 -0
  42. package/frigg-cli/validate-command/__tests__/validate-command.test.js +262 -0
  43. package/frigg-cli/validate-command/checks/config.js +504 -0
  44. package/frigg-cli/validate-command/checks/integrations.js +274 -0
  45. package/frigg-cli/validate-command/format-report.js +58 -0
  46. package/frigg-cli/validate-command/index.js +107 -0
  47. package/frigg-cli/validate-command/load-app-definition.js +105 -0
  48. package/frigg-cli/validate-command/schema-issues.js +154 -0
  49. package/frigg-cli/validate-command/validate-app-definition.js +60 -0
  50. package/infrastructure/README.md +32 -5
  51. package/infrastructure/__tests__/helpers/bundled-prisma-engine-excludes.js +39 -0
  52. package/infrastructure/__tests__/management-api-gateway-routes.test.js +284 -0
  53. package/infrastructure/__tests__/postgres-config.test.js +245 -836
  54. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +151 -0
  55. package/infrastructure/__tests__/scoped-environment.test.js +3 -0
  56. package/infrastructure/__tests__/ssm-preload-node-options.test.js +3 -0
  57. package/infrastructure/__tests__/template-generation.test.js +39 -8
  58. package/infrastructure/app-definition-schema-contract.test.js +634 -0
  59. package/infrastructure/create-frigg-infrastructure.js +4 -1
  60. package/infrastructure/create-frigg-infrastructure.test.js +51 -0
  61. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +80 -98
  62. package/infrastructure/domains/admin-scripts/admin-script-builder.js +8 -2
  63. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +52 -6
  64. package/infrastructure/domains/database/aurora-builder.js +13 -2
  65. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  66. package/infrastructure/domains/database/migration-builder.js +21 -2
  67. package/infrastructure/domains/database/migration-builder.test.js +61 -6
  68. package/infrastructure/domains/database/migration-engines.js +93 -0
  69. package/infrastructure/domains/database/migration-engines.test.js +142 -0
  70. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  71. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  72. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  73. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  74. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  75. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  76. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  77. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  78. package/infrastructure/domains/integration/integration-builder.js +2 -0
  79. package/infrastructure/domains/integration/integration-builder.test.js +22 -6
  80. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  81. package/infrastructure/domains/networking/vpc-builder.test.js +26 -12
  82. package/infrastructure/domains/security/iam-generator.js +112 -5
  83. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  84. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  85. package/infrastructure/domains/shared/environment-builder.js +31 -5
  86. package/infrastructure/domains/shared/environment-builder.test.js +93 -7
  87. package/infrastructure/domains/shared/lambda-architectures.js +113 -0
  88. package/infrastructure/domains/shared/lambda-architectures.test.js +164 -0
  89. package/infrastructure/domains/shared/utilities/base-definition-factory.js +39 -3
  90. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +85 -5
  91. package/infrastructure/domains/shared/utilities/nested-node-modules.js +6 -5
  92. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +20 -26
  93. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +92 -12
  94. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +158 -6
  95. package/infrastructure/infrastructure-composer.js +12 -1
  96. package/infrastructure/infrastructure-composer.test.js +339 -794
  97. package/infrastructure/scripts/build-prisma-layer.js +136 -50
  98. package/infrastructure/scripts/build-prisma-layer.test.js +128 -7
  99. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  100. package/package.json +12 -10
  101. package/frigg-cli/index.test.js +0 -158
  102. package/infrastructure/integration.test.js +0 -381
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  const { createBaseDefinition } = require('./base-definition-factory');
8
+ const { itBundlesOnlyTheTargetPrismaEngine } = require('../../../__tests__/helpers/bundled-prisma-engine-excludes');
8
9
 
9
10
  describe('Base Definition Factory', () => {
10
11
  beforeEach(() => {
@@ -94,7 +95,19 @@ describe('Base Definition Factory', () => {
94
95
 
95
96
  expect(result.functions.auth.handler).toBe('node_modules/@friggframework/core/handlers/routers/auth.handler');
96
97
  expect(result.functions.auth.layers).toEqual([{ Ref: 'PrismaLambdaLayer' }]);
97
- expect(result.functions.auth.events).toHaveLength(3);
98
+ expect(
99
+ result.functions.auth.events.map(
100
+ (e) => `${e.httpApi.method} ${e.httpApi.path}`
101
+ )
102
+ ).toEqual([
103
+ 'ANY /api/integrations',
104
+ 'ANY /api/integrations/{proxy+}',
105
+ 'ANY /api/authorize',
106
+ 'ANY /api/entity',
107
+ 'ANY /api/entity/{proxy+}',
108
+ 'ANY /api/entities',
109
+ 'ANY /api/entities/{proxy+}',
110
+ ]);
98
111
  });
99
112
 
100
113
  it('should NOT include legacy dbMigrate function', () => {
@@ -121,6 +134,27 @@ describe('Base Definition Factory', () => {
121
134
  expect(result.resources.Resources.ApiGatewayAlarm5xx).toBeDefined();
122
135
  });
123
136
 
137
+ it('alarms on the HTTP API 5xx metric of the API osls creates', () => {
138
+ // The Frigg functions use `httpApi` events, so osls creates an
139
+ // API Gateway v2 HTTP API (logical ID HttpApi) with only the
140
+ // `$default` stage. HTTP APIs publish `5xx` (REST APIs publish
141
+ // `5XXError`) with the ApiId dimension; a Stage dimension set to
142
+ // the deploy stage name would never match `$default`.
143
+ const result = createBaseDefinition({}, {}, {});
144
+ const usesHttpApi = Object.values(result.functions).some((fn) =>
145
+ (fn.events || []).some((event) => event.httpApi)
146
+ );
147
+ expect(usesHttpApi).toBe(true);
148
+
149
+ const alarm = result.resources.Resources.ApiGatewayAlarm5xx;
150
+ expect(alarm.Properties).toMatchObject({
151
+ Namespace: 'AWS/ApiGateway',
152
+ MetricName: '5xx',
153
+ Dimensions: [{ Name: 'ApiId', Value: { Ref: 'HttpApi' } }],
154
+ AlarmActions: [{ Ref: 'InternalErrorBridgeTopic' }],
155
+ });
156
+ });
157
+
124
158
  it('should include base IAM permissions', () => {
125
159
  const result = createBaseDefinition({}, {}, {});
126
160
 
@@ -290,19 +324,65 @@ describe('Base Definition Factory', () => {
290
324
  });
291
325
 
292
326
 
293
- describe('nested node_modules (lambda.keepNestedNodeModules)', () => {
327
+ describe('Lambda architecture (architecture)', () => {
294
328
  const build = (appDefinition) => createBaseDefinition(appDefinition, {}, {}, true);
295
329
 
296
- it('excludes every nested node_modules from the core function packages by default', () => {
330
+ it('adds no architecture fields when the key is unset, so existing templates do not change', () => {
331
+ const result = build({ name: 'test-app' });
332
+
333
+ expect(result.provider.architecture).toBeUndefined();
334
+ expect(result.layers.prisma.compatibleArchitectures).toBeUndefined();
335
+ });
336
+
337
+ it.each(['x86_64', 'arm64'])(
338
+ 'sets provider.architecture and the layer compatibleArchitectures to %s when set',
339
+ (architecture) => {
340
+ const result = build({ name: 'test-app', architecture });
341
+
342
+ expect(result.provider.architecture).toBe(architecture);
343
+ expect(result.layers.prisma.compatibleArchitectures).toEqual([architecture]);
344
+ }
345
+ );
346
+
347
+ it('describes the layer without naming an engine, since the engine follows the architecture', () => {
297
348
  const result = build({ name: 'test-app' });
298
349
 
350
+ expect(result.layers.prisma.description).not.toContain('rhel');
351
+ });
352
+
353
+ it('rejects an architecture the registry does not know', () => {
354
+ expect(() => build({ name: 'test-app', architecture: 'aarch64' })).toThrow(
355
+ /aarch64/
356
+ );
357
+ });
358
+ });
359
+
360
+ describe('Lambda architecture with usePrismaLambdaLayer=false', () => {
361
+ const functionsOf = (usePrismaLayer, architecture) => {
362
+ const result = createBaseDefinition(
363
+ { name: 'test-app', ...(architecture && { architecture }) },
364
+ {},
365
+ {},
366
+ usePrismaLayer
367
+ );
368
+ return Object.values(result.functions);
369
+ };
370
+ itBundlesOnlyTheTargetPrismaEngine(functionsOf);
371
+ });
372
+
373
+ describe('nested node_modules (lambda.keepNestedNodeModules)', () => {
374
+ const build = (appDefinition) => createBaseDefinition(appDefinition, {}, {}, true);
375
+
376
+ it('excludes every nested node_modules from the core function packages when the app opts out', () => {
377
+ const result = build({ name: 'test-app', lambda: { keepNestedNodeModules: false } });
378
+
299
379
  for (const fn of ['auth', 'user', 'health']) {
300
380
  expect(result.functions[fn].package.exclude).toContain('node_modules/**/node_modules/**');
301
381
  }
302
382
  });
303
383
 
304
- it('keeps nested node_modules when the app opts in, still excluding nested Frigg, AWS SDK and Prisma copies', () => {
305
- const result = build({ name: 'test-app', lambda: { keepNestedNodeModules: true } });
384
+ it('keeps nested node_modules by default, still excluding nested Frigg, AWS SDK and Prisma copies', () => {
385
+ const result = build({ name: 'test-app' });
306
386
 
307
387
  for (const fn of ['auth', 'user', 'health']) {
308
388
  const { exclude } = result.functions[fn].package;
@@ -6,10 +6,11 @@
6
6
  * npm nests a package only when the root copy cannot satisfy the dependant's
7
7
  * range. Excluding every nested node_modules from a Lambda package therefore
8
8
  * rewires module resolution to whatever is hoisted, and drops a package
9
- * outright when the root copy is dev-only. Apps opt in to shipping the tree
10
- * the way npm resolved it with `lambda.keepNestedNodeModules: true`. Nested
11
- * copies of Frigg packages, the AWS SDK and Prisma stay excluded because the
12
- * app's single core, the Lambda runtime and the Prisma layer provide them.
9
+ * outright when the root copy is dev-only. Function packages ship the tree the
10
+ * way npm resolved it unless an app opts out with
11
+ * `lambda.keepNestedNodeModules: false`. Nested copies of Frigg packages, the
12
+ * AWS SDK and Prisma stay excluded because the app's single core, the Lambda
13
+ * runtime and the Prisma layer provide them.
13
14
  */
14
15
 
15
16
  const ALL_NESTED_NODE_MODULES = 'node_modules/**/node_modules/**';
@@ -19,7 +20,7 @@ const ALL_NESTED_NODE_MODULES = 'node_modules/**/node_modules/**';
19
20
  * @returns {boolean}
20
21
  */
21
22
  function keepsNestedNodeModules(appDefinition = {}) {
22
- return appDefinition.lambda?.keepNestedNodeModules === true;
23
+ return appDefinition.lambda?.keepNestedNodeModules !== false;
23
24
  }
24
25
 
25
26
  /**
@@ -8,20 +8,13 @@ const {
8
8
  nestedNodeModulesExcludes,
9
9
  } = require('./nested-node-modules');
10
10
 
11
- describe('nestedNodeModulesExcludes', () => {
12
- it('excludes every nested node_modules by default', () => {
13
- expect(nestedNodeModulesExcludes({}, true)).toEqual([
14
- 'node_modules/**/node_modules/**',
15
- ]);
16
- expect(ALL_NESTED_NODE_MODULES).toBe('node_modules/**/node_modules/**');
17
- });
11
+ const OPT_OUT = { lambda: { keepNestedNodeModules: false } };
18
12
 
19
- it('keeps nested node_modules when the app opts in, except Frigg, AWS SDK and Prisma copies', () => {
20
- const appDefinition = { lambda: { keepNestedNodeModules: true } };
21
-
22
- const excludes = nestedNodeModulesExcludes(appDefinition, true);
13
+ describe('nestedNodeModulesExcludes', () => {
14
+ it('keeps nested node_modules by default, except Frigg, AWS SDK and Prisma copies', () => {
15
+ const excludes = nestedNodeModulesExcludes({}, true);
23
16
 
24
- expect(excludes).not.toContain('node_modules/**/node_modules/**');
17
+ expect(excludes).not.toContain(ALL_NESTED_NODE_MODULES);
25
18
  expect(excludes).toEqual([
26
19
  'node_modules/**/node_modules/@friggframework/**',
27
20
  'node_modules/**/node_modules/aws-sdk/**',
@@ -32,30 +25,31 @@ describe('nestedNodeModulesExcludes', () => {
32
25
  });
33
26
 
34
27
  it('keeps nested Prisma copies when the app bundles Prisma instead of using the layer', () => {
35
- const appDefinition = { lambda: { keepNestedNodeModules: true } };
36
-
37
- const excludes = nestedNodeModulesExcludes(appDefinition, false);
38
-
39
- expect(excludes).toEqual([
28
+ expect(nestedNodeModulesExcludes({}, false)).toEqual([
40
29
  'node_modules/**/node_modules/@friggframework/**',
41
30
  'node_modules/**/node_modules/aws-sdk/**',
42
31
  'node_modules/**/node_modules/@aws-sdk/**',
43
32
  ]);
44
33
  });
34
+
35
+ it('excludes every nested node_modules when the app opts out', () => {
36
+ expect(nestedNodeModulesExcludes(OPT_OUT, true)).toEqual([
37
+ 'node_modules/**/node_modules/**',
38
+ ]);
39
+ expect(ALL_NESTED_NODE_MODULES).toBe('node_modules/**/node_modules/**');
40
+ });
45
41
  });
46
42
 
47
43
  describe('keepsNestedNodeModules', () => {
48
- it('is only enabled by the boolean true', () => {
49
- expect(
50
- keepsNestedNodeModules({ lambda: { keepNestedNodeModules: true } })
51
- ).toBe(true);
44
+ it('is only disabled by the boolean false', () => {
45
+ expect(keepsNestedNodeModules(OPT_OUT)).toBe(false);
52
46
  expect(
53
47
  keepsNestedNodeModules({
54
- lambda: { keepNestedNodeModules: 'true' },
48
+ lambda: { keepNestedNodeModules: true },
55
49
  })
56
- ).toBe(false);
57
- expect(keepsNestedNodeModules({ lambda: {} })).toBe(false);
58
- expect(keepsNestedNodeModules({})).toBe(false);
59
- expect(keepsNestedNodeModules()).toBe(false);
50
+ ).toBe(true);
51
+ expect(keepsNestedNodeModules({ lambda: {} })).toBe(true);
52
+ expect(keepsNestedNodeModules({})).toBe(true);
53
+ expect(keepsNestedNodeModules()).toBe(true);
60
54
  });
61
55
  });
@@ -9,7 +9,11 @@
9
9
 
10
10
  const path = require('path');
11
11
  const fs = require('fs');
12
- const { buildPrismaLayer } = require('../../../scripts/build-prisma-layer');
12
+ const {
13
+ buildPrismaLayer,
14
+ layerBuildInputs,
15
+ } = require('../../../scripts/build-prisma-layer');
16
+ const { resolveLambdaArchitecture } = require('../lambda-architectures');
13
17
 
14
18
  /**
15
19
  * Check if a process is still running
@@ -26,6 +30,48 @@ function isProcessRunning(pid) {
26
30
  }
27
31
  }
28
32
 
33
+ const LEGACY_MARKER_TARGET = 'rhel-openssl-3.0.x';
34
+
35
+ /**
36
+ * The inputs a completion marker records. A marker written before the
37
+ * marker became JSON recorded nothing, and every layer then held the rhel
38
+ * engine; its versions are unknown, so it never matches and the layer is
39
+ * rebuilt once.
40
+ * @param {string} markerText
41
+ * @returns {{ prismaBinaryTarget: string, clientPackages: string[]|null, coreVersion: string|null, prismaClientVersion: string|null }}
42
+ */
43
+ function parseLayerMarker(markerText) {
44
+ try {
45
+ const marker = JSON.parse(markerText);
46
+ return {
47
+ prismaBinaryTarget: marker.prismaBinaryTarget,
48
+ clientPackages: marker.clientPackages,
49
+ coreVersion: marker.coreVersion,
50
+ prismaClientVersion: marker.prismaClientVersion,
51
+ };
52
+ } catch {
53
+ // A marker written before the JSON format is plain text: treat it as a legacy build
54
+ return {
55
+ prismaBinaryTarget: LEGACY_MARKER_TARGET,
56
+ clientPackages: null,
57
+ coreVersion: null,
58
+ prismaClientVersion: null,
59
+ };
60
+ }
61
+ }
62
+
63
+ function sameLayerInputs(a, b) {
64
+ return (
65
+ a.prismaBinaryTarget === b.prismaBinaryTarget &&
66
+ a.coreVersion === b.coreVersion &&
67
+ a.prismaClientVersion === b.prismaClientVersion &&
68
+ Array.isArray(a.clientPackages) &&
69
+ Array.isArray(b.clientPackages) &&
70
+ a.clientPackages.length === b.clientPackages.length &&
71
+ a.clientPackages.every((pkg, i) => pkg === b.clientPackages[i])
72
+ );
73
+ }
74
+
29
75
  /**
30
76
  * Ensure Prisma Lambda Layer exists
31
77
  *
@@ -34,23 +80,38 @@ function isProcessRunning(pid) {
34
80
  * Prisma CLI is bundled separately in the dbMigrate function.
35
81
  *
36
82
  * Domain Concept: Build Completion State & Process Locking
37
- * - Uses .build-complete marker file to track successful builds
83
+ * - Uses .build-complete marker file to track successful builds; it records
84
+ * the inputs the layer was built from, and a built layer is reused only
85
+ * when they match the requested ones
38
86
  * - Uses .build-lock PID file to prevent concurrent builds
39
87
  * - Waits for active builds to complete before starting new one
40
88
  * - Cleans stale locks and incomplete builds before retry
41
89
  *
42
- * @param {Object} databaseConfig - Database configuration from app definition
90
+ * @param {Object} options
91
+ * @param {Object} options.databaseConfig - Database configuration from app definition
92
+ * @param {string} options.prismaBinaryTarget - The engine the deployed architecture loads
43
93
  * @returns {Promise<void>}
44
94
  * @throws {Error} If layer build fails
45
95
  */
46
- async function ensurePrismaLayerExists(databaseConfig = {}) {
96
+ async function ensurePrismaLayerExists({
97
+ databaseConfig = {},
98
+ prismaBinaryTarget = resolveLambdaArchitecture().prismaBinaryTarget,
99
+ } = {}) {
47
100
  const projectRoot = process.cwd();
48
101
  const layerPath = path.join(projectRoot, 'layers/prisma');
49
102
  const completionMarkerPath = path.join(layerPath, '.build-complete');
50
103
  const lockFilePath = path.join(layerPath, '.build-lock');
104
+ const inputs = layerBuildInputs({ databaseConfig, prismaBinaryTarget });
105
+
106
+ const builtLayerMatches = () =>
107
+ fs.existsSync(completionMarkerPath) &&
108
+ sameLayerInputs(
109
+ parseLayerMarker(fs.readFileSync(completionMarkerPath, 'utf-8')),
110
+ inputs
111
+ );
51
112
 
52
113
  // Check if build is complete (marker exists)
53
- if (fs.existsSync(completionMarkerPath)) {
114
+ if (builtLayerMatches()) {
54
115
  console.log('✓ Prisma Lambda Layer already exists at', layerPath);
55
116
  return;
56
117
  }
@@ -68,8 +129,13 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
68
129
 
69
130
  // Check if build completed
70
131
  if (fs.existsSync(completionMarkerPath)) {
71
- console.log('✓ Concurrent build completed successfully');
72
- return;
132
+ if (builtLayerMatches()) {
133
+ console.log('✓ Concurrent build completed successfully');
134
+ return;
135
+ }
136
+ console.log('⚠ Concurrent build completed for other inputs - rebuilding');
137
+ fs.rmSync(lockFilePath, { force: true });
138
+ break;
73
139
  }
74
140
 
75
141
  // Check if process died
@@ -81,14 +147,16 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
81
147
  }
82
148
 
83
149
  // Timeout - check one final time
84
- if (fs.existsSync(completionMarkerPath)) {
150
+ if (builtLayerMatches()) {
85
151
  console.log('✓ Concurrent build completed');
86
152
  return;
87
153
  }
88
154
 
89
155
  // Still locked after 60s - remove stale lock
90
- console.log('⚠ Build timeout - removing stale lock and rebuilding');
91
- fs.rmSync(lockFilePath, { force: true });
156
+ if (fs.existsSync(lockFilePath)) {
157
+ console.log('⚠ Build timeout - removing stale lock and rebuilding');
158
+ fs.rmSync(lockFilePath, { force: true });
159
+ }
92
160
  } else {
93
161
  // Stale lock file (process not running)
94
162
  console.log(`⚠ Stale lock file detected (PID ${lockPid} not running) - cleaning up`);
@@ -99,6 +167,8 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
99
167
  // Check if incomplete build exists (directory without marker)
100
168
  if (fs.existsSync(layerPath) && !fs.existsSync(completionMarkerPath)) {
101
169
  console.log('⚠ Incomplete Prisma layer detected - will be cleaned by buildPrismaLayer()');
170
+ } else if (fs.existsSync(completionMarkerPath)) {
171
+ console.log(`⚠ Built Prisma layer does not match ${JSON.stringify(inputs)} - rebuilding`);
102
172
  }
103
173
 
104
174
  // Build layer
@@ -119,12 +189,21 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
119
189
 
120
190
  try {
121
191
  // Build layer WITHOUT CLI (runtime only for minimal size)
122
- await buildPrismaLayer(databaseConfig);
192
+ await buildPrismaLayer({ databaseConfig, prismaBinaryTarget });
123
193
 
124
194
  // Create completion marker
125
195
  fs.writeFileSync(
126
196
  completionMarkerPath,
127
- `Build completed: ${new Date().toISOString()}\nNode: ${process.version}\nPlatform: ${process.platform}\n`
197
+ JSON.stringify(
198
+ {
199
+ ...inputs,
200
+ builtAt: new Date().toISOString(),
201
+ node: process.version,
202
+ platform: process.platform,
203
+ },
204
+ null,
205
+ 2
206
+ )
128
207
  );
129
208
 
130
209
  console.log('✓ Prisma Lambda Layer built successfully (~10-15MB)\n');
@@ -155,5 +234,6 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
155
234
 
156
235
  module.exports = {
157
236
  ensurePrismaLayerExists,
237
+ parseLayerMarker,
158
238
  };
159
239
 
@@ -12,9 +12,19 @@ const { ensurePrismaLayerExists } = require('./prisma-layer-manager');
12
12
  jest.mock('fs');
13
13
  jest.mock('../../../scripts/build-prisma-layer', () => ({
14
14
  buildPrismaLayer: jest.fn(),
15
+ layerBuildInputs: jest.fn(),
15
16
  }));
16
17
 
17
- const { buildPrismaLayer } = require('../../../scripts/build-prisma-layer');
18
+ const { buildPrismaLayer, layerBuildInputs } = require('../../../scripts/build-prisma-layer');
19
+
20
+ const inputsFor = ({ prismaBinaryTarget = 'rhel-openssl-3.0.x' } = {}) => ({
21
+ prismaBinaryTarget,
22
+ clientPackages: ['generated/prisma-postgresql'],
23
+ coreVersion: '2.0.0-next.120',
24
+ prismaClientVersion: '6.19.3',
25
+ });
26
+ const markerFor = (overrides = {}) =>
27
+ JSON.stringify({ ...inputsFor(), ...overrides });
18
28
 
19
29
  // Helper to mock fs methods for different scenarios
20
30
  const mockFs = {
@@ -50,6 +60,8 @@ describe('Prisma Layer Manager', () => {
50
60
  originalCwd = process.cwd;
51
61
  process.cwd = jest.fn().mockReturnValue('/project');
52
62
  jest.clearAllMocks();
63
+ layerBuildInputs.mockImplementation(inputsFor);
64
+ fs.readFileSync = jest.fn((p) => (p.endsWith('.build-lock') ? '99999' : markerFor()));
53
65
  });
54
66
 
55
67
  afterEach(() => {
@@ -87,9 +99,27 @@ describe('Prisma Layer Manager', () => {
87
99
  postgres: { enable: true },
88
100
  };
89
101
 
90
- await ensurePrismaLayerExists(databaseConfig);
102
+ await ensurePrismaLayerExists({ databaseConfig });
103
+
104
+ expect(buildPrismaLayer).toHaveBeenCalledWith({
105
+ databaseConfig,
106
+ prismaBinaryTarget: 'rhel-openssl-3.0.x',
107
+ });
108
+ });
109
+
110
+ it('should pass the Prisma binary target of the deployed architecture to buildPrismaLayer', async () => {
111
+ fs.existsSync = jest.fn().mockReturnValue(false);
112
+ buildPrismaLayer.mockResolvedValue();
113
+
114
+ await ensurePrismaLayerExists({
115
+ databaseConfig: {},
116
+ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x',
117
+ });
91
118
 
92
- expect(buildPrismaLayer).toHaveBeenCalledWith(databaseConfig);
119
+ expect(buildPrismaLayer).toHaveBeenCalledWith({
120
+ databaseConfig: {},
121
+ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x',
122
+ });
93
123
  });
94
124
 
95
125
  it('should handle build errors and rethrow', async () => {
@@ -105,7 +135,10 @@ describe('Prisma Layer Manager', () => {
105
135
 
106
136
  await ensurePrismaLayerExists();
107
137
 
108
- expect(buildPrismaLayer).toHaveBeenCalledWith({});
138
+ expect(buildPrismaLayer).toHaveBeenCalledWith({
139
+ databaseConfig: {},
140
+ prismaBinaryTarget: 'rhel-openssl-3.0.x',
141
+ });
109
142
  });
110
143
 
111
144
  it('should use correct layer path relative to project root', async () => {
@@ -123,6 +156,7 @@ describe('Prisma Layer Manager', () => {
123
156
 
124
157
  it('should log success when layer already exists', async () => {
125
158
  fs.existsSync = jest.fn().mockReturnValue(true);
159
+ fs.readFileSync = jest.fn().mockReturnValue(markerFor());
126
160
  const consoleSpy = jest.spyOn(console, 'log').mockImplementation();
127
161
 
128
162
  await ensurePrismaLayerExists();
@@ -169,6 +203,120 @@ describe('Prisma Layer Manager', () => {
169
203
  consoleErrorSpy.mockRestore();
170
204
  });
171
205
 
206
+ describe('layer cache keyed by its inputs', () => {
207
+ const existingMarker = () => {
208
+ fs.existsSync = jest.fn((p) => p.endsWith('.build-complete') || p.endsWith('layers/prisma'));
209
+ fs.writeFileSync = jest.fn();
210
+ fs.rmSync = jest.fn();
211
+ buildPrismaLayer.mockResolvedValue();
212
+ };
213
+
214
+ it('reuses the layer when the marker records the same target, clients and versions', async () => {
215
+ existingMarker();
216
+ fs.readFileSync = jest.fn().mockReturnValue(markerFor());
217
+
218
+ await ensurePrismaLayerExists({ prismaBinaryTarget: 'rhel-openssl-3.0.x' });
219
+
220
+ expect(buildPrismaLayer).not.toHaveBeenCalled();
221
+ });
222
+
223
+ it('rebuilds when the deployed architecture changes the target', async () => {
224
+ existingMarker();
225
+ fs.readFileSync = jest.fn().mockReturnValue(markerFor());
226
+
227
+ await ensurePrismaLayerExists({ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x' });
228
+
229
+ expect(buildPrismaLayer).toHaveBeenCalledWith({
230
+ databaseConfig: {},
231
+ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x',
232
+ });
233
+ });
234
+
235
+ it('rebuilds when the installed core version changes', async () => {
236
+ existingMarker();
237
+ fs.readFileSync = jest.fn().mockReturnValue(markerFor({ coreVersion: '2.0.0-next.105' }));
238
+
239
+ await ensurePrismaLayerExists();
240
+
241
+ expect(buildPrismaLayer).toHaveBeenCalledTimes(1);
242
+ });
243
+
244
+ it('rebuilds when the client set changes', async () => {
245
+ existingMarker();
246
+ fs.readFileSync = jest.fn().mockReturnValue(
247
+ markerFor({ clientPackages: ['generated/prisma-postgresql', 'generated/prisma-mongodb'] })
248
+ );
249
+
250
+ await ensurePrismaLayerExists();
251
+
252
+ expect(buildPrismaLayer).toHaveBeenCalledTimes(1);
253
+ });
254
+
255
+ it('rebuilds over a legacy plain-text marker, which records no target or versions', async () => {
256
+ existingMarker();
257
+ fs.readFileSync = jest.fn().mockReturnValue(
258
+ 'Build completed: 2026-01-01T00:00:00.000Z\nNode: v22.0.0\nPlatform: darwin\n'
259
+ );
260
+
261
+ await ensurePrismaLayerExists();
262
+
263
+ expect(buildPrismaLayer).toHaveBeenCalledTimes(1);
264
+ });
265
+
266
+ it('writes the inputs into the marker after a build', async () => {
267
+ mockFs.noBuild();
268
+ buildPrismaLayer.mockResolvedValue();
269
+
270
+ await ensurePrismaLayerExists({ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x' });
271
+
272
+ const [, written] = fs.writeFileSync.mock.calls.find(
273
+ ([p]) => p === '/project/layers/prisma/.build-complete'
274
+ );
275
+ expect(JSON.parse(written)).toEqual(
276
+ expect.objectContaining(inputsFor({ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x' }))
277
+ );
278
+ });
279
+
280
+ it('rebuilds after waiting on a concurrent build that finished for the other target', async () => {
281
+ jest.useFakeTimers();
282
+ let completionMarkerExists = false;
283
+ fs.existsSync = jest.fn((p) => {
284
+ if (p.endsWith('.build-complete')) return completionMarkerExists;
285
+ if (p.endsWith('.build-lock')) return !completionMarkerExists;
286
+ if (p.endsWith('layers/prisma')) return true;
287
+ return false;
288
+ });
289
+ fs.readFileSync = jest.fn((p) =>
290
+ p.endsWith('.build-lock') ? '12345' : markerFor({ prismaBinaryTarget: 'rhel-openssl-3.0.x' })
291
+ );
292
+ fs.writeFileSync = jest.fn();
293
+ fs.mkdirSync = jest.fn();
294
+ fs.rmSync = jest.fn();
295
+ buildPrismaLayer.mockResolvedValue();
296
+ const originalKill = process.kill;
297
+ let polls = 0;
298
+ process.kill = jest.fn(() => {
299
+ if (++polls >= 3) completionMarkerExists = true;
300
+ return true;
301
+ });
302
+
303
+ const promise = ensurePrismaLayerExists({ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x' });
304
+ for (let i = 0; i < 5; i++) {
305
+ jest.advanceTimersByTime(1000);
306
+ await Promise.resolve();
307
+ }
308
+ await promise;
309
+
310
+ expect(buildPrismaLayer).toHaveBeenCalledWith({
311
+ databaseConfig: {},
312
+ prismaBinaryTarget: 'linux-arm64-openssl-3.0.x',
313
+ });
314
+
315
+ process.kill = originalKill;
316
+ jest.useRealTimers();
317
+ });
318
+ });
319
+
172
320
  describe('Concurrent Build Protection', () => {
173
321
  it('should skip build if completion marker exists (TDD)', async () => {
174
322
  mockFs.completedBuild();
@@ -191,7 +339,9 @@ describe('Prisma Layer Manager', () => {
191
339
  if (path.endsWith('layers/prisma')) return true;
192
340
  return false;
193
341
  });
194
- fs.readFileSync = jest.fn().mockReturnValue(activePid.toString());
342
+ fs.readFileSync = jest.fn((p) =>
343
+ p.endsWith('.build-lock') ? activePid.toString() : markerFor()
344
+ );
195
345
  fs.writeFileSync = jest.fn();
196
346
  fs.rmSync = jest.fn();
197
347
 
@@ -405,7 +555,9 @@ describe('Prisma Layer Manager', () => {
405
555
  if (path.endsWith('layers/prisma')) return true;
406
556
  return false;
407
557
  });
408
- fs.readFileSync = jest.fn().mockReturnValue('12345');
558
+ fs.readFileSync = jest.fn((p) =>
559
+ p.endsWith('.build-lock') ? '12345' : markerFor()
560
+ );
409
561
  fs.writeFileSync = jest.fn();
410
562
  fs.rmSync = jest.fn();
411
563
 
@@ -61,6 +61,8 @@ function applySsmPreloadNodeOptions(appDefinition, functions, providerEnvironmen
61
61
  const { modifyHandlerPaths } = require('./domains/shared/utilities/handler-path-resolver');
62
62
  const { createBaseDefinition } = require('./domains/shared/utilities/base-definition-factory');
63
63
  const { ensurePrismaLayerExists } = require('./domains/shared/utilities/prisma-layer-manager');
64
+ const { resolveLambdaArchitecture } = require('./domains/shared/lambda-architectures');
65
+ const { ensureMigrationEngines } = require('./domains/database/migration-engines');
64
66
  const { validateAndCleanPlugins, validatePackagingConfiguration } = require('./domains/shared/validation/plugin-validator');
65
67
 
66
68
  /**
@@ -74,14 +76,23 @@ const composeServerlessDefinition = async (AppDefinition) => {
74
76
 
75
77
  // Determine if deployment should use Prisma Lambda Layer (default: true)
76
78
  const usePrismaLayer = AppDefinition.usePrismaLambdaLayer !== false;
79
+ const { prismaBinaryTarget } = resolveLambdaArchitecture(AppDefinition);
77
80
 
78
81
  // Ensure Prisma layer exists only when configured to use it
79
82
  if (usePrismaLayer) {
80
- await ensurePrismaLayerExists(AppDefinition.database || {});
83
+ await ensurePrismaLayerExists({
84
+ databaseConfig: AppDefinition.database || {},
85
+ prismaBinaryTarget,
86
+ });
81
87
  } else {
82
88
  console.log('📦 Skipping Prisma Lambda Layer (usePrismaLambdaLayer=false - bundling Prisma with functions)');
83
89
  }
84
90
 
91
+ // The migration worker ships its own Prisma CLI engines (layer or not)
92
+ if (new MigrationBuilder().shouldExecute(AppDefinition)) {
93
+ await ensureMigrationEngines({ prismaBinaryTarget });
94
+ }
95
+
85
96
  // Create orchestrator with all domain builders
86
97
  const orchestrator = new BuilderOrchestrator([
87
98
  new VpcBuilder(),