@friggframework/devtools 2.0.0--canary.686.588657b.0 → 2.0.0--canary.680.6bacd26.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.
@@ -1,22 +1,7 @@
1
1
  const { spawnSync } = require('child_process');
2
2
  const path = require('path');
3
3
 
4
- async function buildCommand(options = {}) {
5
- // A non-AWS provider (appDefinition.provider) builds through its plugin:
6
- // platform config + function entry points, no serverless package
7
- // (friggframework/frigg#545).
8
- const providerResult = loadProviderIfConfigured();
9
- if (providerResult) {
10
- const { buildWithProvider } = require('../../infrastructure/provider-build');
11
- buildWithProvider({
12
- appDefinition: providerResult.appDefinition,
13
- backendDir: providerResult.backendDir,
14
- provider: providerResult.provider,
15
- verbose: options.verbose,
16
- });
17
- return;
18
- }
19
-
4
+ async function buildCommand(options) {
20
5
  console.log('Building the serverless application...');
21
6
 
22
7
  // Suppress AWS SDK warning message about maintenance mode
@@ -78,20 +63,4 @@ async function buildCommand(options = {}) {
78
63
  // });
79
64
  }
80
65
 
81
- /**
82
- * The resolved non-AWS provider, or null for AWS / no app definition found.
83
- */
84
- function loadProviderIfConfigured() {
85
- const { loadProviderForCli } = require('../utils/provider-helper');
86
- let result;
87
- try {
88
- result = loadProviderForCli();
89
- } catch (error) {
90
- // A non-AWS provider whose package is missing: say so, don't build for AWS.
91
- console.error(error.message);
92
- process.exit(1);
93
- }
94
- return result && result.provider ? result : null;
95
- }
96
-
97
66
  module.exports = { buildCommand };
@@ -310,16 +310,9 @@ async function pushOffloadedParametersOrAbort(appDefinition, options) {
310
310
  }
311
311
 
312
312
  async function deployCommand(options) {
313
- const appDefinition = loadAppDefinition();
314
-
315
- // A non-AWS provider (appDefinition.provider) deploys through its plugin
316
- // (friggframework/frigg#545).
317
- const providerName = appDefinition?.provider;
318
- if (providerName && providerName !== 'aws') {
319
- return deployWithProvider(appDefinition, providerName, options);
320
- }
321
-
322
313
  console.log('Deploying the serverless application...');
314
+
315
+ const appDefinition = loadAppDefinition();
323
316
  const environment = validateAndBuildEnvironment(appDefinition, options);
324
317
 
325
318
  await pushOffloadedParametersOrAbort(appDefinition, options);
@@ -353,45 +346,4 @@ async function deployCommand(options) {
353
346
  }
354
347
  }
355
348
 
356
- /**
357
- * Deploy with a provider plugin: validate(), then deploy() (which runs its
358
- * own preflightCheck()).
359
- */
360
- async function deployWithProvider(appDefinition, providerName, options = {}) {
361
- let provider;
362
- try {
363
- const { resolveProvider } = require('@friggframework/core/providers/resolve-provider');
364
- provider = resolveProvider(appDefinition);
365
- } catch (error) {
366
- console.error(`Failed to load provider '${providerName}': ${error.message}`);
367
- process.exit(1);
368
- }
369
-
370
- console.log(`Deploying with ${providerName} provider...`);
371
-
372
- if (typeof provider.validate === 'function') {
373
- const validation = provider.validate(appDefinition);
374
- if (validation.errors?.length > 0) {
375
- console.error(`\nValidation errors for ${providerName}:`);
376
- for (const error of validation.errors) console.error(` - ${error}`);
377
- process.exit(1);
378
- }
379
- for (const warning of validation.warnings || []) console.warn(` Warning: ${warning}`);
380
- }
381
-
382
- try {
383
- const result = await provider.deploy(appDefinition, {
384
- stage: options.stage,
385
- prod: options.stage === 'production' || options.stage === 'prod',
386
- dryRun: options.dryRun || false,
387
- });
388
- console.log('\nDeployment completed successfully.');
389
- if (result?.url) console.log(` URL: ${result.url}`);
390
- } catch (error) {
391
- console.error(`\nDeployment failed: ${error.message}`);
392
- for (const item of error.missing || []) console.error(` - ${item}`);
393
- process.exit(1);
394
- }
395
- }
396
-
397
349
  module.exports = { deployCommand };
@@ -246,13 +246,6 @@ async function promptForStackSelection(region) {
246
246
  */
247
247
  async function doctorCommand(stackName, options = {}) {
248
248
  try {
249
- // AWS-only (CloudFormation); a non-AWS provider has nothing to inspect.
250
- if (require('../utils/provider-helper').isNonAwsProject()) {
251
- output.error('The doctor command is only available for AWS deployments.');
252
- output.log('Your appDefinition uses a non-AWS provider.');
253
- process.exit(1);
254
- }
255
-
256
249
  // Extract options with defaults
257
250
  const region = options.region || process.env.AWS_REGION || 'us-east-1';
258
251
  const format = options.format || 'console';
@@ -9,13 +9,6 @@ const { generateIAMCloudFormation, getFeatureSummary } = require('../infrastruct
9
9
  */
10
10
  async function generateIamCommand(options = {}) {
11
11
  try {
12
- // AWS-only (CloudFormation); a non-AWS provider has nothing to inspect.
13
- if (require('./utils/provider-helper').isNonAwsProject()) {
14
- console.error('The generate-iam command is only available for AWS deployments.');
15
- console.log('Your appDefinition uses a non-AWS provider.');
16
- process.exit(1);
17
- }
18
-
19
12
  console.log('🔍 Finding Frigg application...');
20
13
 
21
14
  // Find the backend package.json
@@ -453,13 +453,6 @@ async function handleReconcileRepair(stackIdentifier, report, options) {
453
453
  */
454
454
  async function repairCommand(stackName, options = {}) {
455
455
  try {
456
- // AWS-only (CloudFormation); a non-AWS provider has nothing to inspect.
457
- if (require('../utils/provider-helper').isNonAwsProject()) {
458
- output.error('The repair command is only available for AWS deployments.');
459
- output.log('Your appDefinition uses a non-AWS provider.');
460
- process.exit(1);
461
- }
462
-
463
456
  // Validate required parameter
464
457
  if (!stackName) {
465
458
  console.error('Error: Stack name is required');
@@ -37,12 +37,6 @@ async function startCommand(options) {
37
37
  console.log(chalk.green('✓ Database checks passed\n'));
38
38
  console.log('Starting backend and optional frontend...');
39
39
 
40
- // A non-AWS provider runs its own local dev server (friggframework/frigg#545).
41
- const providerResult = loadNonAwsProvider();
42
- if (providerResult) {
43
- return startWithProvider(providerResult, options);
44
- }
45
-
46
40
  // Suppress AWS SDK warning message about maintenance mode
47
41
  process.env.AWS_SDK_JS_SUPPRESS_MAINTENANCE_MODE_MESSAGE = '1';
48
42
  // Skip AWS discovery for local development
@@ -152,56 +146,4 @@ async function performDatabaseChecks(verbose) {
152
146
  // connection when it starts.
153
147
  }
154
148
 
155
- function loadNonAwsProvider() {
156
- try {
157
- const { loadProviderForCli } = require('../utils/provider-helper');
158
- const result = loadProviderForCli();
159
- return result && result.provider ? result : null;
160
- } catch {
161
- return null;
162
- }
163
- }
164
-
165
- /**
166
- * Local dev server per provider: Netlify -> `netlify dev` (reads netlify.toml
167
- * and serves the generated functions), run from the project root that holds
168
- * backend/ and netlify.toml.
169
- */
170
- function startWithProvider({ providerName, backendDir }, options = {}) {
171
- const DEV_COMMANDS = {
172
- netlify: { command: 'netlify', args: ['dev'] },
173
- };
174
- const devCmd = DEV_COMMANDS[providerName];
175
- if (!devCmd) {
176
- console.error(chalk.red(
177
- `Provider '${providerName}' does not have a local dev server configured.\n` +
178
- ` Supported providers for local dev: ${Object.keys(DEV_COMMANDS).join(', ')}, aws`
179
- ));
180
- process.exit(1);
181
- }
182
-
183
- const cwd = require('node:path').dirname(backendDir);
184
- console.log(chalk.blue(`Starting local dev server (${providerName})...`));
185
- if (options.verbose) {
186
- console.log(`Executing command: ${devCmd.command} ${devCmd.args.join(' ')}`);
187
- console.log(`Working directory: ${cwd}`);
188
- }
189
-
190
- const childProcess = spawn(devCmd.command, devCmd.args, {
191
- cwd,
192
- stdio: 'inherit',
193
- env: { ...process.env },
194
- });
195
- childProcess.on('error', (error) => {
196
- if (error.code === 'ENOENT') {
197
- console.error(chalk.red(`'${devCmd.command}' not found. Install it with: npm install -g ${devCmd.command}-cli`));
198
- } else {
199
- console.error(`Error executing command: ${error.message}`);
200
- }
201
- });
202
- childProcess.on('close', (code) => {
203
- if (code !== 0) console.log(`Child process exited with code ${code}`);
204
- });
205
- }
206
-
207
149
  module.exports = { startCommand };
@@ -5,13 +5,6 @@
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
-
15
8
  const { composeServerlessDefinition } = require('../infrastructure-composer');
16
9
 
17
10
  describe('CloudFormation Template Generation', () => {
@@ -35,20 +35,6 @@ 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
-
52
38
  const cachePath = getCachePath(backendDir);
53
39
  const lockPath = getLockPath(backendDir);
54
40
 
@@ -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 - Deployment provider: 'aws' (serverless/Lambda) or 'netlify' (@friggframework/provider-netlify)
132
+ * @property {string} provider - Cloud provider (e.g., 'aws')
133
133
  * @property {string} region - AWS region
134
134
  *
135
135
  * @property {VpcDefinition} [vpc] - VPC configuration
@@ -144,20 +144,6 @@
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()
161
147
  */
162
148
 
163
149
  /**
@@ -15,17 +15,15 @@ const {
15
15
  } = require('@friggframework/core/management-api/route-registry');
16
16
 
17
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).
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.
22
21
  */
23
22
  function managementApiEvents(AppDefinition, functionName) {
24
23
  const managementApi = AppDefinition.managementApi || {};
25
24
  return getGatewayRoutes({
26
25
  v1: managementApi.v1 !== false,
27
26
  proxy: managementApi.proxy?.enable === true,
28
- coreExtensions: AppDefinition.coreExtensions,
29
27
  })
30
28
  .filter((route) => route.function === functionName)
31
29
  .map(({ method, path }) => ({ httpApi: { path, method } }));
@@ -142,33 +142,9 @@ describe('Base Definition Factory', () => {
142
142
  'GET /health/{proxy+}',
143
143
  'GET /api/meta',
144
144
  'GET /api/meta/{proxy+}',
145
- // Redirects to /api/meta/openapi/v2.json (ADR-053 docs path)
146
- 'GET /api/docs',
147
145
  ]);
148
146
  });
149
147
 
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
148
  it('drops the v1 routes when managementApi.v1 is false, keeping the OAuth redirect', () => {
173
149
  const result = createBaseDefinition({ managementApi: { v1: false } }, {}, {});
174
150
  const routes = result.functions.auth.events.map(
@@ -2,13 +2,6 @@ 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
-
12
5
  const {
13
6
  SSM_PRELOAD_NODE_OPTIONS,
14
7
  } = require('./domains/parameters/offload-utils');
@@ -249,36 +249,6 @@ async function createLayerStructure() {
249
249
  logSuccess(`Created ${LAYER_NODE_MODULES}`);
250
250
  }
251
251
 
252
- /**
253
- * Run `npm install --omit=dev` confined to the layer directory.
254
- *
255
- * npm resolves its project root by walking up from cwd to the nearest
256
- * package.json. If the layer's package.json is missing when npm starts (a
257
- * concurrent build cleaned the directory, as two jest workers composing at
258
- * once did), npm walked up into the enclosing workspace and ran
259
- * `install --omit=dev` there, pruning the devDependencies (jest, jest-util)
260
- * out of the repository's root node_modules. So: the package.json must exist,
261
- * and `--prefix` pins npm's root to the layer directory while
262
- * `--workspaces=false` stops it acting on an enclosing workspace.
263
- *
264
- * @param {string} layerNodejsDir - absolute path of <layer>/nodejs
265
- * @param {Object} [options]
266
- * @param {Object} [options.env]
267
- * @param {Function} [options.exec] - execSync stand-in (tests)
268
- */
269
- function runLayerInstall(layerNodejsDir, { env = process.env, exec = execSync } = {}) {
270
- const manifest = path.join(layerNodejsDir, 'package.json');
271
- if (!fs.existsSync(manifest)) {
272
- throw new Error(
273
- `Refusing to run npm install: ${manifest} does not exist (npm would install into an enclosing project)`
274
- );
275
- }
276
- exec(
277
- `npm install --omit=dev --no-package-lock --workspaces=false --prefix ${JSON.stringify(layerNodejsDir)}`,
278
- { cwd: layerNodejsDir, stdio: 'inherit', env }
279
- );
280
- }
281
-
282
252
  /**
283
253
  * Install Prisma client directly into layer (RUNTIME ONLY - NO CLI)
284
254
  *
@@ -315,7 +285,11 @@ async function installPrismaPackages() {
315
285
  PRISMA_CLI_BINARY_TARGETS: 'rhel-openssl-3.0.x',
316
286
  };
317
287
 
318
- runLayerInstall(path.join(LAYER_OUTPUT_PATH, 'nodejs'), { env });
288
+ execSync('npm install --omit=dev --no-package-lock', {
289
+ cwd: path.join(LAYER_OUTPUT_PATH, 'nodejs'),
290
+ stdio: 'inherit',
291
+ env,
292
+ });
319
293
  logSuccess('Prisma packages installed with Lambda binary target');
320
294
  } catch (error) {
321
295
  throw new Error(`Failed to install Prisma packages: ${error.message}`);
@@ -719,7 +693,6 @@ if (require.main === module) {
719
693
 
720
694
  module.exports = {
721
695
  buildPrismaLayer,
722
- runLayerInstall,
723
696
  getGeneratedClientPackages,
724
697
  getMigrationsPackages,
725
698
  getMigrationSourcePath,
@@ -168,38 +168,3 @@ describe('getMigrationDestinationPath()', () => {
168
168
  );
169
169
  });
170
170
  });
171
-
172
-
173
- describe('runLayerInstall', () => {
174
- const fs = require('fs');
175
- const os = require('os');
176
- const path = require('path');
177
- const { runLayerInstall } = require('./build-prisma-layer');
178
-
179
- it('refuses when the layer package.json is missing (npm would walk up into the workspace)', () => {
180
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'layer-'));
181
- const exec = jest.fn();
182
- try {
183
- expect(() => runLayerInstall(dir, { exec })).toThrow(/Refusing to run npm install/);
184
- expect(exec).not.toHaveBeenCalled();
185
- } finally {
186
- fs.rmSync(dir, { recursive: true, force: true });
187
- }
188
- });
189
-
190
- it('pins npm to the layer directory and off any enclosing workspace', () => {
191
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'layer-'));
192
- fs.writeFileSync(path.join(dir, 'package.json'), '{}');
193
- const exec = jest.fn();
194
- try {
195
- runLayerInstall(dir, { exec, env: { X: '1' } });
196
- const [command, options] = exec.mock.calls[0];
197
- expect(command).toContain('npm install --omit=dev');
198
- expect(command).toContain('--workspaces=false');
199
- expect(command).toContain(`--prefix ${JSON.stringify(dir)}`);
200
- expect(options).toMatchObject({ cwd: dir, env: { X: '1' } });
201
- } finally {
202
- fs.rmSync(dir, { recursive: true, force: true });
203
- }
204
- });
205
- });
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.686.588657b.0",
4
+ "version": "2.0.0--canary.680.6bacd26.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.686.588657b.0",
30
- "@friggframework/schemas": "2.0.0--canary.686.588657b.0",
31
- "@friggframework/test": "2.0.0--canary.686.588657b.0",
29
+ "@friggframework/core": "2.0.0--canary.680.6bacd26.0",
30
+ "@friggframework/schemas": "2.0.0--canary.680.6bacd26.0",
31
+ "@friggframework/test": "2.0.0--canary.680.6bacd26.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.686.588657b.0",
60
- "@friggframework/prettier-config": "2.0.0--canary.686.588657b.0",
59
+ "@friggframework/eslint-config": "2.0.0--canary.680.6bacd26.0",
60
+ "@friggframework/prettier-config": "2.0.0--canary.680.6bacd26.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": "588657b8dac3b0f0b52c0af0cc625f47c06bf1ce"
92
+ "gitHead": "6bacd2666932cc417e175260ee2dbf3522740572"
93
93
  }
@@ -1,140 +0,0 @@
1
- /**
2
- * Provider dispatch (friggframework/frigg#545): appDefinition.provider
3
- * decides whether a CLI command runs the AWS/serverless path or the
4
- * provider plugin. Uses real temp projects and the real provider-netlify.
5
- */
6
- const fs = require('fs');
7
- const os = require('os');
8
- const path = require('path');
9
-
10
- function writeProject(definitionSource) {
11
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-dispatch-'));
12
- const backend = path.join(dir, 'backend');
13
- fs.mkdirSync(backend);
14
- fs.writeFileSync(path.join(backend, 'package.json'), '{"name":"backend"}');
15
- fs.writeFileSync(path.join(backend, 'index.js'), `module.exports = { Definition: ${definitionSource} };`);
16
- return { dir, backend };
17
- }
18
-
19
- const NETLIFY_APP = `{
20
- name: 'dispatch-app',
21
- provider: 'netlify',
22
- integrations: [],
23
- database: { postgres: { enable: true } },
24
- }`;
25
-
26
- describe('provider-helper', () => {
27
- const { loadProviderForCli, loadCliAppDefinition, isNonAwsProject } = require('../../../utils/provider-helper');
28
- const dirs = [];
29
- afterAll(() => dirs.forEach((d) => fs.rmSync(d, { recursive: true, force: true })));
30
-
31
- it('returns null without an app definition', () => {
32
- expect(loadProviderForCli({ cwd: os.tmpdir() })).toBeNull();
33
- expect(loadCliAppDefinition('/nonexistent/path')).toBeNull();
34
- expect(isNonAwsProject({ cwd: os.tmpdir() })).toBe(false);
35
- });
36
-
37
- it('treats a missing provider as aws with no plugin', () => {
38
- const { dir, backend } = writeProject(`{ integrations: [] }`);
39
- dirs.push(dir);
40
- expect(loadProviderForCli({ cwd: backend })).toEqual(
41
- expect.objectContaining({ providerName: 'aws', provider: null, backendDir: backend })
42
- );
43
- expect(isNonAwsProject({ cwd: backend })).toBe(false);
44
- });
45
-
46
- it('resolves the netlify plugin from the project root or from backend/', () => {
47
- const { dir, backend } = writeProject(NETLIFY_APP);
48
- dirs.push(dir);
49
- for (const cwd of [dir, backend]) {
50
- const result = loadProviderForCli({ cwd });
51
- expect(result.providerName).toBe('netlify');
52
- expect(result.provider.name).toBe('netlify');
53
- expect(result.backendDir).toBe(backend);
54
- }
55
- expect(isNonAwsProject({ cwd: backend })).toBe(true);
56
- });
57
- });
58
-
59
- describe('buildWithProvider', () => {
60
- const { buildWithProvider } = require('../../../../infrastructure/provider-build');
61
-
62
- beforeEach(() => {
63
- jest.spyOn(console, 'log').mockImplementation();
64
- jest.spyOn(console, 'warn').mockImplementation();
65
- jest.spyOn(console, 'error').mockImplementation();
66
- });
67
- afterEach(() => jest.restoreAllMocks());
68
-
69
- it('writes netlify.toml, functions and lib shims beside backend/, where their requires resolve', () => {
70
- const { dir, backend } = writeProject(NETLIFY_APP);
71
- try {
72
- const appDefinition = require(path.join(backend, 'index.js')).Definition;
73
- const { projectDir } = buildWithProvider({ appDefinition, backendDir: backend });
74
-
75
- expect(projectDir).toBe(dir);
76
- expect(fs.existsSync(path.join(dir, 'netlify.toml'))).toBe(true);
77
- const auth = fs.readFileSync(path.join(dir, 'netlify/functions/auth.js'), 'utf8');
78
- expect(auth).toContain("require('../../backend/index.js')");
79
- expect(fs.existsSync(path.join(dir, 'netlify/lib/create-netlify-app-handler.js'))).toBe(true);
80
- // Nothing is written into the backend directory itself.
81
- expect(fs.existsSync(path.join(backend, 'netlify'))).toBe(false);
82
- } finally {
83
- fs.rmSync(dir, { recursive: true, force: true });
84
- }
85
- });
86
-
87
- it('stops on validation errors and writes nothing', () => {
88
- const exit = jest.fn();
89
- const { dir, backend } = writeProject(`{ provider: 'netlify', integrations: [] }`);
90
- try {
91
- const appDefinition = require(path.join(backend, 'index.js')).Definition;
92
- const { written } = buildWithProvider({ appDefinition, backendDir: backend, exit });
93
- expect(exit).toHaveBeenCalledWith(1);
94
- expect(written).toEqual([]);
95
- expect(fs.existsSync(path.join(dir, 'netlify.toml'))).toBe(false);
96
- } finally {
97
- fs.rmSync(dir, { recursive: true, force: true });
98
- }
99
- });
100
- });
101
-
102
- describe('frigg build dispatch', () => {
103
- beforeEach(() => {
104
- jest.resetModules();
105
- jest.spyOn(console, 'log').mockImplementation();
106
- jest.spyOn(console, 'warn').mockImplementation();
107
- });
108
- afterEach(() => {
109
- jest.restoreAllMocks();
110
- jest.dontMock('child_process');
111
- });
112
-
113
- it('builds a netlify app through the plugin, never through osls', async () => {
114
- const spawnSync = jest.fn(() => ({ status: 0 }));
115
- jest.doMock('child_process', () => ({ ...jest.requireActual('child_process'), spawnSync }));
116
- const { dir, backend } = writeProject(NETLIFY_APP);
117
- try {
118
- jest.spyOn(process, 'cwd').mockReturnValue(backend);
119
- await require('../../../build-command').buildCommand({});
120
- expect(spawnSync).not.toHaveBeenCalled();
121
- expect(fs.existsSync(path.join(dir, 'netlify/functions/worker-background.js'))).toBe(true);
122
- } finally {
123
- fs.rmSync(dir, { recursive: true, force: true });
124
- }
125
- });
126
-
127
- it('keeps the serverless path for an aws app', async () => {
128
- const spawnSync = jest.fn(() => ({ status: 0 }));
129
- jest.doMock('child_process', () => ({ ...jest.requireActual('child_process'), spawnSync }));
130
- const { dir, backend } = writeProject(`{ integrations: [] }`);
131
- try {
132
- jest.spyOn(process, 'cwd').mockReturnValue(backend);
133
- await require('../../../build-command').buildCommand({});
134
- expect(spawnSync).toHaveBeenCalledWith('osls', expect.any(Array), expect.any(Object));
135
- expect(fs.existsSync(path.join(dir, 'netlify'))).toBe(false);
136
- } finally {
137
- fs.rmSync(dir, { recursive: true, force: true });
138
- }
139
- });
140
- });
@@ -1,80 +0,0 @@
1
- /**
2
- * CLI Provider Helper (friggframework/frigg#545, 88cf983e / c8705715)
3
- *
4
- * Loads the app definition from the user's project and resolves its
5
- * provider plugin, so CLI commands can delegate to it (Netlify, ...) or fall
6
- * through to the AWS/serverless behaviour.
7
- */
8
- const path = require('path');
9
- const fs = require('fs');
10
-
11
- /**
12
- * Find the backend: <cwd>/backend/index.js, then <cwd>/index.js.
13
- * @param {string} cwd
14
- * @returns {{ appDefinition: Object, backendDir: string } | null}
15
- */
16
- function loadCliBackend(cwd) {
17
- for (const dir of [path.join(cwd, 'backend'), cwd]) {
18
- const indexPath = path.join(dir, 'index.js');
19
- if (!fs.existsSync(indexPath)) continue;
20
- try {
21
- const exported = require(indexPath);
22
- if (exported && exported.Definition) {
23
- return { appDefinition: exported.Definition, backendDir: dir };
24
- }
25
- } catch {
26
- // Failed to load, try next
27
- }
28
- }
29
- return null;
30
- }
31
-
32
- /**
33
- * @param {string} cwd
34
- * @returns {Object|null} the app Definition
35
- */
36
- function loadCliAppDefinition(cwd) {
37
- return loadCliBackend(cwd)?.appDefinition || null;
38
- }
39
-
40
- /**
41
- * Load the app definition and resolve the provider plugin for CLI commands.
42
- *
43
- * @param {Object} [options]
44
- * @param {string} [options.cwd] - Working directory (default: process.cwd())
45
- * @returns {{ appDefinition: Object, backendDir: string, provider: Object|null, providerName: string } | null}
46
- * null when no app definition is found; provider null for 'aws' (the
47
- * caller keeps its existing behaviour).
48
- */
49
- function loadProviderForCli(options = {}) {
50
- const cwd = options.cwd || process.cwd();
51
- const backend = loadCliBackend(cwd);
52
- if (!backend) {
53
- return null;
54
- }
55
-
56
- const providerName = backend.appDefinition.provider || 'aws';
57
- if (providerName === 'aws') {
58
- return { ...backend, provider: null, providerName: 'aws' };
59
- }
60
-
61
- const {
62
- resolveProvider,
63
- } = require('@friggframework/core/providers/resolve-provider');
64
- return { ...backend, provider: resolveProvider(backend.appDefinition), providerName };
65
- }
66
-
67
- /**
68
- * True when the project's app definition names a non-AWS provider. Used to
69
- * guard the AWS-only commands (doctor, repair, generate-iam).
70
- */
71
- function isNonAwsProject(options = {}) {
72
- try {
73
- const result = loadProviderForCli(options);
74
- return Boolean(result && result.providerName !== 'aws');
75
- } catch {
76
- return false;
77
- }
78
- }
79
-
80
- module.exports = { loadProviderForCli, loadCliAppDefinition, loadCliBackend, isNonAwsProject };
@@ -1,64 +0,0 @@
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
- });
@@ -1,119 +0,0 @@
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:
7
- * 1. validate(appDefinition) - errors abort, warnings print
8
- * 2. generateConfig(appDefinition) - e.g. netlify.toml
9
- * 3. getFunctionEntryPoints(appDefinition) - written to <project>/netlify/functions
10
- * 4. getLibEntryPoints(appDefinition) - written to <project>/netlify/lib
11
- *
12
- * <project> is the directory that holds backend/: the generated entry points
13
- * require '../../backend/...', so they must sit beside it. #545 had two
14
- * copies of this, and the CLI one wrote into the backend directory itself,
15
- * where those relative requires do not resolve.
16
- *
17
- * Shared by createFriggInfrastructure() (`node infrastructure.js package`,
18
- * what a backend's `npm run build` runs) and `frigg build`.
19
- */
20
- const path = require('path');
21
- const fs = require('fs');
22
-
23
- const CONFIG_FILE_NAMES = { netlify: 'netlify.toml' };
24
-
25
- /**
26
- * @param {Object} params
27
- * @param {Object} params.appDefinition
28
- * @param {string} params.backendDir - directory containing the backend's index.js
29
- * @param {Object} [params.provider] - resolved plugin; defaults to resolveProvider(appDefinition)
30
- * @param {boolean} [params.verbose]
31
- * @param {Function} [params.exit] - called with 1 on validation errors (default process.exit)
32
- * @returns {{ projectDir: string, written: string[] }}
33
- */
34
- function buildWithProvider({
35
- appDefinition,
36
- backendDir,
37
- provider,
38
- verbose = false,
39
- exit = (code) => process.exit(code),
40
- }) {
41
- const providerName = appDefinition.provider;
42
- const plugin =
43
- provider ||
44
- require('@friggframework/core/providers/resolve-provider').resolveProvider(
45
- appDefinition
46
- );
47
- const projectDir = path.dirname(path.resolve(backendDir));
48
- const written = [];
49
-
50
- console.log(`Building for ${providerName} provider (skipping AWS infrastructure)...`);
51
-
52
- if (typeof plugin.validate === 'function') {
53
- const validation = plugin.validate(appDefinition);
54
- if (validation.errors?.length > 0) {
55
- console.error(`\nValidation errors for ${providerName}:`);
56
- for (const error of validation.errors) {
57
- console.error(` - ${error}`);
58
- }
59
- exit(1);
60
- return { projectDir, written };
61
- }
62
- for (const warning of validation.warnings || []) {
63
- console.warn(` Warning: ${warning}`);
64
- }
65
- }
66
-
67
- const write = (filePath, content) => {
68
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
69
- fs.writeFileSync(filePath, content, 'utf-8');
70
- written.push(filePath);
71
- if (verbose) console.log(` Written ${path.relative(projectDir, filePath)}`);
72
- };
73
-
74
- if (typeof plugin.generateConfig === 'function') {
75
- const fileName = CONFIG_FILE_NAMES[providerName] || `${providerName}.config`;
76
- write(path.join(projectDir, fileName), plugin.generateConfig(appDefinition));
77
- console.log(` Written ${fileName}`);
78
- }
79
-
80
- if (typeof plugin.getFunctionEntryPoints === 'function') {
81
- const entryPoints = plugin.getFunctionEntryPoints(appDefinition);
82
- for (const [fileName, content] of Object.entries(entryPoints)) {
83
- write(path.join(projectDir, 'netlify', 'functions', fileName), content);
84
- }
85
- console.log(` Generated ${Object.keys(entryPoints).length} function entry points`);
86
- }
87
-
88
- if (typeof plugin.getLibEntryPoints === 'function') {
89
- const libEntryPoints = plugin.getLibEntryPoints(appDefinition);
90
- for (const [fileName, content] of Object.entries(libEntryPoints)) {
91
- write(path.join(projectDir, 'netlify', 'lib', fileName), content);
92
- }
93
- console.log(` Generated ${Object.keys(libEntryPoints).length} lib entry points`);
94
- }
95
-
96
- if (typeof plugin.generateEnvTemplate === 'function') {
97
- const missing = Object.entries(plugin.generateEnvTemplate(appDefinition)).filter(
98
- ([key]) => !process.env[key]
99
- );
100
- if (missing.length > 0) {
101
- console.log('\n Environment variables not set locally (configure them on the platform):');
102
- for (const [key] of missing) console.log(` - ${key}`);
103
- }
104
- }
105
-
106
- console.log(`\nBuild complete for ${providerName}.`);
107
- return { projectDir, written };
108
- }
109
-
110
- /**
111
- * True when the app definition names a provider other than AWS.
112
- * @param {Object} [appDefinition]
113
- */
114
- function isNonAwsProvider(appDefinition) {
115
- const name = appDefinition?.provider;
116
- return Boolean(name) && name !== 'aws';
117
- }
118
-
119
- module.exports = { buildWithProvider, isNonAwsProvider };
@@ -1,104 +0,0 @@
1
- /**
2
- * Jest setup: no test may run a package-manager command that rewrites a
3
- * node_modules tree outside the OS temp directory.
4
- *
5
- * Why: two infrastructure tests composed a serverless definition in parallel,
6
- * each building the real Prisma layer under packages/devtools/layers/prisma.
7
- * One cleaned the layer while the other's `npm install --omit=dev` was
8
- * starting, npm found no package.json in its cwd, walked up into the
9
- * monorepo workspace and pruned the devDependencies (jest, jest-util) out of
10
- * the repository's root node_modules. Every later workspace then failed with
11
- * `jest: not found`.
12
- *
13
- * The guard wraps the real child_process functions. A test that mocks
14
- * child_process (jest.mock) gets its mock and is unaffected; anything that
15
- * reaches the real module with, for example, `npm install` in a repository
16
- * directory throws instead of running.
17
- */
18
- const childProcess = require('child_process');
19
- const fs = require('fs');
20
- const os = require('os');
21
- const path = require('path');
22
-
23
- const PACKAGE_MANAGERS = new Set(['npm', 'npx', 'yarn', 'pnpm']);
24
- const MUTATING = new Set([
25
- 'install', 'i', 'in', 'ci', 'add', 'prune', 'uninstall', 'remove', 'rm', 'r', 'un',
26
- 'update', 'up', 'upgrade', 'dedupe', 'link', 'rebuild',
27
- ]);
28
-
29
- function realpathOrSelf(p) {
30
- try {
31
- return fs.realpathSync(p);
32
- } catch {
33
- return path.resolve(p);
34
- }
35
- }
36
-
37
- const TMP = realpathOrSelf(os.tmpdir());
38
- // The monorepo root (packages/devtools/test -> ../../..). A checkout can
39
- // itself live under the temp directory, so "under tmp" alone is not enough.
40
- const REPO_ROOT = realpathOrSelf(path.resolve(__dirname, '..', '..', '..'));
41
-
42
- const within = (dir, root) => dir === root || dir.startsWith(root + path.sep);
43
-
44
- /** True only for a scratch directory: under tmp and outside this repository. */
45
- function insideTmp(dir) {
46
- const real = realpathOrSelf(dir);
47
- return within(real, TMP) && !within(real, REPO_ROOT);
48
- }
49
-
50
- /** @returns {string|null} the offending command, or null when allowed */
51
- function offending(tokens, cwd) {
52
- const [bin, ...args] = tokens;
53
- if (!bin || !PACKAGE_MANAGERS.has(path.basename(String(bin)))) return null;
54
- const sub = args.find((a) => !String(a).startsWith('-'));
55
- // npx <pkg> runs a package; only installs/prunes rewrite node_modules.
56
- if (path.basename(String(bin)) === 'npx' || !MUTATING.has(sub)) return null;
57
- const prefixAt = args.indexOf('--prefix');
58
- const target = prefixAt >= 0 ? args[prefixAt + 1] : cwd;
59
- if (insideTmp(target || process.cwd())) return null;
60
- return tokens.join(' ');
61
- }
62
-
63
- const GUARDED = Symbol.for('frigg.devtools.npmInstallGuard');
64
-
65
- function guard(name, fn, toTokens) {
66
- // setupFiles runs once per test file in a shared worker: wrap once.
67
- if (fn[GUARDED]) return fn;
68
- const guarded = function guarded(...callArgs) {
69
- const { tokens, cwd } = toTokens(callArgs);
70
- const bad = offending(tokens, cwd);
71
- if (bad) {
72
- throw new Error(
73
- `Test tried to run "${bad}" outside the temp directory (cwd ${cwd || process.cwd()}); ` +
74
- 'it would rewrite a real node_modules. Mock it or run it in a temp dir.'
75
- );
76
- }
77
- return fn.apply(this, callArgs);
78
- };
79
- guarded[GUARDED] = true;
80
- return guarded;
81
- }
82
-
83
- const fromString = ([command, options]) => ({
84
- tokens: String(command).trim().split(/\s+/),
85
- cwd: options?.cwd,
86
- });
87
- const fromFile = ([file, args, options]) =>
88
- Array.isArray(args)
89
- ? { tokens: [file, ...args], cwd: options?.cwd }
90
- : { tokens: [file], cwd: args?.cwd };
91
-
92
- for (const name of ['execSync', 'exec']) {
93
- childProcess[name] = guard(name, childProcess[name], fromString);
94
- }
95
- for (const name of ['execFileSync', 'execFile', 'spawn', 'spawnSync']) {
96
- const original = childProcess[name];
97
- childProcess[name] = guard(name, original, (callArgs) => {
98
- const opts = Array.isArray(callArgs[1]) ? callArgs[2] : callArgs[1];
99
- if (opts?.shell && !Array.isArray(callArgs[1])) return fromString([callArgs[0], opts]);
100
- return fromFile(callArgs);
101
- });
102
- }
103
-
104
- module.exports = { offending, insideTmp };
@@ -1,53 +0,0 @@
1
- const os = require('os');
2
- const path = require('path');
3
- const childProcess = require('child_process');
4
- // Read before this file loads the guard itself: jest's setupFiles must have
5
- // installed it already, for every test file.
6
- const guardedBySetup = Boolean(childProcess.execSync[Symbol.for('frigg.devtools.npmInstallGuard')]);
7
- const { offending } = require('./npm-install-guard');
8
-
9
- const repoDir = path.resolve(__dirname, '..');
10
-
11
- describe('npm install guard (jest setupFiles)', () => {
12
- // Every command here is a --dry-run, so even a broken guard that let it
13
- // through could not rewrite this repository's node_modules.
14
- it('is installed by jest setupFiles, before any test code runs', () => {
15
- expect(guardedBySetup).toBe(true);
16
- });
17
-
18
- it('blocks installs and prunes on the real child_process', () => {
19
- expect(() =>
20
- childProcess.execSync('npm install --dry-run --omit=dev', { cwd: repoDir, stdio: 'ignore' })
21
- ).toThrow(/outside the temp directory/);
22
- expect(() =>
23
- childProcess.spawnSync('npm', ['prune', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
24
- ).toThrow(/outside the temp directory/);
25
- expect(() =>
26
- childProcess.execFileSync('/usr/bin/npm', ['ci', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
27
- ).toThrow(/outside the temp directory/);
28
- });
29
-
30
- it('treats a temp dir inside this repository as part of the repository', () => {
31
- // A checkout may itself live under os.tmpdir() (as in some sandboxes).
32
- expect(offending(['npm', 'install'], path.join(repoDir, 'layers/prisma/nodejs'))).not.toBeNull();
33
- });
34
-
35
- it.each([
36
- [['npm', 'install', '--omit=dev'], repoDir, true],
37
- [['npm', 'ci'], repoDir, true],
38
- [['yarn', 'add', 'x'], repoDir, true],
39
- [['npm', 'install', '--prefix', repoDir], os.tmpdir(), true],
40
- [['npm', 'install'], os.tmpdir(), false],
41
- [['npm', 'install', '--prefix', path.join(os.tmpdir(), 'layer')], repoDir, false],
42
- [['npm', 'root'], repoDir, false],
43
- [['npm', 'run', 'build'], repoDir, false],
44
- [['npx', 'netlify-cli', 'deploy'], repoDir, false],
45
- [['git', 'install'], repoDir, false],
46
- ])('%j in %s -> blocked %s', (tokens, cwd, blocked) => {
47
- expect(offending(tokens, cwd) !== null).toBe(blocked);
48
- });
49
-
50
- it('lets harmless commands through', () => {
51
- expect(childProcess.execSync('node -e "process.stdout.write(\'ok\')"', { encoding: 'utf8' })).toBe('ok');
52
- });
53
- });