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

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 (37) hide show
  1. package/frigg-cli/README.md +77 -30
  2. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +18 -0
  3. package/frigg-cli/__tests__/unit/commands/init.test.js +688 -0
  4. package/frigg-cli/__tests__/unit/commands/install.test.js +594 -341
  5. package/frigg-cli/generate-command/index.js +1 -0
  6. package/frigg-cli/generate-iam-command.js +1 -0
  7. package/frigg-cli/index.js +9 -4
  8. package/frigg-cli/init-command/backend-first-handler.js +397 -554
  9. package/frigg-cli/init-command/deployment-modes.js +7 -0
  10. package/frigg-cli/init-command/index.js +82 -35
  11. package/frigg-cli/init-command/safe-path.js +58 -0
  12. package/frigg-cli/init-command/scaffold-dependencies.js +202 -0
  13. package/frigg-cli/install-command/app-definition.js +174 -0
  14. package/frigg-cli/install-command/commit-changes.js +40 -8
  15. package/frigg-cli/install-command/environment-variables.js +15 -0
  16. package/frigg-cli/install-command/index.js +96 -21
  17. package/frigg-cli/install-command/install-package.js +77 -4
  18. package/frigg-cli/install-command/integration-file.js +20 -11
  19. package/frigg-cli/install-command/resolve-module.js +69 -0
  20. package/frigg-cli/install-command/template.js +102 -75
  21. package/frigg-cli/install-command/validate-package.js +36 -4
  22. package/frigg-cli/package.json +1 -1
  23. package/frigg-cli/templates/backend/README.md +267 -0
  24. package/frigg-cli/templates/backend/env.example +20 -0
  25. package/frigg-cli/templates/backend/gitignore +10 -0
  26. package/frigg-cli/templates/backend/index.js +114 -0
  27. package/frigg-cli/templates/backend/infrastructure.js +20 -0
  28. package/frigg-cli/test/init-command.test.js +9 -2
  29. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +148 -0
  30. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +21 -1
  31. package/infrastructure/domains/database/aurora-builder.js +13 -2
  32. package/infrastructure/domains/database/aurora-builder.test.js +22 -0
  33. package/infrastructure/domains/security/iam-generator.js +112 -5
  34. package/infrastructure/domains/security/iam-generator.test.js +94 -0
  35. package/infrastructure/domains/shared/utilities/base-definition-factory.js +7 -2
  36. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +21 -0
  37. package/package.json +10 -8
@@ -1,7 +1,14 @@
1
- const { installPackage } = require('./install-package');
2
- const { createIntegrationFile } = require('./integration-file');
3
- const { resolve } = require('node:path');
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { getInstallSpec, installPackage } = require('./install-package');
4
+ const {
5
+ createIntegrationFile,
6
+ INTEGRATIONS_DIR,
7
+ } = require('./integration-file');
4
8
  const { updateBackendJsFile } = require('./backend-js');
9
+ const { registerIntegration } = require('./app-definition');
10
+ const { resolveInstalledModule, readModuleInfo } = require('./resolve-module');
11
+ const { toIdentifier } = require('./template');
5
12
  const { logInfo, logError } = require('./logger');
6
13
  const { commitChanges } = require('./commit-changes');
7
14
  const { handleEnvVariables } = require('./environment-variables');
@@ -9,8 +16,39 @@ const {
9
16
  validatePackageExists,
10
17
  searchAndSelectPackage,
11
18
  } = require('./validate-package');
12
- const { findNearestBackendPackageJson, validateBackendPath } = require('@friggframework/core/utils');
19
+ const {
20
+ findNearestBackendPackageJson,
21
+ validateBackendPath,
22
+ } = require('@friggframework/core/utils');
23
+
24
+ /**
25
+ * Print what to do by hand when the app definition could not be edited.
26
+ */
27
+ function printManualSteps({ className, requirePath, definitionFile, reason }) {
28
+ logInfo(
29
+ `\nCould not add ${className} to ${definitionFile} automatically (${reason}). Add it by hand:\n` +
30
+ ` 1. At the top of ${definitionFile}:\n` +
31
+ ` const ${className} = require('${requirePath}');\n` +
32
+ ` 2. In the app definition's integrations array:\n` +
33
+ ` integrations: [${className}],\n`
34
+ );
35
+ }
13
36
 
37
+ /**
38
+ * `frigg install <module>`: install an API module and scaffold an
39
+ * integration for it.
40
+ *
41
+ * 1. `npm install` the module in the app directory (the `@next` tag for apps
42
+ * on a Frigg 2.x prerelease).
43
+ * 2. Resolve it from the app directory (`require.resolve` with
44
+ * `paths: [appDir]`).
45
+ * 3. Write `src/integrations/<Label>Integration.js`.
46
+ * 4. Register it: in a `frigg init` app, in index.js's `integrations` array
47
+ * (or print the manual steps when that cannot be done safely); in an older
48
+ * app with a backend.js, in backend.js as before.
49
+ * 5. Commit the changed files when inside a git repository.
50
+ * 6. Report (or prompt for) environment variables the module reads.
51
+ */
14
52
  const installCommand = async (apiModuleName) => {
15
53
  try {
16
54
  const packageNames = await searchAndSelectPackage(apiModuleName);
@@ -18,32 +56,69 @@ const installCommand = async (apiModuleName) => {
18
56
 
19
57
  const backendPath = findNearestBackendPackageJson();
20
58
  validateBackendPath(backendPath);
59
+ const projectDir = path.dirname(backendPath);
60
+ const backendJsPath = path.join(projectDir, 'backend.js');
61
+ const indexJsPath = path.join(projectDir, 'index.js');
62
+ const hasBackendJs = fs.existsSync(backendJsPath);
21
63
 
22
64
  for (const packageName of packageNames) {
23
65
  await validatePackageExists(packageName);
24
- installPackage(backendPath, packageName);
25
-
26
- const modulePath = resolve(
66
+ installPackage(
27
67
  backendPath,
28
- `../../node_modules/${packageName}`
68
+ getInstallSpec(packageName, projectDir)
29
69
  );
30
- const {
31
- Config: { label },
32
- Api: ApiClass,
33
- } = require(modulePath);
34
-
35
- const sanitizedLabel = label.replace(
36
- /[<>:"/\\|?*\x00-\x1F\s]/g,
37
- ''
38
- ); // Remove invalid characters and spaces console.log('Installing integration for:', sanitizedLabel);
39
- createIntegrationFile(backendPath, sanitizedLabel, ApiClass);
40
- updateBackendJsFile(backendPath, sanitizedLabel);
41
- commitChanges(backendPath, sanitizedLabel);
70
+
71
+ const { entryPath, moduleDir } = resolveInstalledModule(
72
+ packageName,
73
+ projectDir
74
+ );
75
+ const info = readModuleInfo(entryPath, packageName);
76
+ const baseName = toIdentifier(info.label);
77
+ const className = `${baseName}Integration`;
78
+ const requirePath = `./${INTEGRATIONS_DIR}/${className}`;
79
+
80
+ const { filePath } = createIntegrationFile(backendPath, {
81
+ className,
82
+ packageName,
83
+ ...info,
84
+ });
85
+ const changedFiles = [filePath];
86
+
87
+ if (hasBackendJs) {
88
+ // Older layout: the app definition lives in backend.js.
89
+ updateBackendJsFile(backendPath, baseName);
90
+ changedFiles.push(backendJsPath);
91
+ } else {
92
+ const result = registerIntegration(
93
+ indexJsPath,
94
+ className,
95
+ requirePath
96
+ );
97
+ if (result.status === 'registered') {
98
+ logInfo(`Added ${className} to index.js`);
99
+ changedFiles.push(indexJsPath);
100
+ } else if (result.status === 'already-registered') {
101
+ logInfo(`${className} is already in index.js`);
102
+ } else {
103
+ printManualSteps({
104
+ className,
105
+ requirePath,
106
+ definitionFile: 'index.js',
107
+ reason: result.reason,
108
+ });
109
+ }
110
+ }
111
+
112
+ for (const file of ['package.json', 'package-lock.json']) {
113
+ const full = path.join(projectDir, file);
114
+ if (fs.existsSync(full)) changedFiles.push(full);
115
+ }
116
+ commitChanges(backendPath, info.label, changedFiles);
42
117
  logInfo(
43
118
  `Successfully installed ${packageName} and updated the project.`
44
119
  );
45
120
 
46
- await handleEnvVariables(backendPath, modulePath);
121
+ await handleEnvVariables(backendPath, moduleDir);
47
122
  }
48
123
  } catch (error) {
49
124
  logError('An error occurred:', error);
@@ -1,13 +1,86 @@
1
- const { execSync } = require('child_process');
1
+ const fs = require('fs');
2
2
  const path = require('path');
3
+ const spawn = require('cross-spawn');
4
+ const semver = require('semver');
3
5
 
4
- function installPackage(backendPath, packageName) {
5
- execSync(`npm install ${packageName}`, {
6
+ /**
7
+ * The npm spec to install an API module with, for the app in `projectDir`.
8
+ *
9
+ * An app on a Frigg 2.x prerelease (e.g. `@friggframework/core@2.0.0-next.115`,
10
+ * what `frigg init` scaffolds today) needs the API modules published under the
11
+ * `next` dist-tag: npm's `latest` for most modules is still a 1.x release that
12
+ * depends on `@friggframework/core@^1`. Anything else installs the default
13
+ * (`latest`) version.
14
+ *
15
+ * @param {string} packageName - e.g. `@friggframework/api-module-hubspot`
16
+ * @param {string} projectDir - Directory holding the app's package.json
17
+ * @returns {string} npm install spec
18
+ */
19
+ function getInstallSpec(packageName, projectDir) {
20
+ const version = getCoreVersion(projectDir);
21
+ if (version && version.major >= 2 && version.prerelease.length > 0) {
22
+ return `${packageName}@next`;
23
+ }
24
+ return packageName;
25
+ }
26
+
27
+ /**
28
+ * The app's `@friggframework/core` version: the installed copy if there is
29
+ * one (this also covers `file:` and `link:` dependencies), otherwise the
30
+ * lowest version its package.json range admits.
31
+ *
32
+ * @returns {semver.SemVer|null}
33
+ */
34
+ function getCoreVersion(projectDir) {
35
+ try {
36
+ const installed = require.resolve('@friggframework/core/package.json', {
37
+ paths: [projectDir],
38
+ });
39
+ const { version } = JSON.parse(fs.readFileSync(installed, 'utf8'));
40
+ const parsed = semver.parse(version);
41
+ if (parsed) return parsed;
42
+ } catch (error) {
43
+ // Not installed yet; fall back to the declared range.
44
+ }
45
+ try {
46
+ const pkg = JSON.parse(
47
+ fs.readFileSync(path.join(projectDir, 'package.json'), 'utf8')
48
+ );
49
+ const range =
50
+ (pkg.dependencies && pkg.dependencies['@friggframework/core']) ||
51
+ (pkg.devDependencies &&
52
+ pkg.devDependencies['@friggframework/core']);
53
+ return range && semver.validRange(range)
54
+ ? semver.minVersion(range)
55
+ : null;
56
+ } catch (error) {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * `npm install <spec>` in the app directory. Arguments are passed as an
63
+ * array (no shell), so a package name can never be interpreted as a command.
64
+ *
65
+ * @param {string} backendPath - Path to the app's package.json
66
+ * @param {string} spec - npm install spec
67
+ */
68
+ function installPackage(backendPath, spec) {
69
+ const result = spawn.sync('npm', ['install', spec], {
6
70
  cwd: path.dirname(backendPath),
7
71
  stdio: 'inherit',
8
72
  });
73
+ if (result.error) {
74
+ throw result.error;
75
+ }
76
+ if (result.status !== 0) {
77
+ throw new Error(
78
+ `npm install ${spec} exited with code ${result.status}`
79
+ );
80
+ }
9
81
  }
10
82
 
11
83
  module.exports = {
84
+ getInstallSpec,
12
85
  installPackage,
13
- };
86
+ };
@@ -2,29 +2,38 @@ const fs = require('fs-extra');
2
2
  const path = require('path');
3
3
  const { logInfo } = require('./logger');
4
4
  const { getIntegrationTemplate } = require('./template');
5
+
5
6
  const INTEGRATIONS_DIR = 'src/integrations';
6
7
 
7
- function createIntegrationFile(backendPath, apiModuleName, ApiClass) {
8
+ /**
9
+ * Write `src/integrations/<ClassName>.js` next to the app's package.json.
10
+ * An existing file is left untouched (it may hold the user's work).
11
+ *
12
+ * @param {string} backendPath - Path to the app's package.json
13
+ * @param {object} templateParams - See getIntegrationTemplate
14
+ * @returns {{ filePath: string, created: boolean }}
15
+ */
16
+ function createIntegrationFile(backendPath, templateParams) {
8
17
  const integrationDir = path.join(
9
18
  path.dirname(backendPath),
10
19
  INTEGRATIONS_DIR
11
20
  );
12
- logInfo(`Ensuring directory exists: ${integrationDir}`);
13
21
  fs.ensureDirSync(integrationDir);
14
22
 
15
- const integrationFilePath = path.join(
23
+ const filePath = path.join(
16
24
  integrationDir,
17
- `${apiModuleName}Integration.js`
18
- );
19
- logInfo(`Writing integration file: ${integrationFilePath}`);
20
- const integrationTemplate = getIntegrationTemplate(
21
- apiModuleName,
22
- backendPath,
23
- ApiClass
25
+ `${templateParams.className}.js`
24
26
  );
25
- fs.writeFileSync(integrationFilePath, integrationTemplate);
27
+ if (fs.existsSync(filePath)) {
28
+ logInfo(`Keeping existing integration file: ${filePath}`);
29
+ return { filePath, created: false };
30
+ }
31
+ logInfo(`Writing integration file: ${filePath}`);
32
+ fs.writeFileSync(filePath, getIntegrationTemplate(templateParams));
33
+ return { filePath, created: true };
26
34
  }
27
35
 
28
36
  module.exports = {
37
+ INTEGRATIONS_DIR,
29
38
  createIntegrationFile,
30
39
  };
@@ -0,0 +1,69 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ /**
5
+ * Locate an installed API module from the app's point of view.
6
+ *
7
+ * Resolution starts at the app directory (`require.resolve` with
8
+ * `paths: [projectDir]`), so it finds the copy npm just installed whether
9
+ * node_modules sits in the app (a `frigg init` app) or is hoisted to a
10
+ * workspace root (the older `backend/` layout).
11
+ *
12
+ * @param {string} packageName
13
+ * @param {string} projectDir - Directory holding the app's package.json
14
+ * @returns {{ entryPath: string, moduleDir: string }}
15
+ */
16
+ function resolveInstalledModule(packageName, projectDir) {
17
+ const entryPath = require.resolve(packageName, { paths: [projectDir] });
18
+
19
+ // Walk up from the entry file to the package root (its package.json).
20
+ let dir = path.dirname(entryPath);
21
+ while (dir !== path.dirname(dir)) {
22
+ const pkgJson = path.join(dir, 'package.json');
23
+ if (fs.existsSync(pkgJson)) {
24
+ try {
25
+ const { name } = JSON.parse(fs.readFileSync(pkgJson, 'utf8'));
26
+ if (name === packageName) {
27
+ return { entryPath, moduleDir: dir };
28
+ }
29
+ } catch (error) {
30
+ // Not a readable package.json; keep walking.
31
+ }
32
+ }
33
+ dir = path.dirname(dir);
34
+ }
35
+ return { entryPath, moduleDir: path.dirname(entryPath) };
36
+ }
37
+
38
+ /**
39
+ * Load an installed API module and read what the integration scaffold needs.
40
+ *
41
+ * @returns {{ moduleName: string, label: string, description?: string,
42
+ * detailsUrl?: string, icon?: string, categories?: string[] }}
43
+ */
44
+ function readModuleInfo(entryPath, packageName) {
45
+ // eslint-disable-next-line global-require
46
+ const mod = require(entryPath);
47
+ const definition = mod && mod.Definition;
48
+ if (!definition) {
49
+ throw new Error(
50
+ `${packageName} does not export a Definition, so it is not a Frigg API module.`
51
+ );
52
+ }
53
+ const config = (mod && mod.Config) || {};
54
+ const moduleName =
55
+ (typeof definition.getName === 'function' && definition.getName()) ||
56
+ definition.moduleName ||
57
+ config.name ||
58
+ packageName.replace(/^@friggframework\/api-module-/, '');
59
+ return {
60
+ moduleName,
61
+ label: config.label || config.displayName || moduleName,
62
+ description: config.description,
63
+ detailsUrl: config.productUrl || config.detailsUrl,
64
+ icon: config.logoUrl || config.icon,
65
+ categories: config.categories,
66
+ };
67
+ }
68
+
69
+ module.exports = { resolveInstalledModule, readModuleInfo };
@@ -1,90 +1,117 @@
1
- const path = require('path');
1
+ /**
2
+ * Source for a new integration class (`src/integrations/<Name>Integration.js`)
3
+ * that wraps one installed API module.
4
+ *
5
+ * It follows the current IntegrationBase contract: a static `Definition`
6
+ * (name, version, display, `modules: { <key>: { definition } }`) and event
7
+ * handlers registered on `this.events` in the constructor. Calls to the API
8
+ * module go through `this.<key>.api.<method>()`.
9
+ */
2
10
 
3
- function getIntegrationTemplate(apiModuleName, backendPath, ApiClass) {
4
- // Find the sample data method
5
- const apiMethods = Object.getOwnPropertyNames(ApiClass.prototype);
6
- const sampleDataMethod =
7
- apiMethods.find(
8
- (method) =>
9
- method.toLowerCase().includes('search') ||
10
- method.toLowerCase().includes('list') ||
11
- method.toLowerCase().includes('get')
12
- ) || 'searchDeals';
11
+ /** Turn an arbitrary label (e.g. "Google Drive", "Monday.com") into a JS identifier. */
12
+ function toIdentifier(label) {
13
+ const words = String(label)
14
+ .split(/[^A-Za-z0-9]+/)
15
+ .filter(Boolean);
16
+ let identifier = words
17
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
18
+ .join('');
19
+ if (!identifier) {
20
+ identifier = 'Module';
21
+ }
22
+ if (/^[0-9]/.test(identifier)) {
23
+ identifier = `Module${identifier}`;
24
+ }
25
+ return identifier;
26
+ }
13
27
 
14
- return `const { get, IntegrationBase, Options } = require('@friggframework/core');
15
- const { Definition: ${apiModuleName}Module, Config: defaultConfig } = require('@friggframework/api-module-${apiModuleName.toLowerCase()}');
28
+ /** camelCase key for `Definition.modules` (e.g. "google-drive" -> "googleDrive"). */
29
+ function toModuleKey(moduleName) {
30
+ const words = String(moduleName)
31
+ .split(/[^A-Za-z0-9]+/)
32
+ .filter(Boolean);
33
+ if (words.length === 0) {
34
+ return 'module';
35
+ }
36
+ const key = words
37
+ .map((word, i) =>
38
+ i === 0
39
+ ? word.charAt(0).toLowerCase() + word.slice(1)
40
+ : word.charAt(0).toUpperCase() + word.slice(1)
41
+ )
42
+ .join('');
43
+ return /^[0-9]/.test(key) ? `module${key}` : key;
44
+ }
16
45
 
17
- class ${apiModuleName}Integration extends IntegrationBase {
18
- static Config = {
19
- name: defaultConfig.name || '${apiModuleName.toLowerCase()}',
20
- version: '1.0.0',
21
- supportedVersions: ['1.0.0'],
22
- events: ['SEARCH_DEALS'],
23
- };
46
+ const quote = (value) => JSON.stringify(value === undefined ? '' : value);
24
47
 
25
- static Options =
26
- new Options({
27
- module: ${apiModuleName}Module,
28
- integrations: [${apiModuleName}Module],
29
- display: {
30
- name: defaultConfig.displayName || '${apiModuleName}',
31
- description: defaultConfig.description || 'Sales & CRM, Marketing',
32
- category: defaultConfig.category || 'Sales & CRM, Marketing',
33
- detailsUrl: defaultConfig.detailsUrl || 'https://www.${apiModuleName.toLowerCase()}.com',
34
- icon: defaultConfig.icon || 'https://friggframework.org/assets/img/${apiModuleName.toLowerCase()}.jpeg',
35
- },
36
- hasUserConfig: true,
37
- });
48
+ /**
49
+ * @param {object} params
50
+ * @param {string} params.className - e.g. `HubSpotIntegration`
51
+ * @param {string} params.packageName - e.g. `@friggframework/api-module-hubspot`
52
+ * @param {string} params.moduleName - The module's `Definition.getName()`
53
+ * @param {string} params.label - Human-readable name
54
+ * @param {string} [params.description]
55
+ * @param {string} [params.detailsUrl]
56
+ * @param {string} [params.icon]
57
+ * @param {string[]} [params.categories]
58
+ * @returns {string}
59
+ */
60
+ function getIntegrationTemplate({
61
+ className,
62
+ packageName,
63
+ moduleName,
64
+ label,
65
+ description,
66
+ detailsUrl,
67
+ icon,
68
+ categories,
69
+ }) {
70
+ const moduleKey = toModuleKey(moduleName);
71
+ const moduleVar = `${moduleKey}Module`;
72
+ const category = Array.isArray(categories) ? categories.join(', ') : '';
38
73
 
39
- static modules = {
40
- ${apiModuleName.toLowerCase()}: ${apiModuleName}Module,
41
- }
74
+ return `const { IntegrationBase } = require('@friggframework/core');
75
+ const ${moduleVar} = require(${quote(packageName)});
42
76
 
43
- /**
44
- * HANDLE EVENTS
45
- */
46
- async receiveNotification(notifier, event, object = null) {
47
- if (event === 'SEARCH_DEALS') {
48
- return this.target.api.searchDeals(object);
49
- }
50
- }
77
+ class ${className} extends IntegrationBase {
78
+ static Definition = {
79
+ name: ${quote(moduleName)},
80
+ version: '1.0.0',
81
+ supportedVersions: ['1.0.0'],
82
+ hasUserConfig: false,
51
83
 
52
- /**
53
- * ALL CUSTOM/OPTIONAL METHODS FOR AN INTEGRATION MANAGER
54
- */
55
- async getSampleData() {
56
- const res = await this.target.api.${sampleDataMethod}();
57
- return { data: res };
58
- }
84
+ display: {
85
+ label: ${quote(label)},
86
+ description: ${quote(description)},
87
+ category: ${quote(category)},
88
+ detailsUrl: ${quote(detailsUrl)},
89
+ icon: ${quote(icon)},
90
+ },
59
91
 
60
- /**
61
- * ALL REQUIRED METHODS FOR AN INTEGRATION MANAGER
62
- */
63
- async onCreate(params) {
64
- // Validate that we have all of the data we need
65
- // Set integration status as makes sense. Default ENABLED
66
- // TODO turn this into a validateConfig method/function
67
- this.record.status = 'ENABLED';
68
- await this.record.save();
69
- return this.record;
70
- }
92
+ // The API modules this integration uses. Each key becomes
93
+ // \`this.<key>\` on an integration instance, e.g.
94
+ // \`this.${moduleKey}.api\`.
95
+ modules: {
96
+ ${moduleKey}: { definition: ${moduleVar}.Definition },
97
+ },
71
98
 
72
- async onUpdate(params) {
73
- const newConfig = get(params, 'config');
74
- const oldConfig = this.record.config;
75
- // Just save whatever
76
- this.record.markModified('config');
77
- await this.record.save();
78
- return this.validateConfig();
79
- }
99
+ // HTTP routes, served under /api/${moduleName}-integration/...
100
+ // e.g. { path: '/sample', method: 'GET', event: 'GET_SAMPLE_DATA' }
101
+ routes: [],
102
+ };
80
103
 
81
- async getConfigOptions() {
82
- const options = {}
83
- return options;
104
+ constructor(params) {
105
+ super(params);
106
+ this.events = {
107
+ // Map event names to handlers, e.g.
108
+ // GET_SAMPLE_DATA: { handler: this.getSampleData.bind(this) },
109
+ };
84
110
  }
85
111
  }
86
112
 
87
- module.exports = ${apiModuleName}Integration;`;
113
+ module.exports = ${className};
114
+ `;
88
115
  }
89
116
 
90
- module.exports = { getIntegrationTemplate };
117
+ module.exports = { getIntegrationTemplate, toIdentifier, toModuleKey };
@@ -1,12 +1,28 @@
1
- const { execSync } = require('child_process');
1
+ const spawn = require('cross-spawn');
2
2
  const axios = require('axios');
3
3
  const { logError } = require('./logger');
4
4
  const { checkbox } = require('@inquirer/prompts');
5
5
 
6
+ const API_MODULE_PREFIX = '@friggframework/api-module-';
7
+
6
8
  async function searchPackages(apiModuleName) {
7
- const searchCommand = `npm search @friggframework/api-module-${apiModuleName} --json`;
8
- const result = execSync(searchCommand, { encoding: 'utf8' });
9
- return JSON.parse(result);
9
+ // Arguments are passed as an array (no shell), so the search term can
10
+ // never be interpreted as a command.
11
+ const result = spawn.sync(
12
+ 'npm',
13
+ ['search', `${API_MODULE_PREFIX}${apiModuleName}`, '--json'],
14
+ { encoding: 'utf8' }
15
+ );
16
+ if (result.error) {
17
+ throw result.error;
18
+ }
19
+ if (result.status !== 0) {
20
+ throw new Error(`npm search failed: ${result.stderr || result.status}`);
21
+ }
22
+ // npm search is a full-text search; keep only Frigg API modules.
23
+ return JSON.parse(result.stdout || '[]').filter(
24
+ (pkg) => pkg && pkg.name && pkg.name.startsWith(API_MODULE_PREFIX)
25
+ );
10
26
  }
11
27
 
12
28
  async function checkPackageExists(packageName) {
@@ -58,6 +74,21 @@ const searchAndSelectPackage = async (apiModuleName) => {
58
74
  };
59
75
  });
60
76
 
77
+ // Without a terminal to prompt on, take the exact match
78
+ // (`frigg install hubspot` -> @friggframework/api-module-hubspot).
79
+ if (!process.stdin.isTTY) {
80
+ const exact = `${API_MODULE_PREFIX}${apiModuleName}`;
81
+ if (filteredResults.some((pkg) => pkg.name === exact)) {
82
+ return [exact];
83
+ }
84
+ logError(
85
+ `No exact match for ${exact}, and there is no terminal to choose from: ${filteredResults
86
+ .map((pkg) => pkg.name)
87
+ .join(', ')}`
88
+ );
89
+ process.exit(1);
90
+ }
91
+
61
92
  const selectedPackages = await checkbox({
62
93
  message: 'Select the packages to install:',
63
94
  choices,
@@ -68,6 +99,7 @@ const searchAndSelectPackage = async (apiModuleName) => {
68
99
  };
69
100
 
70
101
  module.exports = {
102
+ API_MODULE_PREFIX,
71
103
  validatePackageExists,
72
104
  checkPackageExists,
73
105
  searchPackages,
@@ -26,7 +26,7 @@
26
26
  "lodash": "4.18.1",
27
27
  "node-cache": "^5.1.2",
28
28
  "open": "^8.4.2",
29
- "osls": "^3.58.0",
29
+ "osls": "^3.78.0",
30
30
  "semver": "^7.6.0",
31
31
  "validate-npm-package-name": "^5.0.0"
32
32
  },