@friggframework/devtools 2.0.0--canary.703.6a9383b.0 → 2.0.0--canary.680.daae24e.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.
@@ -163,9 +163,11 @@ const appDefinition = {
163
163
  enableVPCEndpoints: true // Optional: create VPC endpoints
164
164
  },
165
165
 
166
- // KMS encryption
166
+ // Field-level encryption. 'kms' wires KMS_KEY_ARN on every stage (dev too).
167
+ // A deployed stage with no key refuses to start; 'none' is the explicit
168
+ // plaintext opt-out (sets FRIGG_ENCRYPTION_DISABLED=true).
167
169
  encryption: {
168
- fieldLevelEncryptionMethod: 'kms',
170
+ fieldLevelEncryptionMethod: 'kms', // 'kms' | 'aes' | 'none'
169
171
  createResourceIfNoneFound: true
170
172
  },
171
173
 
@@ -0,0 +1,335 @@
1
+ /**
2
+ * Management API ↔ API Gateway route coverage
3
+ *
4
+ * The Management API (ADR-053) is served by the `auth` Lambda (v1, v2 and
5
+ * the OAuth redirect) and, for /api/meta, by the DB-free `health` Lambda.
6
+ * API Gateway HTTP APIs have no implicit catch-all: a request whose path
7
+ * matches no declared route gets a gateway 404 and never reaches Express.
8
+ * So every route those routers register must be covered by an httpApi event
9
+ * on the right function, and no more-specific route on another function may
10
+ * shadow it. Both the routers and the gateway routes come from core's route
11
+ * registry; this test proves the outcome end to end.
12
+ *
13
+ * The Express routes are read from the live routers (not a hard-coded
14
+ * list), so a route added to core later fails this test until the gateway
15
+ * routes follow.
16
+ */
17
+
18
+ // Avoid AWS calls: hand the builders a fixed discovery result.
19
+ jest.mock('../domains/shared/resource-discovery', () => {
20
+ const actual = jest.requireActual('../domains/shared/resource-discovery');
21
+ return {
22
+ ...actual,
23
+ gatherDiscoveredResources: jest.fn().mockResolvedValue({
24
+ defaultVpcId: 'vpc-123456',
25
+ vpcCidr: '172.31.0.0/16',
26
+ defaultSecurityGroupId: 'sg-123456',
27
+ privateSubnetId1: 'subnet-123456',
28
+ privateSubnetId2: 'subnet-789012',
29
+ publicSubnetId1: 'subnet-public-1',
30
+ publicSubnetId2: 'subnet-public-2',
31
+ defaultRouteTableId: 'rtb-123456',
32
+ defaultKmsKeyId:
33
+ 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012',
34
+ existingNatGatewayId: 'nat-default123',
35
+ auroraClusterEndpoint:
36
+ 'test-cluster.cluster-abc123.us-east-1.rds.amazonaws.com',
37
+ auroraPort: 5432,
38
+ auroraEngine: 'aurora-postgresql',
39
+ }),
40
+ };
41
+ });
42
+
43
+ // The Management API routers load the app definition from the consuming
44
+ // backend; give them one so they can be built in isolation. The entity proxy
45
+ // is enabled so its route is checked too.
46
+ jest.mock('@friggframework/core/handlers/app-definition-loader', () => ({
47
+ loadAppDefinition: () => ({
48
+ integrations: [],
49
+ userConfig: {},
50
+ managementApi: { proxy: { enable: true } },
51
+ }),
52
+ }));
53
+
54
+ const { composeServerlessDefinition } = require('../infrastructure-composer');
55
+
56
+ /** Routes registered on an Express router, including nested routers. */
57
+ function collectRoutes(router, routes = new Map()) {
58
+ const stack = (router._router || router).stack || [];
59
+ for (const layer of stack) {
60
+ if (layer.route) {
61
+ for (const method of Object.keys(layer.route.methods)) {
62
+ const route = {
63
+ method: method === '_all' ? 'ANY' : method.toUpperCase(),
64
+ path: layer.route.path,
65
+ };
66
+ routes.set(`${route.method} ${route.path}`, route);
67
+ }
68
+ } else if (layer.handle && Array.isArray(layer.handle.stack)) {
69
+ collectRoutes(layer.handle, routes);
70
+ }
71
+ }
72
+ return routes;
73
+ }
74
+
75
+ /**
76
+ * Builds a core router with DB_TYPE set: the repository factories pick an
77
+ * adapter from it (or the backend's app definition, which doesn't exist
78
+ * here). Nothing connects.
79
+ */
80
+ function withDbType(build) {
81
+ const previousDbType = process.env.DB_TYPE;
82
+ process.env.DB_TYPE = 'postgresql';
83
+ try {
84
+ return build();
85
+ } finally {
86
+ if (previousDbType === undefined) delete process.env.DB_TYPE;
87
+ else process.env.DB_TYPE = previousDbType;
88
+ }
89
+ }
90
+
91
+ /** Every route the auth Lambda's router (core/handlers/routers/auth.js) serves. */
92
+ function getAuthLambdaRoutes() {
93
+ const { router } = withDbType(() =>
94
+ require('@friggframework/core/handlers/routers/auth')
95
+ );
96
+ return [...collectRoutes(router).values()];
97
+ }
98
+
99
+ /** Every route the health Lambda serves under /api/meta. */
100
+ function getMetaRoutes() {
101
+ const { router } = withDbType(() =>
102
+ require('@friggframework/core/handlers/routers/health')
103
+ );
104
+ return [...collectRoutes(router).values()].filter((r) =>
105
+ r.path.startsWith('/api/meta')
106
+ );
107
+ }
108
+
109
+ function getGatewayRoutes(definition) {
110
+ const routes = [];
111
+ for (const [functionName, fn] of Object.entries(definition.functions)) {
112
+ for (const event of fn.events || []) {
113
+ if (!event.httpApi) continue;
114
+ routes.push({
115
+ functionName,
116
+ method: String(event.httpApi.method).toUpperCase(),
117
+ path: event.httpApi.path,
118
+ });
119
+ }
120
+ }
121
+ return routes;
122
+ }
123
+
124
+ const segmentsOf = (p) => p.split('/').filter(Boolean);
125
+
126
+ // Turn an Express path into a concrete request path, e.g.
127
+ // /api/entities/:entityId/options -> /api/entities/sample-entityId/options
128
+ const toConcretePath = (expressPath) =>
129
+ expressPath.replace(/:([A-Za-z0-9_]+)/g, 'sample-$1');
130
+
131
+ /**
132
+ * HTTP API path matching: literal segments match exactly, {param} matches
133
+ * one segment, a trailing {proxy+} greedily matches one or more segments.
134
+ * Returns null on no match, otherwise a specificity descriptor.
135
+ */
136
+ function matchGatewayPath(gatewayPath, requestPath) {
137
+ const g = segmentsOf(gatewayPath);
138
+ const r = segmentsOf(requestPath);
139
+ let literals = 0;
140
+ for (let i = 0; i < g.length; i++) {
141
+ const seg = g[i];
142
+ if (/^\{[^}]+\+\}$/.test(seg)) {
143
+ if (i !== g.length - 1 || r.length <= i) return null;
144
+ return { greedy: true, literals, prefixLength: i };
145
+ }
146
+ if (i >= r.length) return null;
147
+ if (/^\{[^}]+\}$/.test(seg)) continue;
148
+ if (seg !== r[i]) return null;
149
+ literals++;
150
+ }
151
+ if (g.length !== r.length) return null;
152
+ return { greedy: false, literals, prefixLength: g.length };
153
+ }
154
+
155
+ /**
156
+ * Select the route API Gateway would invoke: a non-greedy match beats a
157
+ * greedy one, then more literal segments, then the longer greedy prefix,
158
+ * then an explicit method beats ANY.
159
+ */
160
+ function selectGatewayRoute(gatewayRoutes, method, requestPath) {
161
+ const candidates = gatewayRoutes
162
+ .filter(
163
+ (r) => r.method === 'ANY' || method === 'ANY' || r.method === method
164
+ )
165
+ .map((r) => ({
166
+ route: r,
167
+ match: matchGatewayPath(r.path, requestPath),
168
+ }))
169
+ .filter((c) => c.match);
170
+ candidates.sort(
171
+ (a, b) =>
172
+ Number(a.match.greedy) - Number(b.match.greedy) ||
173
+ b.match.literals - a.match.literals ||
174
+ b.match.prefixLength - a.match.prefixLength ||
175
+ Number(a.route.method === 'ANY') - Number(b.route.method === 'ANY')
176
+ );
177
+ return candidates.length ? candidates[0].route : null;
178
+ }
179
+
180
+ describe('Management API routes are reachable through API Gateway', () => {
181
+ let gatewayRoutes;
182
+ let managementRoutes;
183
+ let metaRoutes;
184
+ const originalArgv = process.argv;
185
+
186
+ beforeAll(async () => {
187
+ process.argv = ['node', 'test'];
188
+ process.env.AWS_REGION = 'us-east-1';
189
+ // The builders narrate their progress; keep the test output quiet.
190
+ const logSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
191
+ const warnSpy = jest
192
+ .spyOn(console, 'warn')
193
+ .mockImplementation(() => {});
194
+ try {
195
+ const definition = await composeServerlessDefinition({
196
+ name: 'route-coverage-app',
197
+ provider: 'aws',
198
+ usePrismaLambdaLayer: false,
199
+ database: { postgres: { enable: true } },
200
+ websockets: { enable: true },
201
+ adminScripts: [
202
+ class ExampleScript {
203
+ static Definition = { name: 'example-script' };
204
+ },
205
+ ],
206
+ admin: { includeBuiltinReports: true },
207
+ integrations: [
208
+ {
209
+ Definition: {
210
+ name: 'acme',
211
+ webhooks: true,
212
+ extensions: {
213
+ inbound: {
214
+ extension: {
215
+ routes: [
216
+ { path: '/events', method: 'POST' },
217
+ ],
218
+ },
219
+ },
220
+ },
221
+ },
222
+ },
223
+ // Integration names share the /api/ namespace with the
224
+ // Management API; make sure they don't shadow it.
225
+ { Definition: { name: 'entities' } },
226
+ ],
227
+ });
228
+ gatewayRoutes = getGatewayRoutes(definition);
229
+ } finally {
230
+ logSpy.mockRestore();
231
+ warnSpy.mockRestore();
232
+ }
233
+ managementRoutes = getAuthLambdaRoutes();
234
+ metaRoutes = getMetaRoutes();
235
+ });
236
+
237
+ afterAll(() => {
238
+ process.argv = originalArgv;
239
+ delete process.env.AWS_REGION;
240
+ });
241
+
242
+ it('reads the Management API routes from the live auth and health routers', () => {
243
+ const paths = managementRoutes.map((r) => r.path);
244
+ expect(paths).toEqual(
245
+ expect.arrayContaining([
246
+ '/api/integrations',
247
+ '/api/authorize',
248
+ '/api/entity',
249
+ '/api/entity/options/:credentialId',
250
+ '/api/entities/:entityId',
251
+ '/api/integrations/redirect/:appId',
252
+ '/api/v2/integrations',
253
+ '/api/v2/entities/types/:entityType/requirements',
254
+ '/api/v2/entities/:entityId/proxy',
255
+ '/api/v2/credentials/:credentialId/reauthorize',
256
+ '/api/v2/authorize',
257
+ ])
258
+ );
259
+ expect(metaRoutes.map((r) => r.path)).toEqual(
260
+ expect.arrayContaining(['/api/meta', '/api/meta/openapi/v2.json'])
261
+ );
262
+ });
263
+
264
+ it('routes /api/meta to the DB-free health function', () => {
265
+ const unreachable = metaRoutes
266
+ .map(({ method, path: requestPath }) => {
267
+ const selected = selectGatewayRoute(gatewayRoutes, method, requestPath);
268
+ return { route: `${method} ${requestPath}`, ok: selected?.functionName === 'health' };
269
+ })
270
+ .filter((r) => !r.ok)
271
+ .map((r) => r.route);
272
+ expect(unreachable).toEqual([]);
273
+ });
274
+
275
+ it('declares no /api/v2 catch-all', () => {
276
+ expect(
277
+ gatewayRoutes.filter((r) => r.path === '/api/v2/{proxy+}' || r.path === '/api/v2')
278
+ ).toEqual([]);
279
+ expect(selectGatewayRoute(gatewayRoutes, 'PATCH', '/api/v2/reports/daily')).toBeNull();
280
+ });
281
+
282
+ it('routes every Management API route to the auth function', () => {
283
+ const unreachable = managementRoutes
284
+ .map(({ method, path: expressPath }) => {
285
+ const requestPath = toConcretePath(expressPath);
286
+ const selected = selectGatewayRoute(
287
+ gatewayRoutes,
288
+ method,
289
+ requestPath
290
+ );
291
+ return {
292
+ route: `${method} ${expressPath}`,
293
+ reachedBy: selected
294
+ ? `${selected.method} ${selected.path} -> ${selected.functionName}`
295
+ : 'no API Gateway route',
296
+ ok: selected && selected.functionName === 'auth',
297
+ };
298
+ })
299
+ .filter((r) => !r.ok)
300
+ .map(({ route, reachedBy }) => `${route} (${reachedBy})`);
301
+
302
+ expect(unreachable).toEqual([]);
303
+ });
304
+
305
+ it.each([
306
+ ['GET', '/api/v2/reports', 'reportRouter'],
307
+ ['POST', '/api/v2/reports/daily/run', 'reportRouter'],
308
+ ['GET', '/api/v2/reports/daily', 'reportRouter'],
309
+ ['GET', '/admin/scripts/example-script', 'adminScriptRouter'],
310
+ ['POST', '/api/acme-integration/webhooks', 'acmeWebhook'],
311
+ ['POST', '/api/acme-integration/inbound/events', 'acme__inbound'],
312
+ ['GET', '/api/acme-integration/custom', 'acme'],
313
+ ['GET', '/api/entities-integration/custom', 'entities'],
314
+ ['POST', '/user/login', 'user'],
315
+ ['GET', '/health/ready', 'health'],
316
+ ])('leaves %s %s on %s', (method, requestPath, functionName) => {
317
+ const selected = selectGatewayRoute(gatewayRoutes, method, requestPath);
318
+ expect(selected && selected.functionName).toBe(functionName);
319
+ });
320
+
321
+ it('declares no method + path pair on more than one function', () => {
322
+ const seen = new Map();
323
+ const duplicates = [];
324
+ for (const r of gatewayRoutes) {
325
+ const key = `${r.method} ${r.path}`;
326
+ if (seen.has(key) && seen.get(key) !== r.functionName) {
327
+ duplicates.push(
328
+ `${key}: ${seen.get(key)} and ${r.functionName}`
329
+ );
330
+ }
331
+ seen.set(key, r.functionName);
332
+ }
333
+ expect(duplicates).toEqual([]);
334
+ });
335
+ });
@@ -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: {
@@ -10,6 +10,24 @@
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 Management API route
19
+ * registry (ADR-053): the same registry mounts the Express routers and
20
+ * builds the OpenAPI documents, so the three cannot drift.
21
+ */
22
+ function managementApiEvents(AppDefinition, functionName) {
23
+ const managementApi = AppDefinition.managementApi || {};
24
+ return getGatewayRoutes({
25
+ v1: managementApi.v1 !== false,
26
+ proxy: managementApi.proxy?.enable === true,
27
+ })
28
+ .filter((route) => route.function === functionName)
29
+ .map(({ method, path }) => ({ httpApi: { path, method } }));
30
+ }
13
31
 
14
32
  /**
15
33
  * Create base serverless definition with core functions and resources
@@ -286,16 +304,12 @@ function createBaseDefinition(
286
304
  ...(usePrismaLayer && { layers: [{ Ref: 'PrismaLambdaLayer' }] }),
287
305
  skipEsbuild: true, // Handlers in node_modules don't need bundling
288
306
  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
- ],
307
+ // Every Management API path the auth Lambda serves (v1, v2 per
308
+ // resource, the OAuth redirect) comes from core's route
309
+ // registry. HTTP API has no implicit catch-all, so an unlisted
310
+ // prefix 404s at the gateway before Express sees it. Guarded by
311
+ // __tests__/management-api-gateway-routes.test.js.
312
+ events: managementApiEvents(AppDefinition, 'auth'),
299
313
  },
300
314
  user: {
301
315
  handler: 'node_modules/@friggframework/core/handlers/routers/user.handler',
@@ -312,6 +326,8 @@ function createBaseDefinition(
312
326
  events: [
313
327
  { httpApi: { path: '/health', method: 'GET' } },
314
328
  { httpApi: { path: '/health/{proxy+}', method: 'GET' } },
329
+ // GET /api/meta and the OpenAPI documents: public, DB-free.
330
+ ...managementApiEvents(AppDefinition, 'health'),
315
331
  ],
316
332
  },
317
333
  // 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,67 @@ 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
+ ]);
146
+ });
147
+
148
+ it('drops the v1 routes when managementApi.v1 is false, keeping the OAuth redirect', () => {
149
+ const result = createBaseDefinition({ managementApi: { v1: false } }, {}, {});
150
+ const routes = result.functions.auth.events.map(
151
+ (e) => `${e.httpApi.method} ${e.httpApi.path}`
152
+ );
153
+ expect(routes).not.toContain('ANY /api/integrations');
154
+ expect(routes).not.toContain('ANY /api/authorize');
155
+ expect(routes).not.toContain('ANY /api/entity');
156
+ expect(routes).toContain('GET /api/integrations/redirect/{appId}');
157
+ expect(routes).toContain('ANY /api/v2/integrations');
98
158
  });
99
159
 
100
160
  it('should NOT include legacy dbMigrate function', () => {
@@ -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
@@ -93,7 +92,6 @@ const composeServerlessDefinition = async (AppDefinition) => {
93
92
  new WebsocketBuilder(),
94
93
  new IntegrationBuilder(),
95
94
  new SchedulerBuilder(), // Add scheduler after IntegrationBuilder (depends on it)
96
- new TriggerBuilder(), // One trigger tick function per integration with triggers (ADR-055)
97
95
  new AdminScriptBuilder(),
98
96
  ]);
99
97
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/devtools",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.703.6a9383b.0",
4
+ "version": "2.0.0--canary.680.daae24e.0",
5
5
  "bin": {
6
6
  "frigg": "./frigg-cli/index.js"
7
7
  },
@@ -26,9 +26,9 @@
26
26
  "@babel/eslint-parser": "^7.18.9",
27
27
  "@babel/parser": "^7.25.3",
28
28
  "@babel/traverse": "^7.25.3",
29
- "@friggframework/core": "2.0.0--canary.703.6a9383b.0",
30
- "@friggframework/schemas": "2.0.0--canary.703.6a9383b.0",
31
- "@friggframework/test": "2.0.0--canary.703.6a9383b.0",
29
+ "@friggframework/core": "2.0.0--canary.680.daae24e.0",
30
+ "@friggframework/schemas": "2.0.0--canary.680.daae24e.0",
31
+ "@friggframework/test": "2.0.0--canary.680.daae24e.0",
32
32
  "@hapi/boom": "^10.0.1",
33
33
  "@inquirer/prompts": "^5.3.8",
34
34
  "axios": "^1.18.0",
@@ -56,8 +56,8 @@
56
56
  "validate-npm-package-name": "^5.0.0"
57
57
  },
58
58
  "devDependencies": {
59
- "@friggframework/eslint-config": "2.0.0--canary.703.6a9383b.0",
60
- "@friggframework/prettier-config": "2.0.0--canary.703.6a9383b.0",
59
+ "@friggframework/eslint-config": "2.0.0--canary.680.daae24e.0",
60
+ "@friggframework/prettier-config": "2.0.0--canary.680.daae24e.0",
61
61
  "aws-sdk-client-mock": "^4.1.0",
62
62
  "aws-sdk-client-mock-jest": "^4.1.0",
63
63
  "jest": "^30.1.3",
@@ -89,5 +89,5 @@
89
89
  "publishConfig": {
90
90
  "access": "public"
91
91
  },
92
- "gitHead": "6a9383b6cc7509a30ec3f0499d2f9ad52568dd45"
92
+ "gitHead": "daae24ec9d6b03c59759b6b42f6f99369b683981"
93
93
  }
@@ -1,59 +0,0 @@
1
- /**
2
- * A defineIntegration app (ADR-054) provisions through the existing builders with no new path: the contract-2
3
- * binding gets its own function under the derived key, and `triggers` get the ADR-055 tick.
4
- */
5
- jest.mock('@friggframework/core/database/config', () => ({ DB_TYPE: 'mongodb', getDatabaseType: jest.fn(() => 'mongodb'), PRISMA_LOG_LEVEL: 'error,warn' }));
6
-
7
- const { defineApp, defineIntegration, use } = require('@friggframework/core/integrations/define');
8
- const { IntegrationBuilder } = require('./integration-builder');
9
- const { TriggerBuilder } = require('../scheduler/trigger-builder');
10
-
11
- /** A module with a contract-2 webhooks extension, reduced to what provisioning reads. */
12
- const crmModule = {
13
- Definition: { moduleName: 'crm-vendor', getName: () => 'crm-vendor' },
14
- extensions: {
15
- webhooks: {
16
- name: 'crm-vendor-webhooks',
17
- contract: 2,
18
- useDatabase: false,
19
- routes: [{ path: '/webhooks', method: 'POST' }],
20
- receive: (input) => [{ externalId: input.body.account, body: input.body }],
21
- resolve: { module: 'crm-vendor' },
22
- emits: { 'deal.changed': {} },
23
- },
24
- },
25
- };
26
- const chatModule = { Definition: { moduleName: 'chat-vendor', getName: () => 'chat-vendor' } };
27
-
28
- const app = defineApp({
29
- name: 'deal-alerts',
30
- integrations: [
31
- defineIntegration({
32
- name: 'deal-alerts',
33
- modules: { crm: use(crmModule, { webhooks: {} }), chat: use(chatModule) },
34
- on: { 'crm.deal.changed': async () => {} },
35
- triggers: { digest: { every: '1h', handler: async () => {} } },
36
- }),
37
- ],
38
- }, { schemas: null });
39
-
40
- describe('a defineIntegration app on the existing builders', () => {
41
- beforeEach(() => { jest.spyOn(console, 'log').mockImplementation(() => {}); });
42
- afterEach(() => { jest.restoreAllMocks(); });
43
-
44
- it('gives the contract-2 binding its own function, routed under the module key', async () => {
45
- const result = await new IntegrationBuilder().build(app.Definition, {});
46
- const fn = result.functions['deal-alerts__crmwebhooks'];
47
- expect(fn.handler).toBe('node_modules/@friggframework/core/handlers/routers/integration-defined-routers.handlers.deal-alerts__crmwebhooks.handler');
48
- expect(fn.events).toEqual([{ httpApi: { path: '/api/deal-alerts-integration/crm-webhooks/webhooks', method: 'POST' } }]);
49
- expect(fn.layers).toBeUndefined(); // useDatabase: false, so no Prisma layer
50
- expect(result.functions['deal-alertsQueueWorker']).toBeDefined();
51
- });
52
-
53
- it('provisions the ADR-055 tick for its triggers', async () => {
54
- const builder = new TriggerBuilder();
55
- expect(builder.shouldExecute(app.Definition)).toBe(true);
56
- const result = await builder.build(app.Definition, {});
57
- expect(JSON.stringify(result)).toContain('rate(1 hour)');
58
- });
59
- });
@@ -1,114 +0,0 @@
1
- /**
2
- * Trigger Builder (ADR-055 §2)
3
- *
4
- * Domain Layer - Hexagonal Architecture
5
- *
6
- * One function per integration that declares recurring triggers: `{integration}Triggers`, with the Prisma layer.
7
- * It gets one serverless `schedule` event per distinct tick of the integration's `every` / `cron` triggers (and of
8
- * the triggers it resolves per installation, `Definition.instanceTriggers`), plus one EventBridge Scheduler event per
9
- * `at` trigger, with its time zone. Each tick pages through the ENABLED installations and queues the runs that are
10
- * due (core: integrations/use-cases/run-trigger-tick.js). Nothing is created per installation, and these resources
11
- * change only when a Definition does, so they live in CloudFormation and leave with the stack.
12
- *
13
- * IAM, and why this builder adds none:
14
- * - A `rate()` tick is an EventBridge rule; the framework adds the Lambda permission for it.
15
- * - An `at` trigger uses `method: scheduler`; the framework adds `scheduler.amazonaws.com` to the function role's
16
- * trust policy and `lambda:InvokeFunction` on this function to it.
17
- * - The tick reads the integration table (the Prisma layer and the provider's database access, like the queue
18
- * worker) and sends to its own `<Name>Queue`, which the provider-level `sqs:SendMessage(Batch)` statement on
19
- * `${service}--${stage}-*Queue` already allows. It never calls EventBridge Scheduler at runtime, so it needs none
20
- * of SchedulerBuilder's scheduler:* permissions (those stay for one-time jobs).
21
- */
22
-
23
- const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
24
- const { IntegrationBuilder } = require('../integration/integration-builder');
25
- const {
26
- hasTriggers,
27
- provisioningOf,
28
- durationOf,
29
- } = require('@friggframework/core/integrations/triggers');
30
-
31
- /** EventBridge rate() for a tick in minutes: rate(1 minute), rate(5 minutes), rate(1 hour), rate(2 hours), rate(1 day). */
32
- function rateExpression(minutes) {
33
- const [count, unit] =
34
- minutes % 1440 === 0 ? [minutes / 1440, 'day'] : minutes % 60 === 0 ? [minutes / 60, 'hour'] : [minutes, 'minute'];
35
- return `rate(${count} ${unit}${count === 1 ? '' : 's'})`;
36
- }
37
-
38
- /** The function name the trigger tick for an integration runs as. Wire contract with function-environments.js. */
39
- function triggerFunctionName(integrationName) {
40
- return `${integrationName}Triggers`;
41
- }
42
-
43
- class TriggerBuilder extends InfrastructureBuilder {
44
- constructor() {
45
- super();
46
- this.name = 'TriggerBuilder';
47
- }
48
-
49
- shouldExecute(appDefinition) {
50
- return Array.isArray(appDefinition.integrations) && appDefinition.integrations.some((i) => hasTriggers(i));
51
- }
52
-
53
- getDependencies() {
54
- return ['IntegrationBuilder']; // the tick sends to the integration queue
55
- }
56
-
57
- validate(appDefinition) {
58
- const result = new ValidationResult();
59
- for (const integration of appDefinition.integrations || []) {
60
- if (!hasTriggers(integration)) continue;
61
- try {
62
- provisioningOf(integration);
63
- } catch (error) {
64
- result.addError(error.message);
65
- }
66
- }
67
- return result;
68
- }
69
-
70
- async build(appDefinition) {
71
- console.log(`\n[${this.name}] Configuring recurring triggers...`);
72
- const result = { functions: {}, resources: {}, environment: {}, custom: {}, iamStatements: [] };
73
- const usePrismaLayer = appDefinition.usePrismaLambdaLayer !== false;
74
- const functionPackageConfig = new IntegrationBuilder().createFunctionPackageConfig(usePrismaLayer, appDefinition);
75
-
76
- for (const integration of appDefinition.integrations || []) {
77
- if (!hasTriggers(integration)) continue;
78
- const name = integration.Definition.name;
79
- const { ticks, at } = provisioningOf(integration);
80
- const events = [
81
- ...ticks.map((minutes) => ({
82
- schedule: {
83
- rate: [rateExpression(minutes)],
84
- // The rule's own firing time goes in, so a repeated delivery falls in the same tick slot.
85
- inputTransformer: {
86
- inputPathsMap: { time: '$.time' },
87
- inputTemplate: `{"tick":"${durationOf(minutes)}","time":<time>}`,
88
- },
89
- },
90
- })),
91
- ...at.map((t) => ({
92
- schedule: {
93
- method: 'scheduler',
94
- rate: [t.at],
95
- ...(t.timezone ? { timezone: t.timezone } : {}),
96
- input: { at: t.name, time: '<aws.scheduler.scheduled-time>' },
97
- },
98
- })),
99
- ];
100
- result.functions[triggerFunctionName(name)] = {
101
- handler: `node_modules/@friggframework/core/handlers/workers/integration-triggers.handlers.${name}.tick`,
102
- skipEsbuild: true, // Nested exports in node_modules - skip esbuild bundling
103
- package: functionPackageConfig,
104
- ...(usePrismaLayer && { layers: [{ Ref: 'PrismaLambdaLayer' }] }), // reads the integration table
105
- timeout: 300, // a tick past its deadline hands its page cursor to the queue
106
- events,
107
- };
108
- console.log(` ✓ ${triggerFunctionName(name)}: ticks ${ticks.map(durationOf).join(', ') || 'none'}; at ${at.map((t) => t.name).join(', ') || 'none'}`);
109
- }
110
- return result;
111
- }
112
- }
113
-
114
- module.exports = { TriggerBuilder, rateExpression, triggerFunctionName };
@@ -1,82 +0,0 @@
1
- /**
2
- * TriggerBuilder (ADR-055 §2): one tick function per integration with triggers, one schedule per distinct tick and
3
- * one per `at` trigger, never anything per installation.
4
- */
5
- const { TriggerBuilder, rateExpression } = require('./trigger-builder');
6
- const { applyFunctionEnvironments } = require('../shared/function-environments');
7
-
8
- const poll = { every: '15m', handler: 'poll' };
9
-
10
- describe('TriggerBuilder', () => {
11
- beforeEach(() => { jest.spyOn(console, 'log').mockImplementation(() => {}); });
12
- afterEach(() => { jest.restoreAllMocks(); });
13
-
14
- it('runs when, and only when, an integration declares triggers (code or per installation)', () => {
15
- const b = new TriggerBuilder();
16
- expect(b.shouldExecute({ integrations: [{ Definition: { name: 'a', triggers: { poll } } }] })).toBe(true);
17
- expect(b.shouldExecute({ integrations: [{ Definition: { name: 'dd', instanceTriggers: { tick: '5m' } } }] })).toBe(true);
18
- expect(b.shouldExecute({ integrations: [{ Definition: { name: 'a', webhooks: true } }] })).toBe(false);
19
- expect(b.shouldExecute({ integrations: [{ Definition: { name: 'a', triggers: {} } }] })).toBe(false);
20
- expect(b.shouldExecute({})).toBe(false);
21
- expect(b.getDependencies()).toEqual(['IntegrationBuilder']);
22
- });
23
-
24
- it('writes rate() in the largest whole unit EventBridge accepts', () => {
25
- expect([1, 5, 60, 90, 120, 1440].map(rateExpression)).toEqual(['rate(1 minute)', 'rate(5 minutes)', 'rate(1 hour)', 'rate(90 minutes)', 'rate(2 hours)', 'rate(1 day)']);
26
- });
27
-
28
- it('emits one function per integration: a schedule per distinct tick and one per at trigger, with its zone', async () => {
29
- const appDefinition = {
30
- integrations: [
31
- { Definition: { name: 'crm', triggers: {
32
- poll,
33
- sync: { every: '1h', configurable: { min: '15m' }, handler: 'sync' }, // 15m tick: same schedule as poll
34
- digest: { cron: '0 8 * * 1-5', timezone: 'America/New_York', handler: 'digest' }, // 5m
35
- nightly: { at: 'cron(0 3 * * ? *)', timezone: 'Europe/London', handler: 'nightly' },
36
- } } },
37
- { Definition: { name: 'plain' } },
38
- ],
39
- };
40
- const result = await new TriggerBuilder().build(appDefinition, {});
41
- expect(Object.keys(result.functions)).toEqual(['crmTriggers']);
42
- const fn = result.functions.crmTriggers;
43
- expect(fn).toMatchObject({
44
- handler: 'node_modules/@friggframework/core/handlers/workers/integration-triggers.handlers.crm.tick',
45
- skipEsbuild: true,
46
- layers: [{ Ref: 'PrismaLambdaLayer' }],
47
- timeout: 300,
48
- });
49
- expect(fn.events).toEqual([
50
- { schedule: { rate: ['rate(5 minutes)'], inputTransformer: { inputPathsMap: { time: '$.time' }, inputTemplate: '{"tick":"5m","time":<time>}' } } },
51
- { schedule: { rate: ['rate(15 minutes)'], inputTransformer: { inputPathsMap: { time: '$.time' }, inputTemplate: '{"tick":"15m","time":<time>}' } } },
52
- { schedule: { method: 'scheduler', rate: ['cron(0 3 * * ? *)'], timezone: 'Europe/London', input: { at: 'nightly', time: '<aws.scheduler.scheduled-time>' } } },
53
- ]);
54
- // The tick never calls EventBridge Scheduler at runtime: no scheduler IAM, no resources.
55
- expect(result.iamStatements).toEqual([]);
56
- expect(result.resources).toEqual({});
57
- // The inputTemplate is valid JSON once EventBridge fills <time>.
58
- expect(JSON.parse(fn.events[0].schedule.inputTransformer.inputTemplate.replace('<time>', '"2026-10-19T12:00:00Z"'))).toEqual({ tick: '5m', time: '2026-10-19T12:00:00Z' });
59
- });
60
-
61
- it('leaves the Prisma layer off when the app bundles Prisma', async () => {
62
- const result = await new TriggerBuilder().build({ usePrismaLambdaLayer: false, integrations: [{ Definition: { name: 'crm', triggers: { poll } } }] }, {});
63
- expect(result.functions.crmTriggers.layers).toBeUndefined();
64
- });
65
-
66
- it('fails validation, naming the integration, when a trigger cannot be provisioned', () => {
67
- const v = new TriggerBuilder().validate({ integrations: [{ Definition: { name: 'crm', triggers: { bad: { every: 'often', handler: 'x' } } } }] });
68
- expect(v.valid).toBe(false);
69
- expect(v.errors[0]).toMatch(/Integration "crm" declares invalid triggers: bad: every "often"/);
70
- });
71
-
72
- it('scoped env: the queue URL reaches the tick function, through the shared function-name contract', async () => {
73
- const { IntegrationBuilder } = require('../integration/integration-builder');
74
- const integration = { Definition: { name: 'crm', triggers: { poll } } };
75
- const ib = new IntegrationBuilder();
76
- const result = { functionEnvironments: {}, environment: {} };
77
- ib.setQueueUrlEnvironment('crm', { Ref: 'CrmQueue' }, result, { lambda: { scopedEnvironment: true }, integrations: [integration] });
78
- const functions = { auth: {}, crm: {}, crmQueueWorker: {}, ...(await new TriggerBuilder().build({ integrations: [integration] }, {})).functions };
79
- applyFunctionEnvironments(functions, result.functionEnvironments);
80
- expect(functions.crmTriggers.environment).toEqual({ CRM_QUEUE_URL: { Ref: 'CrmQueue' } });
81
- });
82
- });