@friggframework/devtools 2.0.0--canary.703.12b980b.0 → 2.0.0--canary.707.df80bfd.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 (43) hide show
  1. package/frigg-cli/__tests__/unit/commands/provider-dispatch.test.js +140 -0
  2. package/frigg-cli/build-command/index.js +32 -1
  3. package/frigg-cli/db-setup-command/index.js +25 -0
  4. package/frigg-cli/deploy-command/index.js +50 -5
  5. package/frigg-cli/doctor-command/index.js +7 -0
  6. package/frigg-cli/generate-iam-command.js +7 -0
  7. package/frigg-cli/index.js +0 -2
  8. package/frigg-cli/repair-command/index.js +7 -0
  9. package/frigg-cli/start-command/index.js +58 -0
  10. package/frigg-cli/utils/provider-helper.js +80 -0
  11. package/infrastructure/README.md +4 -2
  12. package/infrastructure/__tests__/compose-extension-prisma.test.js +168 -0
  13. package/infrastructure/__tests__/create-frigg-infrastructure-provider.test.js +64 -0
  14. package/infrastructure/__tests__/management-api-gateway-routes.test.js +335 -0
  15. package/infrastructure/__tests__/template-generation.test.js +7 -0
  16. package/infrastructure/compose-extension-prisma.js +73 -0
  17. package/infrastructure/create-frigg-infrastructure.js +14 -0
  18. package/infrastructure/domains/admin-scripts/admin-script-builder.js +2 -6
  19. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +0 -30
  20. package/infrastructure/domains/integration/integration-builder.js +0 -19
  21. package/infrastructure/domains/integration/integration-builder.test.js +0 -22
  22. package/infrastructure/domains/parameters/offload-utils.js +1 -0
  23. package/infrastructure/domains/shared/environment-builder.js +12 -1
  24. package/infrastructure/domains/shared/environment-builder.test.js +20 -0
  25. package/infrastructure/domains/shared/function-environments.js +1 -9
  26. package/infrastructure/domains/shared/function-environments.test.js +0 -14
  27. package/infrastructure/domains/shared/types/app-definition.js +15 -1
  28. package/infrastructure/domains/shared/utilities/base-definition-factory.js +28 -10
  29. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +85 -1
  30. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +10 -0
  31. package/infrastructure/infrastructure-composer.js +13 -3
  32. package/infrastructure/infrastructure-composer.test.js +7 -0
  33. package/infrastructure/provider-build.js +126 -0
  34. package/infrastructure/scripts/build-prisma-layer.js +32 -5
  35. package/infrastructure/scripts/build-prisma-layer.test.js +35 -0
  36. package/package.json +7 -7
  37. package/test/npm-install-guard.js +104 -0
  38. package/test/npm-install-guard.test.js +53 -0
  39. package/frigg-cli/__tests__/unit/commands/deploy-subscriptions-step.test.js +0 -35
  40. package/frigg-cli/deploy-command/subscriptions-step.js +0 -44
  41. package/infrastructure/domains/integration/define-integration-provisioning.test.js +0 -59
  42. package/infrastructure/domains/scheduler/trigger-builder.js +0 -114
  43. package/infrastructure/domains/scheduler/trigger-builder.test.js +0 -82
@@ -141,12 +141,10 @@ class AdminScriptBuilder extends InfrastructureBuilder {
141
141
  }
142
142
 
143
143
  createAdminScriptQueue(result, appDefinition) {
144
- // Registered under custom so the serverless plugin creates it in LocalStack offline
145
- result.custom.AdminScriptQueue = '${self:service}-${self:provider.stage}-AdminScriptQueue';
146
144
  result.resources.AdminScriptQueue = {
147
145
  Type: 'AWS::SQS::Queue',
148
146
  Properties: {
149
- QueueName: '${self:custom.AdminScriptQueue}',
147
+ QueueName: '${self:service}-${self:provider.stage}-AdminScriptQueue',
150
148
  MessageRetentionPeriod: 86400, // 1 day
151
149
  VisibilityTimeout: 900, // 15 minutes (Lambda max)
152
150
  RedrivePolicy: {
@@ -266,12 +264,10 @@ class AdminScriptBuilder extends InfrastructureBuilder {
266
264
  }
267
265
 
268
266
  createReportQueue(result, appDefinition) {
269
- // Registered under custom so the serverless plugin creates it in LocalStack offline
270
- result.custom.ReportQueue = '${self:service}-${self:provider.stage}-ReportQueue';
271
267
  result.resources.ReportQueue = {
272
268
  Type: 'AWS::SQS::Queue',
273
269
  Properties: {
274
- QueueName: '${self:custom.ReportQueue}',
270
+ QueueName: '${self:service}-${self:provider.stage}-ReportQueue',
275
271
  MessageRetentionPeriod: 86400, // 1 day
276
272
  VisibilityTimeout: 900, // 15 minutes (Lambda max)
277
273
  RedrivePolicy: {
@@ -168,21 +168,6 @@ describe('AdminScriptBuilder', () => {
168
168
  expect(result.resources.AdminScriptQueue.Properties.VisibilityTimeout).toBe(900); // 15 minutes
169
169
  });
170
170
 
171
- it('registers AdminScriptQueue under custom so frigg start creates it locally', async () => {
172
- const appDefinition = {
173
- adminScripts: [{ Definition: { name: 'test-script' } }],
174
- };
175
-
176
- const result = await adminScriptBuilder.build(appDefinition, {});
177
-
178
- expect(result.custom.AdminScriptQueue).toBe(
179
- '${self:service}-${self:provider.stage}-AdminScriptQueue'
180
- );
181
- expect(result.resources.AdminScriptQueue.Properties.QueueName).toBe(
182
- '${self:custom.AdminScriptQueue}'
183
- );
184
- });
185
-
186
171
  it('should configure AdminScriptQueue redrive policy to InternalErrorQueue', async () => {
187
172
  const appDefinition = {
188
173
  adminScripts: [
@@ -636,21 +621,6 @@ describe('AdminScriptBuilder', () => {
636
621
  });
637
622
 
638
623
  describe('reports (ReportQueue + reportExecutor)', () => {
639
- it('registers ReportQueue under custom so frigg start creates it locally', async () => {
640
- const appDefinition = {
641
- reports: [{ Definition: { name: 'my-report', version: '1.0.0' } }],
642
- };
643
-
644
- const result = await adminScriptBuilder.build(appDefinition, {});
645
-
646
- expect(result.custom.ReportQueue).toBe(
647
- '${self:service}-${self:provider.stage}-ReportQueue'
648
- );
649
- expect(result.resources.ReportQueue.Properties.QueueName).toBe(
650
- '${self:custom.ReportQueue}'
651
- );
652
- });
653
-
654
624
  it('creates ReportQueue + reportExecutor and wires REPORT_QUEUE_URL when reports are present', async () => {
655
625
  const appDefinition = {
656
626
  reports: [{ Definition: { name: 'my-report', version: '1.0.0' } }],
@@ -360,25 +360,6 @@ class IntegrationBuilder extends InfrastructureBuilder {
360
360
  method: 'POST',
361
361
  },
362
362
  },
363
- // A provider (the shared runtime for published integration definitions) also receives the
364
- // webhooks of every type it provides at that type's own URL. HTTP API cannot match part of a
365
- // segment, so the whole segment is a parameter; literal routes still win over it.
366
- ...(integration.IntegrationProvider
367
- ? [
368
- {
369
- httpApi: {
370
- path: '/api/{integrationType}/webhooks',
371
- method: 'POST',
372
- },
373
- },
374
- {
375
- httpApi: {
376
- path: '/api/{integrationType}/webhooks/{integrationId}',
377
- method: 'POST',
378
- },
379
- },
380
- ]
381
- : []),
382
363
  ],
383
364
  };
384
365
  console.log(` ✓ Webhook handler function defined`);
@@ -620,28 +620,6 @@ describe('IntegrationBuilder', () => {
620
620
  ]);
621
621
  });
622
622
 
623
- it('gives a provider of integration types the webhook routes of every type it provides', async () => {
624
- const appDefinition = {
625
- integrations: [
626
- { Definition: { name: 'stripe', webhooks: true } },
627
- {
628
- Definition: { name: 'integration-runtime', webhooks: { enabled: true } },
629
- IntegrationProvider: { resolve: async () => null, list: async () => [] },
630
- },
631
- ],
632
- };
633
-
634
- const result = await integrationBuilder.build(appDefinition, {});
635
-
636
- expect(result.functions['integration-runtimeWebhook'].events.map((e) => e.httpApi.path)).toEqual([
637
- '/api/integration-runtime-integration/webhooks',
638
- '/api/integration-runtime-integration/webhooks/{integrationId}',
639
- '/api/{integrationType}/webhooks',
640
- '/api/{integrationType}/webhooks/{integrationId}',
641
- ]);
642
- expect(result.functions.stripeWebhook.events).toHaveLength(2);
643
- });
644
-
645
623
  it('emits a dedicated per-binding function (namespaced) for Tier 3 extension routes; the main handler keeps only {proxy+}', async () => {
646
624
  const appDefinition = {
647
625
  integrations: [
@@ -40,6 +40,7 @@ const FRAMEWORK_ENV_BLOCKLIST = new Set([
40
40
  'KMS_KEY_ARN',
41
41
  'AES_KEY',
42
42
  'AES_KEY_ID',
43
+ 'FRIGG_ENCRYPTION_DISABLED',
43
44
  'DATABASE_URL',
44
45
  'DATABASE_HOST',
45
46
  'DATABASE_PORT',
@@ -72,6 +72,16 @@ function addLoggingEnv(appDefinition, envVars) {
72
72
  envVars.FRIGG_LOG_LEVEL = normalized;
73
73
  }
74
74
 
75
+ // Field-level encryption fails closed in a deployed stage with no key (core's
76
+ // encryption-config.js). `fieldLevelEncryptionMethod: 'none'` is the explicit,
77
+ // documented way to run a stage in plaintext; core logs a warning on every
78
+ // cold start while it is set.
79
+ function addEncryptionEnv(appDefinition, envVars) {
80
+ if (appDefinition?.encryption?.fieldLevelEncryptionMethod === 'none') {
81
+ envVars.FRIGG_ENCRYPTION_DISABLED = 'true';
82
+ }
83
+ }
84
+
75
85
  /**
76
86
  * Get environment variables from AppDefinition
77
87
  *
@@ -149,6 +159,7 @@ function getAppEnvironmentVars(appDefinition) {
149
159
  }
150
160
 
151
161
  addLoggingEnv(appDefinition, envVars);
162
+ addEncryptionEnv(appDefinition, envVars);
152
163
 
153
164
  if (envKeys.length > 0) {
154
165
  console.log(
@@ -187,7 +198,7 @@ function getAppEnvironmentVars(appDefinition) {
187
198
  function buildEnvironment(appEnvironmentVars, discoveredResources) {
188
199
  const environment = {
189
200
  ...appEnvironmentVars,
190
- STAGE: '${self:provider.stage}', // Used by encryption bypass logic
201
+ STAGE: '${self:provider.stage}', // Read by core: e.g. the local-only encryption bypass
191
202
  FRIGG_STACK: '${self:service}',
192
203
  FRIGG_STAGE: '${self:provider.stage}',
193
204
  FRIGG_REGION: '${self:provider.region}',
@@ -468,6 +468,26 @@ describe('Environment Builder', () => {
468
468
  });
469
469
  });
470
470
 
471
+ describe('field-level encryption opt-out', () => {
472
+ it("emits FRIGG_ENCRYPTION_DISABLED=true for fieldLevelEncryptionMethod: 'none'", () => {
473
+ const result = getAppEnvironmentVars({
474
+ encryption: { fieldLevelEncryptionMethod: 'none' },
475
+ });
476
+
477
+ expect(result.FRIGG_ENCRYPTION_DISABLED).toBe('true');
478
+ });
479
+
480
+ it.each([
481
+ ['kms', { fieldLevelEncryptionMethod: 'kms' }],
482
+ ['aes', { fieldLevelEncryptionMethod: 'aes' }],
483
+ ['no encryption block', undefined],
484
+ ])('does not opt out for %s', (_label, encryption) => {
485
+ const result = getAppEnvironmentVars({ encryption });
486
+
487
+ expect(result.FRIGG_ENCRYPTION_DISABLED).toBeUndefined();
488
+ });
489
+ });
490
+
471
491
  describe('buildEnvironment()', () => {
472
492
  it('should combine app vars with standard Frigg variables', () => {
473
493
  const appEnvironmentVars = {
@@ -1,5 +1,3 @@
1
- const { hasTriggers } = require('@friggframework/core/integrations/triggers');
2
-
3
1
  /**
4
2
  * Per-function environment scoping (ADR-027)
5
3
  *
@@ -49,8 +47,7 @@ function applyFunctionEnvironments(functions, functionEnvironments = {}) {
49
47
  /**
50
48
  * Function names the integration builder creates for one integration.
51
49
  * Wire contract: must stay in sync with
52
- * IntegrationBuilder.createFunctionDefinitions (and TriggerBuilder for
53
- * `${name}Triggers`) — a drift here surfaces as a
50
+ * IntegrationBuilder.createFunctionDefinitions — a drift here surfaces as a
54
51
  * hard unknown-function error at compose time, not a silent var drop.
55
52
  *
56
53
  * @param {Object} integration - entry from appDefinition.integrations
@@ -65,11 +62,6 @@ function getIntegrationFunctionNames(integration) {
65
62
  names.splice(1, 0, `${name}Webhook`);
66
63
  }
67
64
 
68
- // TriggerBuilder (ADR-055): the tick function, which sends trigger runs to this integration's queue.
69
- if (hasTriggers(integration)) {
70
- names.push(`${name}Triggers`);
71
- }
72
-
73
65
  for (const [bindingKey, binding] of Object.entries(
74
66
  integration.Definition.extensions || {}
75
67
  )) {
@@ -67,20 +67,6 @@ describe('function-environments', () => {
67
67
  ).not.toContain('hubspotWebhook');
68
68
  });
69
69
 
70
- it('includes the trigger tick function when the integration declares triggers (ADR-055)', () => {
71
- expect(
72
- getIntegrationFunctionNames({
73
- Definition: { name: 'hubspot', triggers: { poll: { every: '15m', handler: 'poll' } } },
74
- })
75
- ).toEqual(['hubspot', 'hubspotQueueWorker', 'hubspotTriggers']);
76
- expect(
77
- getIntegrationFunctionNames({ Definition: { name: 'dd', instanceTriggers: { tick: '5m' } } })
78
- ).toContain('ddTriggers');
79
- expect(
80
- getIntegrationFunctionNames({ Definition: { name: 'hubspot', triggers: {} } })
81
- ).not.toContain('hubspotTriggers');
82
- });
83
-
84
70
  it('includes one function per routed extension binding, sanitized', () => {
85
71
  const names = getIntegrationFunctionNames({
86
72
  Definition: {
@@ -129,7 +129,7 @@
129
129
  * @typedef {Object} AppDefinition
130
130
  * @property {string} name - Application name
131
131
  * @property {string} stage - Deployment stage (e.g., 'dev', 'production')
132
- * @property {string} provider - Cloud provider (e.g., 'aws')
132
+ * @property {string} provider - Deployment provider: 'aws' (serverless/Lambda) or 'netlify' (@friggframework/provider-netlify)
133
133
  * @property {string} region - AWS region
134
134
  *
135
135
  * @property {VpcDefinition} [vpc] - VPC configuration
@@ -144,6 +144,20 @@
144
144
  * @property {AdminConfig} [admin] - Admin configuration
145
145
  *
146
146
  * @property {Object} [environment] - Environment variables
147
+ *
148
+ * @property {ExtensionDefinition[]} [coreExtensions] - Core (app-level) extensions that add custom Prisma models, encrypted fields, admin routes and bootstrap hooks (not an integration's Definition.extensions, nor ADR-017's keyed appDefinition.extensions)
149
+ */
150
+
151
+ /**
152
+ * App-level extension: custom models, encryption, admin routes and bootstrap
153
+ * @typedef {Object} ExtensionDefinition
154
+ * @property {string} name - Unique identifier for this extension
155
+ * @property {string} [schema] - Absolute path to a .prisma schema fragment
156
+ * @property {Object<string, {fields: string[]}>} [encryption] - Model name → encrypted fields mapping
157
+ * @property {Object} [routes] - Express router configuration
158
+ * @property {string} routes.path - Base URL path for the extension routes: /admin/<segment>..., never /api (/admin/scripts, /admin/db-migrate and /admin/queue are reserved); served by the auth function
159
+ * @property {Function|Object} routes.handler - Router factory (prisma, appDefinition) → Router, or { router } object
160
+ * @property {Function} [bootstrap] - Async function (prisma, appDefinition) → void, run by initializeApp()
147
161
  */
148
162
 
149
163
  /**
@@ -10,6 +10,26 @@
10
10
  const { buildEnvironment } = require('../environment-builder');
11
11
  const { nestedNodeModulesExcludes } = require('./nested-node-modules');
12
12
  const { buildLoggingProviderConfig } = require('./logging-config');
13
+ const {
14
+ getGatewayRoutes,
15
+ } = require('@friggframework/core/management-api/route-registry');
16
+
17
+ /**
18
+ * HTTP API events for one function, from core's route registry (ADR-053):
19
+ * the same registry mounts the Express routers and builds the OpenAPI
20
+ * documents, so the three cannot drift. It also lists /api/docs and the core
21
+ * extensions' admin routes (/admin/<name>, served by the auth Lambda).
22
+ */
23
+ function managementApiEvents(AppDefinition, functionName) {
24
+ const managementApi = AppDefinition.managementApi || {};
25
+ return getGatewayRoutes({
26
+ v1: managementApi.v1 !== false,
27
+ proxy: managementApi.proxy?.enable === true,
28
+ coreExtensions: AppDefinition.coreExtensions,
29
+ })
30
+ .filter((route) => route.function === functionName)
31
+ .map(({ method, path }) => ({ httpApi: { path, method } }));
32
+ }
13
33
 
14
34
  /**
15
35
  * Create base serverless definition with core functions and resources
@@ -286,16 +306,12 @@ function createBaseDefinition(
286
306
  ...(usePrismaLayer && { layers: [{ Ref: 'PrismaLambdaLayer' }] }),
287
307
  skipEsbuild: true, // Handlers in node_modules don't need bundling
288
308
  package: skipEsbuildPackageConfig,
289
- events: [
290
- { httpApi: { path: '/api/integrations', method: 'ANY' } },
291
- {
292
- httpApi: {
293
- path: '/api/integrations/{proxy+}',
294
- method: 'ANY',
295
- },
296
- },
297
- { httpApi: { path: '/api/authorize', method: 'ANY' } },
298
- ],
309
+ // Every Management API path the auth Lambda serves (v1, v2 per
310
+ // resource, the OAuth redirect) comes from core's route
311
+ // registry. HTTP API has no implicit catch-all, so an unlisted
312
+ // prefix 404s at the gateway before Express sees it. Guarded by
313
+ // __tests__/management-api-gateway-routes.test.js.
314
+ events: managementApiEvents(AppDefinition, 'auth'),
299
315
  },
300
316
  user: {
301
317
  handler: 'node_modules/@friggframework/core/handlers/routers/user.handler',
@@ -312,6 +328,8 @@ function createBaseDefinition(
312
328
  events: [
313
329
  { httpApi: { path: '/health', method: 'GET' } },
314
330
  { httpApi: { path: '/health/{proxy+}', method: 'GET' } },
331
+ // GET /api/meta and the OpenAPI documents: public, DB-free.
332
+ ...managementApiEvents(AppDefinition, 'health'),
315
333
  ],
316
334
  },
317
335
  // Reporting is an admin operation (ADR-010): the report router runs on the admin-scripts Lambda, not as a standalone function here.
@@ -94,7 +94,91 @@ describe('Base Definition Factory', () => {
94
94
 
95
95
  expect(result.functions.auth.handler).toBe('node_modules/@friggframework/core/handlers/routers/auth.handler');
96
96
  expect(result.functions.auth.layers).toEqual([{ Ref: 'PrismaLambdaLayer' }]);
97
- expect(result.functions.auth.events).toHaveLength(3);
97
+ expect(
98
+ result.functions.auth.events.map(
99
+ (e) => `${e.httpApi.method} ${e.httpApi.path}`
100
+ )
101
+ ).toEqual([
102
+ // v1 (deprecated, ADR-053)
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/{proxy+}',
109
+ // v2, per resource: never ANY /api/v2/{proxy+}, which would
110
+ // shadow /api/v2/reports on the admin-scripts Lambda
111
+ 'ANY /api/v2/integrations',
112
+ 'ANY /api/v2/integrations/{proxy+}',
113
+ 'ANY /api/v2/entities',
114
+ 'ANY /api/v2/entities/{proxy+}',
115
+ 'ANY /api/v2/credentials',
116
+ 'ANY /api/v2/credentials/{proxy+}',
117
+ 'ANY /api/v2/authorize',
118
+ ]);
119
+ });
120
+
121
+ it('takes the Management API routes from the core route registry', () => {
122
+ const { getGatewayRoutes } = require('@friggframework/core/management-api/route-registry');
123
+ const result = createBaseDefinition({}, {}, {});
124
+ const declared = (fn) =>
125
+ result.functions[fn].events
126
+ .map((e) => `${e.httpApi.method} ${e.httpApi.path}`)
127
+ .filter((route) => route.includes('/api/'));
128
+ const registry = (fn) =>
129
+ getGatewayRoutes()
130
+ .filter((r) => r.function === fn)
131
+ .map((r) => `${r.method} ${r.path}`);
132
+ expect(declared('auth')).toEqual(registry('auth'));
133
+ expect(declared('health')).toEqual(registry('health'));
134
+ });
135
+
136
+ it('serves /api/meta from the DB-free health function', () => {
137
+ const result = createBaseDefinition({}, {}, {});
138
+ expect(
139
+ result.functions.health.events.map((e) => `${e.httpApi.method} ${e.httpApi.path}`)
140
+ ).toEqual([
141
+ 'GET /health',
142
+ 'GET /health/{proxy+}',
143
+ 'GET /api/meta',
144
+ 'GET /api/meta/{proxy+}',
145
+ // Redirects to /api/meta/openapi/v2.json (ADR-053 docs path)
146
+ 'GET /api/docs',
147
+ ]);
148
+ });
149
+
150
+ it('routes each core extension admin path (and below) to the auth function', () => {
151
+ const result = createBaseDefinition(
152
+ {
153
+ coreExtensions: [
154
+ { name: 'db-credentials', routes: { path: '/admin/oauth-credentials' } },
155
+ { name: 'no-routes' },
156
+ ],
157
+ },
158
+ {},
159
+ {}
160
+ );
161
+ const routes = result.functions.auth.events.map(
162
+ (e) => `${e.httpApi.method} ${e.httpApi.path}`
163
+ );
164
+ expect(routes).toContain('ANY /admin/oauth-credentials');
165
+ expect(routes).toContain('ANY /admin/oauth-credentials/{proxy+}');
166
+ // Never a catch-all that would shadow /admin/scripts or /admin/db-migrate.
167
+ expect(routes).not.toContain('ANY /admin/{proxy+}');
168
+ // The HTTP queue route is for hosts without SQS, never AWS.
169
+ expect(JSON.stringify(result.functions)).not.toContain('/admin/queue');
170
+ });
171
+
172
+ it('drops the v1 routes when managementApi.v1 is false, keeping the OAuth redirect', () => {
173
+ const result = createBaseDefinition({ managementApi: { v1: false } }, {}, {});
174
+ const routes = result.functions.auth.events.map(
175
+ (e) => `${e.httpApi.method} ${e.httpApi.path}`
176
+ );
177
+ expect(routes).not.toContain('ANY /api/integrations');
178
+ expect(routes).not.toContain('ANY /api/authorize');
179
+ expect(routes).not.toContain('ANY /api/entity');
180
+ expect(routes).toContain('GET /api/integrations/redirect/{appId}');
181
+ expect(routes).toContain('ANY /api/v2/integrations');
98
182
  });
99
183
 
100
184
  it('should NOT include legacy dbMigrate function', () => {
@@ -153,7 +153,17 @@ async function ensurePrismaLayerExists(databaseConfig = {}) {
153
153
  }
154
154
  }
155
155
 
156
+ /**
157
+ * Forces the next ensurePrismaLayerExists() to rebuild the layer, e.g. after
158
+ * the Prisma client it copies was regenerated.
159
+ */
160
+ function invalidatePrismaLayer() {
161
+ const marker = path.join(process.cwd(), 'layers/prisma', '.build-complete');
162
+ fs.rmSync(marker, { force: true });
163
+ }
164
+
156
165
  module.exports = {
166
+ invalidatePrismaLayer,
157
167
  ensurePrismaLayerExists,
158
168
  };
159
169
 
@@ -17,7 +17,6 @@ const { SsmBuilder } = require('./domains/parameters/ssm-builder');
17
17
  const { WebsocketBuilder } = require('./domains/integration/websocket-builder');
18
18
  const { IntegrationBuilder } = require('./domains/integration/integration-builder');
19
19
  const { SchedulerBuilder } = require('./domains/scheduler/scheduler-builder');
20
- const { TriggerBuilder } = require('./domains/scheduler/trigger-builder');
21
20
  const { AdminScriptBuilder } = require('./domains/admin-scripts/admin-script-builder');
22
21
 
23
22
  // Utilities
@@ -61,7 +60,8 @@ function applySsmPreloadNodeOptions(appDefinition, functions, providerEnvironmen
61
60
  }
62
61
  const { modifyHandlerPaths } = require('./domains/shared/utilities/handler-path-resolver');
63
62
  const { createBaseDefinition } = require('./domains/shared/utilities/base-definition-factory');
64
- const { ensurePrismaLayerExists } = require('./domains/shared/utilities/prisma-layer-manager');
63
+ const { ensurePrismaLayerExists, invalidatePrismaLayer } = require('./domains/shared/utilities/prisma-layer-manager');
64
+ const { composeAppExtensionPrisma } = require('./compose-extension-prisma');
65
65
  const { validateAndCleanPlugins, validatePackagingConfiguration } = require('./domains/shared/validation/plugin-validator');
66
66
 
67
67
  /**
@@ -76,6 +76,17 @@ const composeServerlessDefinition = async (AppDefinition) => {
76
76
  // Determine if deployment should use Prisma Lambda Layer (default: true)
77
77
  const usePrismaLayer = AppDefinition.usePrismaLambdaLayer !== false;
78
78
 
79
+ // Core extensions' models go into core's Prisma client before anything
80
+ // copies it (the layer, or the functions when bundling Prisma). A changed
81
+ // client invalidates a layer built from the previous one.
82
+ const extensionPrisma = composeAppExtensionPrisma({
83
+ appDefinition: AppDefinition,
84
+ backendDir: process.cwd(),
85
+ });
86
+ if (extensionPrisma.changed && usePrismaLayer) {
87
+ invalidatePrismaLayer();
88
+ }
89
+
79
90
  // Ensure Prisma layer exists only when configured to use it
80
91
  if (usePrismaLayer) {
81
92
  await ensurePrismaLayerExists(AppDefinition.database || {});
@@ -93,7 +104,6 @@ const composeServerlessDefinition = async (AppDefinition) => {
93
104
  new WebsocketBuilder(),
94
105
  new IntegrationBuilder(),
95
106
  new SchedulerBuilder(), // Add scheduler after IntegrationBuilder (depends on it)
96
- new TriggerBuilder(), // One trigger tick function per integration with triggers (ADR-055)
97
107
  new AdminScriptBuilder(),
98
108
  ]);
99
109
 
@@ -2,6 +2,13 @@ const {
2
2
  composeServerlessDefinition,
3
3
  applySsmPreloadNodeOptions,
4
4
  } = require('./infrastructure-composer');
5
+ // Composing must not build the real Prisma layer: that runs npm install
6
+ // under packages/devtools, and two workers doing it at once once pruned the
7
+ // repository's root node_modules (test/npm-install-guard.js).
8
+ jest.mock('./domains/shared/utilities/prisma-layer-manager', () => ({
9
+ ensurePrismaLayerExists: jest.fn(async () => {}),
10
+ }));
11
+
5
12
  const {
6
13
  SSM_PRELOAD_NODE_OPTIONS,
7
14
  } = require('./domains/parameters/offload-utils');
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Build for a non-AWS provider (friggframework/frigg#545, 302ab9ba /
3
+ * c8705715).
4
+ *
5
+ * Instead of the serverless/CloudFormation pipeline, the provider plugin
6
+ * (resolved from appDefinition.provider) does the build. First, core
7
+ * extensions' Prisma models are composed into the backend's Prisma client
8
+ * (compose-extension-prisma.js), since the functions bundle that client:
9
+ * 1. validate(appDefinition) - errors abort, warnings print
10
+ * 2. generateConfig(appDefinition) - e.g. netlify.toml
11
+ * 3. getFunctionEntryPoints(appDefinition) - written to <project>/netlify/functions
12
+ * 4. getLibEntryPoints(appDefinition) - written to <project>/netlify/lib
13
+ *
14
+ * <project> is the directory that holds backend/: the generated entry points
15
+ * require '../../backend/...', so they must sit beside it. #545 had two
16
+ * copies of this, and the CLI one wrote into the backend directory itself,
17
+ * where those relative requires do not resolve.
18
+ *
19
+ * Shared by createFriggInfrastructure() (`node infrastructure.js package`,
20
+ * what a backend's `npm run build` runs) and `frigg build`.
21
+ */
22
+ const path = require('path');
23
+ const fs = require('fs');
24
+ const { composeAppExtensionPrisma } = require('./compose-extension-prisma');
25
+
26
+ const CONFIG_FILE_NAMES = { netlify: 'netlify.toml' };
27
+
28
+ /**
29
+ * @param {Object} params
30
+ * @param {Object} params.appDefinition
31
+ * @param {string} params.backendDir - directory containing the backend's index.js
32
+ * @param {Object} [params.provider] - resolved plugin; defaults to resolveProvider(appDefinition)
33
+ * @param {boolean} [params.verbose]
34
+ * @param {Function} [params.exit] - called with 1 on validation errors (default process.exit)
35
+ * @param {Function} [params.composePrisma] - extension Prisma composition (injected in tests)
36
+ * @returns {{ projectDir: string, written: string[] }}
37
+ */
38
+ function buildWithProvider({
39
+ appDefinition,
40
+ backendDir,
41
+ provider,
42
+ verbose = false,
43
+ exit = (code) => process.exit(code),
44
+ composePrisma = composeAppExtensionPrisma,
45
+ }) {
46
+ const providerName = appDefinition.provider;
47
+ const plugin =
48
+ provider ||
49
+ require('@friggframework/core/providers/resolve-provider').resolveProvider(
50
+ appDefinition
51
+ );
52
+ const projectDir = path.dirname(path.resolve(backendDir));
53
+ const written = [];
54
+
55
+ console.log(`Building for ${providerName} provider (skipping AWS infrastructure)...`);
56
+
57
+ if (typeof plugin.validate === 'function') {
58
+ const validation = plugin.validate(appDefinition);
59
+ if (validation.errors?.length > 0) {
60
+ console.error(`\nValidation errors for ${providerName}:`);
61
+ for (const error of validation.errors) {
62
+ console.error(` - ${error}`);
63
+ }
64
+ exit(1);
65
+ return { projectDir, written };
66
+ }
67
+ for (const warning of validation.warnings || []) {
68
+ console.warn(` Warning: ${warning}`);
69
+ }
70
+ }
71
+
72
+ composePrisma({ appDefinition, backendDir });
73
+
74
+ const write = (filePath, content) => {
75
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
76
+ fs.writeFileSync(filePath, content, 'utf-8');
77
+ written.push(filePath);
78
+ if (verbose) console.log(` Written ${path.relative(projectDir, filePath)}`);
79
+ };
80
+
81
+ if (typeof plugin.generateConfig === 'function') {
82
+ const fileName = CONFIG_FILE_NAMES[providerName] || `${providerName}.config`;
83
+ write(path.join(projectDir, fileName), plugin.generateConfig(appDefinition));
84
+ console.log(` Written ${fileName}`);
85
+ }
86
+
87
+ if (typeof plugin.getFunctionEntryPoints === 'function') {
88
+ const entryPoints = plugin.getFunctionEntryPoints(appDefinition);
89
+ for (const [fileName, content] of Object.entries(entryPoints)) {
90
+ write(path.join(projectDir, 'netlify', 'functions', fileName), content);
91
+ }
92
+ console.log(` Generated ${Object.keys(entryPoints).length} function entry points`);
93
+ }
94
+
95
+ if (typeof plugin.getLibEntryPoints === 'function') {
96
+ const libEntryPoints = plugin.getLibEntryPoints(appDefinition);
97
+ for (const [fileName, content] of Object.entries(libEntryPoints)) {
98
+ write(path.join(projectDir, 'netlify', 'lib', fileName), content);
99
+ }
100
+ console.log(` Generated ${Object.keys(libEntryPoints).length} lib entry points`);
101
+ }
102
+
103
+ if (typeof plugin.generateEnvTemplate === 'function') {
104
+ const missing = Object.entries(plugin.generateEnvTemplate(appDefinition)).filter(
105
+ ([key]) => !process.env[key]
106
+ );
107
+ if (missing.length > 0) {
108
+ console.log('\n Environment variables not set locally (configure them on the platform):');
109
+ for (const [key] of missing) console.log(` - ${key}`);
110
+ }
111
+ }
112
+
113
+ console.log(`\nBuild complete for ${providerName}.`);
114
+ return { projectDir, written };
115
+ }
116
+
117
+ /**
118
+ * True when the app definition names a provider other than AWS.
119
+ * @param {Object} [appDefinition]
120
+ */
121
+ function isNonAwsProvider(appDefinition) {
122
+ const name = appDefinition?.provider;
123
+ return Boolean(name) && name !== 'aws';
124
+ }
125
+
126
+ module.exports = { buildWithProvider, isNonAwsProvider };