@friggframework/devtools 2.0.0--canary.703.12b980b.0 → 2.0.0--canary.707.2702ff3.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
@@ -0,0 +1,168 @@
1
+ /**
2
+ * The build step that composes core extension schemas into the backend's
3
+ * installed @friggframework/core. Uses a temp backend whose node_modules holds
4
+ * a core with the real composer and a minimal PostgreSQL schema.
5
+ */
6
+ const fs = require('fs');
7
+ const os = require('os');
8
+ const path = require('path');
9
+ const { composeAppExtensionPrisma } = require('../compose-extension-prisma');
10
+ const { buildWithProvider } = require('../provider-build');
11
+
12
+ const REAL_CORE = path.dirname(
13
+ require.resolve('@friggframework/core/package.json')
14
+ );
15
+
16
+ const BASE = `datasource db {
17
+ provider = "postgresql"
18
+ url = env("DATABASE_URL")
19
+ }
20
+
21
+ model User {
22
+ id Int @id
23
+ }
24
+ `;
25
+
26
+ function makeBackend({ withCore = true } = {}) {
27
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-compose-ext-'));
28
+ const backend = path.join(dir, 'backend');
29
+ fs.mkdirSync(backend);
30
+ fs.writeFileSync(path.join(backend, 'package.json'), '{"name":"backend"}');
31
+ const extSchema = path.join(dir, 'ext.prisma');
32
+ fs.writeFileSync(
33
+ extSchema,
34
+ 'model OAuthAppCredential {\n id Int @id\n}\n'
35
+ );
36
+ let core = null;
37
+ if (withCore) {
38
+ core = path.join(backend, 'node_modules', '@friggframework', 'core');
39
+ fs.mkdirSync(path.join(core, 'prisma-postgresql'), { recursive: true });
40
+ fs.writeFileSync(
41
+ path.join(core, 'package.json'),
42
+ '{"name":"@friggframework/core"}'
43
+ );
44
+ fs.writeFileSync(
45
+ path.join(core, 'prisma-postgresql', 'schema.prisma'),
46
+ BASE
47
+ );
48
+ fs.symlinkSync(
49
+ path.join(REAL_CORE, 'extensions'),
50
+ path.join(core, 'extensions'),
51
+ 'dir'
52
+ );
53
+ fs.symlinkSync(
54
+ path.join(REAL_CORE, 'management-api'),
55
+ path.join(core, 'management-api'),
56
+ 'dir'
57
+ );
58
+ }
59
+ return { dir, backend, core, extSchema };
60
+ }
61
+
62
+ const appDefinition = (extSchema) => ({
63
+ name: 'compose-app',
64
+ provider: 'netlify',
65
+ integrations: [],
66
+ database: { postgres: { enable: true } },
67
+ coreExtensions: [{ name: 'db-credentials', schema: extSchema }],
68
+ });
69
+
70
+ describe('composeAppExtensionPrisma', () => {
71
+ const dirs = [];
72
+ afterAll(() =>
73
+ dirs.forEach((d) => fs.rmSync(d, { recursive: true, force: true }))
74
+ );
75
+
76
+ it("composes into the backend's installed core, not devtools' copy", () => {
77
+ const { dir, backend, core, extSchema } = makeBackend();
78
+ dirs.push(dir);
79
+ const generated = [];
80
+ const result = composeAppExtensionPrisma({
81
+ appDefinition: appDefinition(extSchema),
82
+ backendDir: backend,
83
+ generate: ({ corePath }) => generated.push(corePath),
84
+ log: () => {},
85
+ });
86
+ expect(result.changed).toBe(true);
87
+ expect(generated).toEqual([core]);
88
+ expect(
89
+ fs.readFileSync(
90
+ path.join(core, 'prisma-postgresql', 'schema.prisma'),
91
+ 'utf-8'
92
+ )
93
+ ).toContain('model OAuthAppCredential');
94
+ });
95
+
96
+ it('is a no-op without an installed core when no extension declares a schema', () => {
97
+ const { dir, backend } = makeBackend({ withCore: false });
98
+ dirs.push(dir);
99
+ expect(
100
+ composeAppExtensionPrisma({
101
+ appDefinition: { coreExtensions: [{ name: 'x' }] },
102
+ backendDir: backend,
103
+ })
104
+ ).toEqual({ changed: false, results: [] });
105
+ });
106
+
107
+ it('refuses to build without an installed core when an extension declares a schema', () => {
108
+ const { dir, backend, extSchema } = makeBackend({ withCore: false });
109
+ dirs.push(dir);
110
+ expect(() =>
111
+ composeAppExtensionPrisma({
112
+ appDefinition: appDefinition(extSchema),
113
+ backendDir: backend,
114
+ })
115
+ ).toThrow(
116
+ /declare Prisma schemas, but @friggframework\/core is not installed/
117
+ );
118
+ });
119
+ });
120
+
121
+ describe('buildWithProvider composes extension schemas', () => {
122
+ const plugin = {
123
+ validate: () => ({ errors: [], warnings: [] }),
124
+ generateConfig: () => '# config',
125
+ };
126
+
127
+ it('composes before writing the provider files', () => {
128
+ const { dir, backend } = makeBackend({ withCore: false });
129
+ try {
130
+ const order = [];
131
+ const def = { provider: 'netlify', integrations: [] };
132
+ buildWithProvider({
133
+ appDefinition: def,
134
+ backendDir: backend,
135
+ provider: {
136
+ ...plugin,
137
+ generateConfig: () => (order.push('config'), '# config'),
138
+ },
139
+ composePrisma: (args) =>
140
+ order.push([
141
+ 'compose',
142
+ args.appDefinition,
143
+ args.backendDir,
144
+ ]),
145
+ });
146
+ expect(order).toEqual([['compose', def, backend], 'config']);
147
+ } finally {
148
+ fs.rmSync(dir, { recursive: true, force: true });
149
+ }
150
+ });
151
+
152
+ it('does not compose when validation fails', () => {
153
+ const { dir, backend } = makeBackend({ withCore: false });
154
+ try {
155
+ const compose = jest.fn();
156
+ buildWithProvider({
157
+ appDefinition: { provider: 'netlify' },
158
+ backendDir: backend,
159
+ provider: { validate: () => ({ errors: ['bad'] }) },
160
+ composePrisma: compose,
161
+ exit: () => {},
162
+ });
163
+ expect(compose).not.toHaveBeenCalled();
164
+ } finally {
165
+ fs.rmSync(dir, { recursive: true, force: true });
166
+ }
167
+ });
168
+ });
@@ -0,0 +1,64 @@
1
+ /**
2
+ * `node infrastructure.js package` (what a backend's `npm run build` runs)
3
+ * for an app with provider 'netlify': createFriggInfrastructure() builds
4
+ * through provider-netlify and returns an empty serverless definition
5
+ * instead of composing CloudFormation (friggframework/frigg#545, 302ab9ba).
6
+ */
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+
11
+ jest.mock('../infrastructure-composer', () => ({
12
+ composeServerlessDefinition: jest.fn(async () => ({ service: 'aws-app' })),
13
+ }));
14
+ jest.mock('@friggframework/core', () => ({
15
+ findNearestBackendPackageJson: jest.fn(),
16
+ }));
17
+
18
+ const { composeServerlessDefinition } = require('../infrastructure-composer');
19
+ const { findNearestBackendPackageJson } = require('@friggframework/core');
20
+ const { createFriggInfrastructure } = require('../create-frigg-infrastructure');
21
+
22
+ function writeProject(definitionSource) {
23
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-infra-'));
24
+ const backend = path.join(dir, 'backend');
25
+ fs.mkdirSync(backend);
26
+ fs.writeFileSync(path.join(backend, 'package.json'), '{"name":"backend"}');
27
+ fs.writeFileSync(path.join(backend, 'index.js'), `module.exports = { Definition: ${definitionSource} };`);
28
+ findNearestBackendPackageJson.mockReturnValue(path.join(backend, 'package.json'));
29
+ return dir;
30
+ }
31
+
32
+ describe('createFriggInfrastructure with a non-AWS provider', () => {
33
+ beforeEach(() => {
34
+ jest.clearAllMocks();
35
+ jest.spyOn(console, 'log').mockImplementation();
36
+ jest.spyOn(console, 'warn').mockImplementation();
37
+ });
38
+ afterEach(() => jest.restoreAllMocks());
39
+
40
+ it('generates the Netlify project and composes no serverless definition', async () => {
41
+ const dir = writeProject(`{
42
+ provider: 'netlify', integrations: [], database: { postgres: { enable: true } }
43
+ }`);
44
+ try {
45
+ await expect(createFriggInfrastructure()).resolves.toEqual({});
46
+ expect(composeServerlessDefinition).not.toHaveBeenCalled();
47
+ expect(fs.existsSync(path.join(dir, 'netlify.toml'))).toBe(true);
48
+ expect(fs.existsSync(path.join(dir, 'netlify/functions/auth.js'))).toBe(true);
49
+ expect(fs.existsSync(path.join(dir, 'netlify/lib/create-netlify-app-handler.js'))).toBe(true);
50
+ } finally {
51
+ fs.rmSync(dir, { recursive: true, force: true });
52
+ }
53
+ });
54
+
55
+ it('keeps composing the serverless definition for AWS', async () => {
56
+ const dir = writeProject(`{ provider: 'aws', integrations: [] }`);
57
+ try {
58
+ await expect(createFriggInfrastructure()).resolves.toEqual({ service: 'aws-app' });
59
+ expect(fs.existsSync(path.join(dir, 'netlify.toml'))).toBe(false);
60
+ } finally {
61
+ fs.rmSync(dir, { recursive: true, force: true });
62
+ }
63
+ });
64
+ });
@@ -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
+ });
@@ -5,6 +5,13 @@
5
5
  * valid, consistent CloudFormation templates.
6
6
  */
7
7
 
8
+ // Composing must not build the real Prisma layer: that runs npm install
9
+ // under packages/devtools, and two workers doing it at once once pruned the
10
+ // repository's root node_modules (test/npm-install-guard.js).
11
+ jest.mock('../domains/shared/utilities/prisma-layer-manager', () => ({
12
+ ensurePrismaLayerExists: jest.fn(async () => {}),
13
+ }));
14
+
8
15
  const { composeServerlessDefinition } = require('../infrastructure-composer');
9
16
 
10
17
  describe('CloudFormation Template Generation', () => {
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Build-time step: put the app's core extension models (and PostgreSQL
3
+ * migrations) into the Prisma client of the @friggframework/core the backend
4
+ * installed. See core's extensions/prisma-composer.js.
5
+ *
6
+ * It must run on the backend's own core, not devtools' copy: that is the
7
+ * package the functions bundle and the Lambda layer copy their client from.
8
+ */
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+
12
+ /**
13
+ * Directory of the @friggframework/core the backend resolves.
14
+ * @param {string} backendDir
15
+ */
16
+ function resolveBackendCorePath(backendDir) {
17
+ return path.dirname(
18
+ require.resolve('@friggframework/core/package.json', {
19
+ paths: [backendDir],
20
+ })
21
+ );
22
+ }
23
+
24
+ /**
25
+ * @param {Object} params
26
+ * @param {Object} params.appDefinition
27
+ * @param {string} params.backendDir - directory holding the backend's package.json
28
+ * @param {Function} [params.generate] - injected prisma generate (tests)
29
+ * @param {Function} [params.log]
30
+ * @returns {{ changed: boolean, results: Array<Object> }}
31
+ */
32
+ function composeAppExtensionPrisma({
33
+ appDefinition,
34
+ backendDir,
35
+ generate,
36
+ log,
37
+ }) {
38
+ const declares = (appDefinition?.coreExtensions || []).some(
39
+ (ext) => ext && (ext.schema || ext.migrations)
40
+ );
41
+ let corePath;
42
+ try {
43
+ corePath = resolveBackendCorePath(backendDir);
44
+ } catch (error) {
45
+ // No installed core to compose into. Fine when nothing needs composing.
46
+ if (!declares) return { changed: false, results: [] };
47
+ throw new Error(
48
+ `Core extensions declare Prisma schemas, but @friggframework/core is not installed for ${backendDir}`,
49
+ { cause: error }
50
+ );
51
+ }
52
+ const composerPath = path.join(
53
+ corePath,
54
+ 'extensions',
55
+ 'prisma-composer.js'
56
+ );
57
+ if (!fs.existsSync(composerPath)) {
58
+ if (!declares) return { changed: false, results: [] };
59
+ throw new Error(
60
+ `@friggframework/core at ${corePath} cannot compose extension schemas; ` +
61
+ 'upgrade it to the version devtools was built with'
62
+ );
63
+ }
64
+ const { composeExtensionPrisma } = require(composerPath);
65
+ return composeExtensionPrisma({
66
+ appDefinition,
67
+ corePath,
68
+ ...(generate ? { generate } : {}),
69
+ ...(log ? { log } : {}),
70
+ });
71
+ }
72
+
73
+ module.exports = { composeAppExtensionPrisma, resolveBackendCorePath };
@@ -35,6 +35,20 @@ async function createFriggInfrastructure() {
35
35
  throw new Error('Could not find index.js');
36
36
  }
37
37
 
38
+ // A non-AWS provider (appDefinition.provider, e.g. 'netlify') builds
39
+ // through its provider plugin instead of serverless/CloudFormation
40
+ // (friggframework/frigg#545). Checked before the cache: the cache holds
41
+ // serverless definitions only. Returns an empty serverless definition,
42
+ // so an osls invocation has nothing to package.
43
+ {
44
+ const { isNonAwsProvider, buildWithProvider } = require('./provider-build');
45
+ const appDefinition = require(backendFilePath).Definition;
46
+ if (isNonAwsProvider(appDefinition)) {
47
+ buildWithProvider({ appDefinition, backendDir });
48
+ return {};
49
+ }
50
+ }
51
+
38
52
  const cachePath = getCachePath(backendDir);
39
53
  const lockPath = getLockPath(backendDir);
40
54