@friggframework/devtools 2.0.0-next.120 → 2.0.0-next.122

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 (59) hide show
  1. package/frigg-cli/README.md +77 -30
  2. package/frigg-cli/__tests__/unit/commands/deploy.test.js +30 -24
  3. package/frigg-cli/__tests__/unit/commands/doctor.test.js +10 -6
  4. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  5. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  6. package/frigg-cli/__tests__/unit/commands/install.test.js +601 -341
  7. package/frigg-cli/__tests__/unit/commands/ui.test.js +31 -30
  8. package/frigg-cli/__tests__/unit/dependencies.test.js +6 -2
  9. package/frigg-cli/generate-command/index.js +1 -0
  10. package/frigg-cli/generate-iam-command.js +1 -0
  11. package/frigg-cli/index.js +9 -4
  12. package/frigg-cli/init-command/backend-first-handler.js +397 -554
  13. package/frigg-cli/init-command/deployment-modes.js +7 -0
  14. package/frigg-cli/init-command/index.js +82 -35
  15. package/frigg-cli/init-command/safe-path.js +58 -0
  16. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  17. package/frigg-cli/install-command/app-definition.js +174 -0
  18. package/frigg-cli/install-command/commit-changes.js +40 -8
  19. package/frigg-cli/install-command/environment-variables.js +15 -0
  20. package/frigg-cli/install-command/index.js +96 -21
  21. package/frigg-cli/install-command/install-package.js +77 -4
  22. package/frigg-cli/install-command/integration-file.js +20 -11
  23. package/frigg-cli/install-command/resolve-module.js +69 -0
  24. package/frigg-cli/install-command/template.js +102 -75
  25. package/frigg-cli/install-command/validate-package.js +36 -4
  26. package/frigg-cli/package.json +1 -1
  27. package/frigg-cli/templates/backend/README.md +267 -0
  28. package/frigg-cli/templates/backend/env.example +20 -0
  29. package/frigg-cli/templates/backend/gitignore +10 -0
  30. package/frigg-cli/templates/backend/index.js +114 -0
  31. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  32. package/frigg-cli/test/init-command.test.js +9 -2
  33. package/infrastructure/__tests__/postgres-config.test.js +241 -835
  34. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  35. package/infrastructure/__tests__/template-generation.test.js +36 -8
  36. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
  37. package/infrastructure/domains/database/aurora-builder.js +13 -2
  38. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  39. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +12 -8
  40. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +19 -7
  41. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +12 -8
  42. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +17 -18
  43. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +12 -2
  44. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +8 -1
  45. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +4 -2
  46. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +10 -0
  47. package/infrastructure/domains/networking/vpc-builder.js +18 -8
  48. package/infrastructure/domains/networking/vpc-builder.test.js +26 -12
  49. package/infrastructure/domains/security/iam-generator.js +112 -5
  50. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  51. package/infrastructure/domains/shared/cloudformation-discovery.test.js +36 -6
  52. package/infrastructure/domains/shared/utilities/base-definition-factory.js +7 -2
  53. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +21 -0
  54. package/infrastructure/infrastructure-composer.test.js +268 -794
  55. package/infrastructure/scripts/build-prisma-layer.test.js +28 -7
  56. package/infrastructure/scripts/build-time-discovery.test.js +18 -3
  57. package/package.json +10 -8
  58. package/frigg-cli/index.test.js +0 -158
  59. package/infrastructure/integration.test.js +0 -381
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+
3
+ /** Deployment modes accepted by `frigg init --mode`. */
4
+ const DEPLOYMENT_MODES = ['standalone', 'embedded'];
5
+ const DEFAULT_DEPLOYMENT_MODE = 'standalone';
6
+
7
+ module.exports = { DEPLOYMENT_MODES, DEFAULT_DEPLOYMENT_MODE };
@@ -7,11 +7,12 @@
7
7
 
8
8
  'use strict';
9
9
 
10
- const path = require('path');
11
10
  const chalk = require('chalk');
12
11
  const validateProjectName = require('validate-npm-package-name');
13
12
  const semver = require('semver');
14
13
  const BackendFirstHandler = require('./backend-first-handler');
14
+ const { resolveProjectTarget } = require('./safe-path');
15
+ const { DEPLOYMENT_MODES } = require('./deployment-modes');
15
16
 
16
17
  function checkAppName(appName) {
17
18
  const validationResult = validateProjectName(appName);
@@ -26,7 +27,7 @@ function checkAppName(appName) {
26
27
  [
27
28
  ...(validationResult.errors || []),
28
29
  ...(validationResult.warnings || []),
29
- ].forEach(error => {
30
+ ].forEach((error) => {
30
31
  console.error(chalk.red(` * ${error}`));
31
32
  });
32
33
  console.error(chalk.red('\nPlease choose a different project name.'));
@@ -44,50 +45,96 @@ function checkNodeVersion() {
44
45
  console.log(
45
46
  chalk.yellow(
46
47
  `You are using Node ${process.version} so the project will be bootstrapped with an old unsupported version of tools.\n\n` +
47
- `Please update to Node 14 or higher for a better, fully supported experience.\n`
48
+ `Please update to Node 14 or higher for a better, fully supported experience.\n`
48
49
  )
49
50
  );
50
51
  }
51
52
  }
52
53
 
53
- async function initCommand(projectName, options) {
54
+ async function initCommand(projectName, options = {}) {
54
55
  const verbose = options.verbose || false;
55
56
  const force = options.force || false;
56
-
57
+
57
58
  checkNodeVersion();
58
59
 
59
- const root = path.resolve(projectName);
60
- const appName = path.basename(root);
60
+ // The legacy template system was removed; reject it before doing anything.
61
+ if (options.template) {
62
+ console.log();
63
+ console.log(
64
+ chalk.red('Legacy template system is no longer supported.')
65
+ );
66
+ console.log(
67
+ chalk.yellow(
68
+ `Run ${chalk.cyan(
69
+ 'frigg init <project-name>'
70
+ )} without --template.`
71
+ )
72
+ );
73
+ console.log();
74
+ process.exit(1);
75
+ return;
76
+ }
77
+
78
+ // Accept the project name from the positional argument or the --name flag.
79
+ const targetName = projectName || options.name;
80
+ if (!targetName) {
81
+ console.error(
82
+ chalk.red(
83
+ 'Please specify a project name:\n' +
84
+ ` ${chalk.cyan('frigg init')} ${chalk.green(
85
+ '<project-name>'
86
+ )}\n`
87
+ )
88
+ );
89
+ process.exit(1);
90
+ return;
91
+ }
92
+
93
+ if (options.mode && !DEPLOYMENT_MODES.includes(options.mode)) {
94
+ console.error(
95
+ chalk.red(
96
+ `Invalid --mode "${
97
+ options.mode
98
+ }". Expected one of: ${DEPLOYMENT_MODES.join(', ')}`
99
+ )
100
+ );
101
+ process.exit(1);
102
+ return;
103
+ }
104
+
105
+ // The last path segment is the project (and npm package) name; the
106
+ // project directory is resolved inside its parent directory.
107
+ let root;
108
+ let appName;
109
+ try {
110
+ ({ projectDir: root, name: appName } =
111
+ resolveProjectTarget(targetName));
112
+ } catch (error) {
113
+ console.error(chalk.red(error.message));
114
+ process.exit(1);
115
+ return;
116
+ }
61
117
 
62
118
  checkAppName(appName);
63
-
64
- // Use backend-first handler by default
65
- if (!options.template && !options.legacyFrontend) {
66
- try {
67
- const handler = new BackendFirstHandler(root, {
68
- force,
69
- verbose,
70
- mode: options.mode,
71
- frontend: options.frontend
72
- });
73
-
74
- await handler.initialize();
75
- return;
76
- } catch (error) {
77
- console.log();
78
- console.log(chalk.red('Aborting installation.'));
79
- console.log(chalk.red('Error:'), error.message);
80
- console.log();
81
- process.exit(1);
82
- }
119
+
120
+ try {
121
+ const handler = new BackendFirstHandler(root, {
122
+ force,
123
+ verbose,
124
+ mode: options.mode,
125
+ yes: options.yes || false,
126
+ install: options.install,
127
+ git: options.git,
128
+ });
129
+
130
+ await handler.initialize();
131
+ } catch (error) {
132
+ console.log();
133
+ console.log(chalk.red('Aborting installation.'));
134
+ console.log(chalk.red('Error:'), error.message);
135
+ console.log();
136
+ process.exit(1);
83
137
  }
84
-
85
- // If we get here, show an error for legacy options
86
- console.log();
87
- console.log(chalk.red('Legacy template system is no longer supported.'));
88
- console.log(chalk.yellow('Please use the new backend-first approach.'));
89
- console.log();
90
- process.exit(1);
91
138
  }
92
139
 
93
- module.exports = { initCommand };
140
+ module.exports = { initCommand };
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+
5
+ /**
6
+ * Resolve `segments` against `base` and make sure the result stays inside
7
+ * `base` (or is `base` itself). Every path `frigg init` writes to goes
8
+ * through here, so a crafted name or template entry can never make it write
9
+ * outside the project directory.
10
+ *
11
+ * @param {string} base - Absolute directory the result must stay within
12
+ * @param {...string} segments
13
+ * @returns {string} Absolute, normalized path
14
+ */
15
+ function resolveInside(base, ...segments) {
16
+ const root = path.resolve(base);
17
+ const resolved = path.resolve(root, ...segments);
18
+ const relative = path.relative(root, resolved);
19
+ if (
20
+ relative !== '' &&
21
+ (relative.startsWith('..') || path.isAbsolute(relative))
22
+ ) {
23
+ throw new Error(`Refusing to use ${resolved}: it is outside ${root}`);
24
+ }
25
+ return resolved;
26
+ }
27
+
28
+ /**
29
+ * Resolve the directory `frigg init <name>` creates.
30
+ *
31
+ * The argument may be a bare project name (`my-app`) or a path whose last
32
+ * segment is the project name (`../apps/my-app`, `/tmp/my-app`). The parent
33
+ * is resolved from the working directory and the project directory is
34
+ * resolved inside that parent, so the last segment must be a plain name:
35
+ * `.`, `..` and empty names are rejected (the npm package-name check in
36
+ * initCommand rejects the rest).
37
+ *
38
+ * @param {string} input - CLI argument
39
+ * @param {string} [cwd]
40
+ * @returns {{ parentDir: string, projectDir: string, name: string }}
41
+ */
42
+ function resolveProjectTarget(input, cwd = process.cwd()) {
43
+ if (typeof input !== 'string' || input.trim() === '') {
44
+ throw new Error('A project name is required');
45
+ }
46
+ const parentDir = path.resolve(cwd, path.dirname(input));
47
+ const name = path.basename(input);
48
+ if (name === '' || name === '.' || name === '..') {
49
+ throw new Error(`Invalid project name "${name}"`);
50
+ }
51
+ const projectDir = resolveInside(parentDir, name);
52
+ if (projectDir === parentDir) {
53
+ throw new Error(`Invalid project name "${name}"`);
54
+ }
55
+ return { parentDir, projectDir, name };
56
+ }
57
+
58
+ module.exports = { resolveInside, resolveProjectTarget };
@@ -0,0 +1,202 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const semver = require('semver');
5
+
6
+ /**
7
+ * Lowest stable Frigg 2.x release that a scaffolded app may resolve to.
8
+ *
9
+ * `@friggframework/core@2.0.0` exists on npm but is a deprecated, broken build
10
+ * (an accidental 2024 release on the old mongoose/aws-sdk v2 stack). A range
11
+ * such as `^2.0.0` resolves straight to it, so scaffolded ranges must never
12
+ * admit 2.0.0.
13
+ */
14
+ const MIN_STABLE_FRIGG_VERSION = '2.0.1';
15
+
16
+ /**
17
+ * The serverless plugins the composed infrastructure loads (see
18
+ * `infrastructure/domains/shared/utilities/base-definition-factory.js`) plus
19
+ * the `osls` CLI that `frigg start|build|deploy` spawn. Their versions are read
20
+ * from devtools' own package.json so the scaffold never drifts from what
21
+ * devtools is tested with.
22
+ */
23
+ const SERVERLESS_TOOLING = [
24
+ 'osls',
25
+ 'serverless-esbuild',
26
+ 'serverless-offline',
27
+ 'serverless-offline-sqs',
28
+ 'serverless-dotenv-plugin',
29
+ ];
30
+
31
+ /**
32
+ * Prisma packages: optional peer dependencies of `@friggframework/core` that a
33
+ * Frigg app needs (`frigg db:setup` runs the Prisma CLI, and the generated
34
+ * client loads `@prisma/client` at runtime).
35
+ */
36
+ const PRISMA_PACKAGES = ['@prisma/client', 'prisma'];
37
+
38
+ /**
39
+ * Where devtools' package.json sits when frigg-cli runs from inside
40
+ * `@friggframework/devtools` (the normal case: `<devtools>/frigg-cli/init-command`).
41
+ */
42
+ const LOCAL_DEVTOOLS_PACKAGE_JSON = path.join(
43
+ __dirname,
44
+ '..',
45
+ '..',
46
+ 'package.json'
47
+ );
48
+ const DEVTOOLS_PACKAGE_JSON_SPECIFIER = '@friggframework/devtools/package.json';
49
+
50
+ function isModuleNotFoundFor(error, specifier) {
51
+ return (
52
+ Boolean(error) &&
53
+ error.code === 'MODULE_NOT_FOUND' &&
54
+ typeof error.message === 'string' &&
55
+ error.message.includes(specifier)
56
+ );
57
+ }
58
+
59
+ /**
60
+ * Read `@friggframework/devtools`' package.json.
61
+ *
62
+ * frigg-cli normally ships inside devtools, two levels below its package.json.
63
+ * It is also published on its own as `@friggframework/frigg-cli` (with
64
+ * devtools as a peer dependency); installed that way, two levels up is
65
+ * `node_modules/@friggframework`, which has no package.json, so resolve
66
+ * devtools as a module instead. Only that exact "file not found" takes the
67
+ * fallback: a malformed package.json or any other failure is rethrown so the
68
+ * real cause is not hidden.
69
+ *
70
+ * @param {object} [options]
71
+ * @param {Function} [options.requireFn] - Test seam for `require`.
72
+ * @returns {object} devtools' package.json.
73
+ */
74
+ function readDevtoolsPackageJson({ requireFn = require } = {}) {
75
+ try {
76
+ const pkg = requireFn(LOCAL_DEVTOOLS_PACKAGE_JSON);
77
+ if (pkg && pkg.name === '@friggframework/devtools') {
78
+ return pkg;
79
+ }
80
+ } catch (error) {
81
+ if (!isModuleNotFoundFor(error, LOCAL_DEVTOOLS_PACKAGE_JSON)) {
82
+ throw error;
83
+ }
84
+ }
85
+ return requireFn(DEVTOOLS_PACKAGE_JSON_SPECIFIER);
86
+ }
87
+
88
+ function readCorePackageJson() {
89
+ // eslint-disable-next-line global-require
90
+ return require('@friggframework/core/package.json');
91
+ }
92
+
93
+ /**
94
+ * Derive the semver range a scaffolded app should use for Frigg packages,
95
+ * given the version of the devtools doing the scaffolding.
96
+ *
97
+ * - Prerelease (e.g. `2.0.0-next.115`): pin the exact version. A caret range
98
+ * on a 2.0.0 prerelease also admits the deprecated stable 2.0.0; npm happens
99
+ * to skip deprecated versions when it can, but other clients do not, and
100
+ * the moment a newer prerelease is published an unpinned range drifts away
101
+ * from the devtools that generated the app.
102
+ * - Stable >= 2.0.1: `^<version>`, which can never resolve to 2.0.0.
103
+ * - Stable below 2.0.1 (not expected): `^2.0.1`, the first good stable build.
104
+ *
105
+ * @param {string} version - Devtools version.
106
+ * @returns {string} Range to write into the scaffolded package.json.
107
+ */
108
+ function getFriggVersionRange(version) {
109
+ const parsed = semver.valid(version);
110
+ if (!parsed) {
111
+ throw new Error(`Invalid @friggframework/devtools version: ${version}`);
112
+ }
113
+ if (semver.prerelease(parsed)) {
114
+ return parsed;
115
+ }
116
+ if (semver.lt(parsed, MIN_STABLE_FRIGG_VERSION)) {
117
+ return `^${MIN_STABLE_FRIGG_VERSION}`;
118
+ }
119
+ return `^${parsed}`;
120
+ }
121
+
122
+ function pickVersions(names, ...sources) {
123
+ const result = {};
124
+ for (const name of names) {
125
+ const source = sources.find((deps) => deps && deps[name]);
126
+ if (!source) {
127
+ throw new Error(
128
+ `Cannot determine a version for "${name}" from @friggframework/devtools`
129
+ );
130
+ }
131
+ result[name] = source[name];
132
+ }
133
+ return result;
134
+ }
135
+
136
+ /**
137
+ * Dependencies for a scaffolded Frigg backend's package.json.
138
+ *
139
+ * @param {object} [overrides] - Test seam: package.json objects to read from.
140
+ * @param {object} [overrides.devtoolsPackageJson]
141
+ * @param {object} [overrides.corePackageJson]
142
+ * @returns {{dependencies: object, devDependencies: object}}
143
+ */
144
+ function getScaffoldDependencies({
145
+ devtoolsPackageJson = readDevtoolsPackageJson(),
146
+ corePackageJson = readCorePackageJson(),
147
+ } = {}) {
148
+ const friggRange = getFriggVersionRange(devtoolsPackageJson.version);
149
+
150
+ const dependencies = sortKeys({
151
+ '@friggframework/core': friggRange,
152
+ ...pickVersions(
153
+ PRISMA_PACKAGES,
154
+ corePackageJson.peerDependencies,
155
+ corePackageJson.devDependencies
156
+ ),
157
+ });
158
+
159
+ const devDependencies = sortKeys({
160
+ '@friggframework/devtools': friggRange,
161
+ '@friggframework/serverless-plugin': friggRange,
162
+ ...pickVersions(
163
+ SERVERLESS_TOOLING,
164
+ devtoolsPackageJson.dependencies,
165
+ devtoolsPackageJson.devDependencies
166
+ ),
167
+ jest: devtoolsPackageJson.devDependencies.jest,
168
+ });
169
+
170
+ return { dependencies, devDependencies };
171
+ }
172
+
173
+ function sortKeys(object) {
174
+ return Object.fromEntries(
175
+ Object.entries(object).sort(([a], [b]) => a.localeCompare(b))
176
+ );
177
+ }
178
+
179
+ /**
180
+ * Scripts for a scaffolded Frigg backend. They delegate to the `frigg` binary
181
+ * provided by the `@friggframework/devtools` devDependency.
182
+ */
183
+ function getScaffoldScripts() {
184
+ return {
185
+ start: 'frigg start',
186
+ build: 'frigg build',
187
+ deploy: 'frigg deploy',
188
+ 'db:setup': 'frigg db:setup',
189
+ test: 'jest --passWithNoTests',
190
+ };
191
+ }
192
+
193
+ module.exports = {
194
+ MIN_STABLE_FRIGG_VERSION,
195
+ SERVERLESS_TOOLING,
196
+ PRISMA_PACKAGES,
197
+ LOCAL_DEVTOOLS_PACKAGE_JSON,
198
+ readDevtoolsPackageJson,
199
+ getFriggVersionRange,
200
+ getScaffoldDependencies,
201
+ getScaffoldScripts,
202
+ };
@@ -0,0 +1,174 @@
1
+ const fs = require('fs');
2
+ const { parse } = require('@babel/parser');
3
+
4
+ const PARSE_OPTIONS = {
5
+ sourceType: 'unambiguous',
6
+ allowReturnOutsideFunction: true,
7
+ plugins: ['jsx', 'classProperties', 'objectRestSpread'],
8
+ };
9
+
10
+ /**
11
+ * Find the single `integrations: [...]` array literal in a parsed file.
12
+ * Returns null unless there is exactly one, so an ambiguous file is never
13
+ * edited.
14
+ */
15
+ function findIntegrationsArray(ast) {
16
+ const found = [];
17
+ const visit = (node) => {
18
+ if (!node || typeof node.type !== 'string') return;
19
+ if (
20
+ (node.type === 'ObjectProperty' || node.type === 'Property') &&
21
+ !node.computed &&
22
+ ((node.key.type === 'Identifier' &&
23
+ node.key.name === 'integrations') ||
24
+ (node.key.type === 'StringLiteral' &&
25
+ node.key.value === 'integrations')) &&
26
+ node.value.type === 'ArrayExpression'
27
+ ) {
28
+ found.push(node.value);
29
+ }
30
+ for (const key of Object.keys(node)) {
31
+ if (key === 'loc' || key === 'start' || key === 'end') continue;
32
+ const child = node[key];
33
+ if (Array.isArray(child)) child.forEach(visit);
34
+ else if (child && typeof child.type === 'string') visit(child);
35
+ }
36
+ };
37
+ visit(ast.program);
38
+ return found.length === 1 ? found[0] : null;
39
+ }
40
+
41
+ function isRequireDeclaration(statement) {
42
+ return (
43
+ statement.type === 'VariableDeclaration' &&
44
+ statement.declarations.some(
45
+ (d) =>
46
+ d.init &&
47
+ d.init.type === 'CallExpression' &&
48
+ d.init.callee.type === 'Identifier' &&
49
+ d.init.callee.name === 'require'
50
+ )
51
+ );
52
+ }
53
+
54
+ function hasTopLevelRequire(ast) {
55
+ return ast.program.body.some(isRequireDeclaration);
56
+ }
57
+
58
+ /** Offset just after the last top-level `require` declaration, or after 'use strict', or 0. */
59
+ function findRequireInsertionPoint(ast) {
60
+ let offset = null;
61
+ for (const statement of ast.program.body) {
62
+ if (isRequireDeclaration(statement)) {
63
+ offset = statement.end;
64
+ }
65
+ }
66
+ if (offset !== null) return offset;
67
+ const directives = ast.program.directives || [];
68
+ if (directives.length > 0) return directives[directives.length - 1].end;
69
+ return 0;
70
+ }
71
+
72
+ function lineIndentAt(source, offset) {
73
+ const lineStart = source.lastIndexOf('\n', offset - 1) + 1;
74
+ const match = /^[ \t]*/.exec(source.slice(lineStart));
75
+ return match ? match[0] : '';
76
+ }
77
+
78
+ /**
79
+ * Register an integration class in the app definition file (`index.js`).
80
+ *
81
+ * Adds `const <ClassName> = require('<requirePath>');` after the last
82
+ * top-level require and `<ClassName>,` as the first entry of the one
83
+ * `integrations: [...]` array. The file is only written when it parses, has
84
+ * exactly one `integrations` array literal, and still parses after the edit;
85
+ * otherwise nothing is changed and the caller prints manual steps.
86
+ *
87
+ * @param {string} filePath - The app definition file (index.js)
88
+ * @param {string} className - e.g. `HubSpotIntegration`
89
+ * @param {string} requirePath - e.g. `./src/integrations/HubSpotIntegration`
90
+ * @returns {{ status: 'registered'|'already-registered'|'manual', reason?: string }}
91
+ */
92
+ function registerIntegration(filePath, className, requirePath) {
93
+ let source;
94
+ try {
95
+ source = fs.readFileSync(filePath, 'utf8');
96
+ } catch (error) {
97
+ return { status: 'manual', reason: `cannot read ${filePath}` };
98
+ }
99
+
100
+ let ast;
101
+ try {
102
+ ast = parse(source, PARSE_OPTIONS);
103
+ } catch (error) {
104
+ return { status: 'manual', reason: `cannot parse ${filePath}` };
105
+ }
106
+
107
+ const array = findIntegrationsArray(ast);
108
+ if (!array) {
109
+ return {
110
+ status: 'manual',
111
+ reason: 'expected exactly one `integrations: [...]` array literal',
112
+ };
113
+ }
114
+
115
+ const alreadyListed = array.elements.some(
116
+ (el) => el && el.type === 'Identifier' && el.name === className
117
+ );
118
+ const requireLine = `const ${className} = require('${requirePath}');`;
119
+ const alreadyRequired = source.includes(`require('${requirePath}')`);
120
+ if (alreadyListed && alreadyRequired) {
121
+ return { status: 'already-registered' };
122
+ }
123
+ if (alreadyListed !== alreadyRequired) {
124
+ return {
125
+ status: 'manual',
126
+ reason: `${className} is partly registered already`,
127
+ };
128
+ }
129
+
130
+ const baseIndent = lineIndentAt(source, array.start);
131
+ const itemIndent = `${baseIndent} `;
132
+ const inner = source.slice(array.start + 1, array.end - 1);
133
+ let arrayText;
134
+ if (inner.trim() === '') {
135
+ arrayText = `[\n${itemIndent}${className},\n${baseIndent}]`;
136
+ } else {
137
+ arrayText = `[\n${itemIndent}${className},${
138
+ inner.startsWith('\n') ? '' : `\n${itemIndent}`
139
+ }${inner}]`;
140
+ }
141
+
142
+ const at = findRequireInsertionPoint(ast);
143
+ let requireText;
144
+ if (at === 0) {
145
+ requireText = `${requireLine}\n`;
146
+ } else if (hasTopLevelRequire(ast)) {
147
+ requireText = `\n${requireLine}`;
148
+ } else {
149
+ requireText = `\n\n${requireLine}`;
150
+ }
151
+
152
+ // Apply the later edit first so the earlier offset stays valid.
153
+ const edits = [
154
+ { start: array.start, end: array.end, text: arrayText },
155
+ { start: at, end: at, text: requireText },
156
+ ].sort((a, b) => b.start - a.start);
157
+ let updated = source;
158
+ for (const edit of edits) {
159
+ updated =
160
+ updated.slice(0, edit.start) + edit.text + updated.slice(edit.end);
161
+ }
162
+
163
+ try {
164
+ const check = parse(updated, PARSE_OPTIONS);
165
+ if (!findIntegrationsArray(check)) throw new Error('lost array');
166
+ } catch (error) {
167
+ return { status: 'manual', reason: 'the edited file would not parse' };
168
+ }
169
+
170
+ fs.writeFileSync(filePath, updated);
171
+ return { status: 'registered' };
172
+ }
173
+
174
+ module.exports = { registerIntegration };
@@ -1,14 +1,46 @@
1
- const { execSync } = require('child_process');
1
+ const spawn = require('cross-spawn');
2
2
  const path = require('path');
3
+ const { logInfo } = require('./logger');
3
4
 
4
- function commitChanges(backendPath, apiModuleName) {
5
- const apiModulePath = path.join(path.dirname(backendPath), 'src', 'integrations', `${apiModuleName}Integration.js`);
6
- try {
7
- execSync(`git add ${apiModulePath}`);
8
- execSync(`git commit -m "Add ${apiModuleName}Integration to ${apiModuleName}Integration.js"`);
9
- } catch (error) {
10
- throw new Error('Failed to commit changes:', error);
5
+ function git(args, cwd) {
6
+ return spawn.sync('git', args, { cwd, stdio: 'ignore' });
7
+ }
8
+
9
+ /**
10
+ * Commit the files `frigg install` changed, and only those
11
+ * (`git commit -- <paths>` leaves anything else the user has staged alone).
12
+ *
13
+ * Committing is a convenience: outside a git repository, or when the commit
14
+ * fails (e.g. no git identity configured), the install still succeeds and the
15
+ * changes are left in the working tree.
16
+ *
17
+ * @param {string} backendPath - Path to the app's package.json
18
+ * @param {string} label - Integration label, for the commit message
19
+ * @param {string[]} files - Absolute paths of the files to commit
20
+ * @returns {boolean} whether a commit was made
21
+ */
22
+ function commitChanges(backendPath, label, files = []) {
23
+ const cwd = path.dirname(backendPath);
24
+ const inRepo = git(['rev-parse', '--is-inside-work-tree'], cwd);
25
+ if (inRepo.error || inRepo.status !== 0 || files.length === 0) {
26
+ return false;
27
+ }
28
+ const relative = files.map((file) => path.relative(cwd, file));
29
+ const add = git(['add', '--', ...relative], cwd);
30
+ const commit =
31
+ add.status === 0 &&
32
+ git(
33
+ ['commit', '-m', `Add ${label} integration`, '--', ...relative],
34
+ cwd
35
+ );
36
+ if (!commit || commit.status !== 0) {
37
+ logInfo(
38
+ 'Could not commit the changes; they are left in your working tree.'
39
+ );
40
+ return false;
11
41
  }
42
+ logInfo(`Committed: Add ${label} integration`);
43
+ return true;
12
44
  }
13
45
 
14
46
  module.exports = {
@@ -43,6 +43,12 @@ const extractRawEnvVariables = (modulePath) => {
43
43
  return envVariables;
44
44
  };
45
45
  const handleEnvVariables = async (backendPath, modulePath) => {
46
+ if (!existsSync(resolve(modulePath, 'definition.js'))) {
47
+ logInfo(
48
+ 'This module has no definition.js; check its README for the environment variables it needs.'
49
+ );
50
+ return;
51
+ }
46
52
  logInfo('Searching for missing environment variables...');
47
53
  const Definition = { env: extractRawEnvVariables(modulePath) };
48
54
  if (Definition && Definition.env) {
@@ -80,6 +86,15 @@ const handleEnvVariables = async (backendPath, modulePath) => {
80
86
 
81
87
  logInfo(`Missing environment variables: ${missingEnvVars.join(', ')}`);
82
88
 
89
+ if (missingEnvVars.length > 0 && !process.stdin.isTTY) {
90
+ logInfo(
91
+ `Set these in .env for local development: ${missingEnvVars.join(
92
+ ', '
93
+ )}`
94
+ );
95
+ return;
96
+ }
97
+
83
98
  if (missingEnvVars.length > 0) {
84
99
  const addEnvVars = await confirm({
85
100
  message: `The following environment variables are required: ${missingEnvVars.join(