@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
@@ -1,21 +1,82 @@
1
1
  const fs = require('fs-extra');
2
2
  const path = require('path');
3
3
  const chalk = require('chalk');
4
- const { select, confirm, multiselect } = require('@inquirer/prompts');
5
- const { execSync } = require('child_process');
4
+ const { spawnSync } = require('child_process');
6
5
  const spawn = require('cross-spawn');
6
+ const { resolveInside } = require('./safe-path');
7
7
  const npmRegistry = require('../utils/npm-registry');
8
- const { validateAppDefinition, formatErrors } = require('@friggframework/schemas');
8
+ const {
9
+ validateAppDefinition,
10
+ formatErrors,
11
+ } = require('@friggframework/schemas');
12
+ const {
13
+ getScaffoldDependencies,
14
+ getScaffoldScripts,
15
+ } = require('./scaffold-dependencies');
16
+
17
+ const {
18
+ DEPLOYMENT_MODES,
19
+ DEFAULT_DEPLOYMENT_MODE,
20
+ } = require('./deployment-modes');
21
+
22
+ /** Sub-directory that holds the Frigg backend in embedded mode. */
23
+ const EMBEDDED_DIR = 'frigg-integration';
9
24
 
10
25
  /**
11
- * Backend-first template handler that treats frontend as optional demonstration
26
+ * Template files stored under a different name. npm strips `.gitignore` from
27
+ * published packages, and dotfiles are easy to lose, so they are renamed when
28
+ * copied into the new project.
29
+ */
30
+ const RENAMED_TEMPLATE_FILES = {
31
+ gitignore: '.gitignore',
32
+ 'env.example': '.env.example',
33
+ };
34
+
35
+ /**
36
+ * Files that may already exist in the target directory. They are kept (not
37
+ * overwritten) unless --force is given.
38
+ */
39
+ const PRESERVED_FILES = ['README.md', '.gitignore'];
40
+ const ALLOWED_EXISTING_FILES = ['.git', '.DS_Store', ...PRESERVED_FILES];
41
+
42
+ const TEMPLATE_APP_NAME = "name: 'frigg-app',";
43
+ const TEMPLATE_README_TITLE = '# Frigg Backend';
44
+
45
+ /**
46
+ * Scaffolds a new Frigg backend application.
47
+ *
48
+ * Prompts are interactive only when stdin is a TTY and --yes was not given;
49
+ * otherwise every prompt resolves to its default, so `frigg init` works in CI
50
+ * and scripts.
12
51
  */
13
52
  class BackendFirstHandler {
14
53
  constructor(targetPath, options = {}) {
15
- this.targetPath = targetPath;
16
- this.appName = path.basename(targetPath);
54
+ this.targetPath = path.resolve(targetPath);
55
+ this.appName = path.basename(this.targetPath);
17
56
  this.options = options;
18
57
  this.templatesDir = path.join(__dirname, '..', 'templates');
58
+ this.interactive =
59
+ options.interactive !== undefined
60
+ ? Boolean(options.interactive)
61
+ : !options.yes && Boolean(process.stdin.isTTY);
62
+ // Test seam: inject prompt implementations.
63
+ this.prompts = options.prompts || null;
64
+ }
65
+
66
+ /**
67
+ * Ask a question, or return its default when running non-interactively.
68
+ *
69
+ * @param {'select'|'confirm'|'checkbox'} type - @inquirer/prompts function.
70
+ * @param {object} config - Prompt config; `default` is used when
71
+ * non-interactive.
72
+ */
73
+ async ask(type, config) {
74
+ if (!this.interactive) {
75
+ return config.default;
76
+ }
77
+ // eslint-disable-next-line global-require
78
+ const prompts = this.prompts || require('@inquirer/prompts');
79
+ return prompts[type](config);
19
80
  }
20
81
 
21
82
  /**
@@ -23,34 +84,27 @@ class BackendFirstHandler {
23
84
  */
24
85
  async initialize() {
25
86
  console.log(chalk.blue('🚀 Welcome to Frigg - Integration Framework'));
26
- console.log(chalk.gray('Creating a new Frigg backend application...\n'));
87
+ console.log(
88
+ chalk.gray('Creating a new Frigg backend application...\n')
89
+ );
27
90
 
28
- // Get deployment mode
29
91
  const deploymentMode = await this.selectDeploymentMode();
30
-
31
- // Get project configuration
92
+ this.projectDir =
93
+ deploymentMode === 'embedded'
94
+ ? resolveInside(this.targetPath, EMBEDDED_DIR)
95
+ : this.targetPath;
96
+
97
+ // Fail fast, before asking anything else, if the target is not empty.
98
+ await this.ensureSafeDirectory(this.projectDir);
99
+
32
100
  const config = await this.getProjectConfiguration(deploymentMode);
33
101
 
34
- // Create project structure
35
102
  await this.createProject(deploymentMode, config);
36
103
 
37
- console.log(chalk.green('\n✅ Frigg application created successfully!'));
38
-
39
- // If user needs custom API module, prompt to create it
40
- if (config.needsCustomApiModule) {
41
- console.log(chalk.cyan('\n🔧 Now let\'s create your custom API module...'));
42
- const createModule = await confirm({
43
- message: 'Would you like to create your custom API module now?',
44
- default: true
45
- });
46
-
47
- if (createModule) {
48
- console.log(chalk.gray('\n Run this command after setup:'));
49
- console.log(chalk.cyan(` cd ${path.relative(process.cwd(), this.targetPath)}`));
50
- console.log(chalk.cyan(' frigg generate:api-module\n'));
51
- }
52
- }
53
-
104
+ console.log(
105
+ chalk.green('\n✅ Frigg application created successfully!')
106
+ );
107
+
54
108
  this.displayNextSteps(deploymentMode, config);
55
109
  }
56
110
 
@@ -59,27 +113,32 @@ class BackendFirstHandler {
59
113
  */
60
114
  async selectDeploymentMode() {
61
115
  if (this.options.mode) {
116
+ if (!DEPLOYMENT_MODES.includes(this.options.mode)) {
117
+ throw new Error(
118
+ `Invalid --mode "${
119
+ this.options.mode
120
+ }". Expected one of: ${DEPLOYMENT_MODES.join(', ')}`
121
+ );
122
+ }
62
123
  return this.options.mode;
63
124
  }
64
125
 
65
- const mode = await select({
126
+ return this.ask('select', {
66
127
  message: 'How will you deploy this Frigg application?',
67
128
  choices: [
68
- {
69
- name: 'Embedded - Integrate into existing application',
70
- value: 'embedded',
71
- description: 'Add Frigg as a library to your existing backend'
72
- },
73
129
  {
74
130
  name: 'Standalone - Deploy as separate service',
75
131
  value: 'standalone',
76
- description: 'Run Frigg as an independent microservice'
77
- }
132
+ description: 'Run Frigg as an independent microservice',
133
+ },
134
+ {
135
+ name: 'Embedded - Add to an existing repository',
136
+ value: 'embedded',
137
+ description: `Scaffold the Frigg backend into ./${EMBEDDED_DIR} of an existing project`,
138
+ },
78
139
  ],
79
- default: 'standalone'
140
+ default: DEFAULT_DEPLOYMENT_MODE,
80
141
  });
81
-
82
- return mode;
83
142
  }
84
143
 
85
144
  /**
@@ -88,154 +147,136 @@ class BackendFirstHandler {
88
147
  async getProjectConfiguration(deploymentMode) {
89
148
  const config = { deploymentMode };
90
149
 
91
- // Ask about the purpose of this Frigg application
92
- config.appPurpose = await select({
150
+ config.appPurpose = await this.ask('select', {
93
151
  message: 'What are you building with Frigg?',
94
152
  choices: [
95
153
  {
96
154
  name: 'Integrations for my own application',
97
155
  value: 'own-app',
98
- description: 'Build integrations that connect your app with third-party services'
156
+ description:
157
+ 'Build integrations that connect your app with third-party services',
99
158
  },
100
159
  {
101
160
  name: 'Integration platform for multiple apps',
102
161
  value: 'platform',
103
- description: 'Build a platform that provides integrations to other applications'
162
+ description:
163
+ 'Build a platform that provides integrations to other applications',
104
164
  },
105
165
  {
106
166
  name: 'Just exploring Frigg',
107
167
  value: 'exploring',
108
- description: 'Testing and learning about Frigg capabilities'
109
- }
110
- ]
168
+ description:
169
+ 'Testing and learning about Frigg capabilities',
170
+ },
171
+ ],
172
+ default: 'own-app',
111
173
  });
112
174
 
113
- // If building for own app, ask about creating custom API module
114
175
  if (config.appPurpose === 'own-app') {
115
- config.needsCustomApiModule = await confirm({
116
- message: 'Do you need to create an API module for your own application?',
117
- default: true
176
+ config.needsCustomApiModule = await this.ask('confirm', {
177
+ message:
178
+ 'Do you need to create an API module for your own application?',
179
+ default: false,
118
180
  });
119
-
120
- if (config.needsCustomApiModule) {
121
- console.log(chalk.cyan('\n💡 We\'ll help you create a custom API module after setup'));
122
- console.log(chalk.gray(' This will allow other integrations to connect with your API\n'));
123
- }
124
181
  }
125
182
 
126
- // Ask about initial integrations
127
- config.includeIntegrations = await confirm({
128
- message: 'Would you like to create integrations with available API modules?',
129
- default: true
183
+ // Selected modules are installed afterwards with `frigg install`,
184
+ // which installs the package and scaffolds the integration file.
185
+ config.includeIntegrations = await this.ask('confirm', {
186
+ message:
187
+ 'Would you like to pick API modules to integrate with? (installed afterwards with `frigg install`)',
188
+ default: false,
130
189
  });
131
190
 
132
191
  if (config.includeIntegrations) {
133
- console.log(chalk.gray('\n🔍 Discovering available API modules from npm...'));
134
-
135
- // Fetch available modules from npm
136
- const availableModules = await this.getAvailableModules();
137
-
138
- if (availableModules.length === 0) {
139
- console.log(chalk.yellow('⚠️ Could not fetch modules from npm. Using default list.'));
140
- config.starterIntegrations = await this.selectDefaultIntegrations();
141
- } else {
142
- // Group modules by category for better UX
143
- const groupedModules = await npmRegistry.getModulesByType();
144
- const choices = [];
145
-
146
- Object.entries(groupedModules).forEach(([category, modules]) => {
147
- if (modules.length > 0) {
148
- choices.push({ name: `--- ${category} ---`, value: null, disabled: true });
149
- modules.forEach(mod => {
150
- const name = mod.integrationName;
151
- const value = mod.name.replace('@friggframework/api-module-', '');
152
- choices.push({
153
- name: `${name} - ${mod.description || 'No description'}`,
154
- value: value,
155
- short: name
156
- });
157
- });
158
- }
159
- });
160
-
161
- config.starterIntegrations = await multiselect({
162
- message: 'Select API modules to integrate (space to select, enter to confirm):',
163
- choices,
164
- instructions: '\n Press <space> to select, <a> to toggle all, <enter> to confirm\n',
165
- validate: (answer) => {
166
- if (answer.length === 0) {
167
- return 'Please select at least one integration or press Ctrl+C to skip';
168
- }
169
- return true;
170
- }
171
- });
172
- }
173
- }
174
-
175
- // Ask about demo frontend only if not explicitly disabled
176
- if (this.options.frontend !== false) {
177
- config.includeDemoFrontend = await confirm({
178
- message: 'Include a demo frontend to showcase integration capabilities?',
179
- default: false
180
- });
181
-
182
- if (config.includeDemoFrontend) {
183
- console.log(chalk.yellow('\n📝 Note: The demo frontend is for demonstration purposes only.'));
184
- console.log(chalk.yellow(' For production, integrate Frigg into your existing application'));
185
- console.log(chalk.yellow(' or use "frigg ui" for development and management.\n'));
186
-
187
- config.frontendFramework = await select({
188
- message: 'Which framework for the demo frontend?',
189
- choices: [
190
- { name: 'React - Modern React with Vite', value: 'react' },
191
- { name: 'Vue 3 - Vue with Composition API', value: 'vue' },
192
- { name: 'Svelte - SvelteKit application', value: 'svelte' },
193
- { name: 'Angular - Angular with standalone components', value: 'angular' }
194
- ]
195
- });
196
-
197
- config.demoAuthMode = await select({
198
- message: 'Demo authentication mode:',
199
- choices: [
200
- {
201
- name: 'Mock Login - Simple username/password for demo',
202
- value: 'mock',
203
- description: 'Basic auth for demonstration'
204
- },
205
- {
206
- name: 'API Credentials - Use your app\'s actual auth',
207
- value: 'real',
208
- description: 'Configure with your authentication system'
209
- }
210
- ],
211
- default: 'mock'
212
- });
213
- }
192
+ config.starterIntegrations = await this.selectIntegrations();
214
193
  }
215
194
 
216
- // Serverless configuration for standalone mode
217
195
  if (deploymentMode === 'standalone') {
218
- config.serverlessProvider = await select({
196
+ config.serverlessProvider = await this.ask('select', {
219
197
  message: 'Which cloud provider will you use?',
220
198
  choices: [
221
199
  { name: 'AWS Lambda', value: 'aws' },
222
- { name: 'Local Development Only', value: 'local' }
200
+ { name: 'Local Development Only', value: 'local' },
223
201
  ],
224
- default: 'aws'
202
+ default: 'aws',
225
203
  });
226
204
  }
227
205
 
228
- config.installDependencies = await confirm({
229
- message: 'Install dependencies now?',
230
- default: true
206
+ config.installDependencies =
207
+ this.options.install === false
208
+ ? false
209
+ : await this.ask('confirm', {
210
+ message: 'Install dependencies now?',
211
+ default: true,
212
+ });
213
+
214
+ // Embedded mode lives inside an existing repository.
215
+ config.initializeGit =
216
+ deploymentMode === 'embedded' || this.options.git === false
217
+ ? false
218
+ : await this.ask('confirm', {
219
+ message: 'Initialize Git repository?',
220
+ default: true,
221
+ });
222
+
223
+ return config;
224
+ }
225
+
226
+ /**
227
+ * Let the user pick API modules. Only names are collected; the next-steps
228
+ * output tells the user to run `frigg install <name>` for each.
229
+ */
230
+ async selectIntegrations() {
231
+ console.log(
232
+ chalk.gray('\n🔍 Discovering available API modules from npm...')
233
+ );
234
+
235
+ const groupedModules = await this.getModulesByType();
236
+ const choices = [];
237
+ // eslint-disable-next-line global-require
238
+ const { Separator } = this.prompts || require('@inquirer/prompts');
239
+
240
+ Object.entries(groupedModules).forEach(([category, modules]) => {
241
+ if (modules.length === 0) return;
242
+ choices.push(new Separator(`--- ${category} ---`));
243
+ modules.forEach((mod) => {
244
+ choices.push({
245
+ name: `${mod.integrationName} - ${
246
+ mod.description || 'No description'
247
+ }`,
248
+ value: mod.name.replace('@friggframework/api-module-', ''),
249
+ short: mod.integrationName,
250
+ });
251
+ });
231
252
  });
232
253
 
233
- config.initializeGit = await confirm({
234
- message: 'Initialize Git repository?',
235
- default: true
254
+ if (choices.length === 0) {
255
+ console.log(
256
+ chalk.yellow(
257
+ '⚠️ Could not fetch modules from npm. Use `frigg search` / `frigg install <module>` later.'
258
+ )
259
+ );
260
+ return [];
261
+ }
262
+
263
+ return this.ask('checkbox', {
264
+ message:
265
+ 'Select API modules to integrate (space to select, enter to confirm):',
266
+ choices,
267
+ default: [],
236
268
  });
269
+ }
237
270
 
238
- return config;
271
+ async getModulesByType() {
272
+ try {
273
+ return await npmRegistry.getModulesByType();
274
+ } catch (error) {
275
+ if (this.options.verbose) {
276
+ console.error('Failed to fetch modules:', error.message);
277
+ }
278
+ return {};
279
+ }
239
280
  }
240
281
 
241
282
  /**
@@ -244,313 +285,179 @@ class BackendFirstHandler {
244
285
  async createProject(deploymentMode, config) {
245
286
  console.log(chalk.blue('\n📁 Creating Frigg backend application...'));
246
287
 
247
- // Ensure target directory exists and is safe
248
- await this.ensureSafeDirectory();
288
+ const packageName =
289
+ deploymentMode === 'embedded'
290
+ ? `${this.appName}-frigg-integration`
291
+ : this.appName;
249
292
 
250
- if (deploymentMode === 'standalone') {
251
- await this.createStandaloneProject(config);
252
- } else {
253
- await this.createEmbeddedProject(config);
254
- }
293
+ await fs.ensureDir(this.projectDir);
294
+ await this.copyTemplate(this.projectDir, packageName);
295
+ await this.writePackageJson(this.projectDir, packageName);
296
+ await this.validateGeneratedAppDefinition(
297
+ resolveInside(this.projectDir, 'index.js')
298
+ );
255
299
 
256
- // Initialize git if requested
257
300
  if (config.initializeGit) {
258
301
  await this.initializeGit();
259
302
  }
260
303
 
261
- // Install dependencies if requested
262
304
  if (config.installDependencies) {
263
- await this.installDependencies(config);
305
+ config.dependenciesInstalled = await this.installDependencies();
264
306
  }
265
307
  }
266
308
 
267
309
  /**
268
- * Create standalone Frigg service
310
+ * Copy the backend template into `dir`, substituting the project name and
311
+ * never overwriting a pre-existing README.md/.gitignore without --force.
269
312
  */
270
- async createStandaloneProject(config) {
271
- // Copy backend template
272
- const backendTemplate = path.join(this.templatesDir, 'backend');
273
- await fs.copy(backendTemplate, this.targetPath);
274
-
275
- // Create package.json for standalone mode
276
- const packageJson = {
277
- name: this.appName,
278
- version: '0.1.0',
279
- private: true,
280
- scripts: {
281
- "backend-start": "node infrastructure.js start",
282
- "start": "npm run backend-start",
283
- "build": "node infrastructure.js package",
284
- "deploy": "node infrastructure.js deploy",
285
- "test": "jest"
286
- },
287
- dependencies: {
288
- "@friggframework/core": "^2.0.0"
313
+ async copyTemplate(dir, packageName) {
314
+ const templateDir = resolveInside(this.templatesDir, 'backend');
315
+ const entries = await fs.readdir(templateDir);
316
+
317
+ for (const entry of entries) {
318
+ const destName = RENAMED_TEMPLATE_FILES[entry] || entry;
319
+ const dest = resolveInside(dir, destName);
320
+
321
+ if (
322
+ PRESERVED_FILES.includes(destName) &&
323
+ !this.options.force &&
324
+ (await fs.pathExists(dest))
325
+ ) {
326
+ console.log(
327
+ chalk.gray(
328
+ `Keeping existing ${destName} (use --force to overwrite)`
329
+ )
330
+ );
331
+ continue;
289
332
  }
290
- };
291
-
292
- // Add demo frontend if requested
293
- if (config.includeDemoFrontend) {
294
- packageJson.workspaces = ['backend', 'frontend'];
295
- packageJson.scripts['dev'] = 'concurrently "npm run backend-start" "npm run frontend:dev"';
296
- packageJson.scripts['frontend:dev'] = 'cd frontend && npm run dev';
297
-
298
- await this.createDemoFrontend(config);
299
- }
300
333
 
301
- // Add selected integrations as dependencies
302
- if (config.starterIntegrations && config.starterIntegrations.length > 0) {
303
- for (const integration of config.starterIntegrations) {
304
- packageJson.dependencies[`@friggframework/api-module-${integration}`] = '^2.0.0';
305
- }
334
+ await fs.copy(resolveInside(templateDir, entry), dest);
306
335
  }
307
336
 
308
- await fs.writeJSON(
309
- path.join(this.targetPath, 'package.json'),
310
- packageJson,
311
- { spaces: 2 }
337
+ await this.substituteInFile(
338
+ resolveInside(dir, 'index.js'),
339
+ TEMPLATE_APP_NAME,
340
+ `name: '${packageName}',`
341
+ );
342
+ await this.substituteInFile(
343
+ resolveInside(dir, 'README.md'),
344
+ TEMPLATE_README_TITLE,
345
+ `# ${packageName}`
312
346
  );
313
347
 
314
- // Update index.js with selected integrations
315
- if (config.starterIntegrations && config.starterIntegrations.length > 0) {
316
- await this.updateAppDefinition(config.starterIntegrations);
348
+ // Seed a local .env from the example so `frigg start` has a
349
+ // DATABASE_URL to work with. .env is git-ignored.
350
+ const envExample = resolveInside(dir, '.env.example');
351
+ const env = resolveInside(dir, '.env');
352
+ if ((await fs.pathExists(envExample)) && !(await fs.pathExists(env))) {
353
+ await fs.copy(envExample, env);
317
354
  }
355
+ }
318
356
 
319
- // Validate generated app definition against schema
320
- const appDefPath = path.join(this.targetPath, 'index.js');
321
- await this.validateGeneratedAppDefinition(appDefPath);
322
-
323
- // Update serverless.yml based on provider
324
- if (config.serverlessProvider === 'aws') {
325
- await this.configureAWSServerless();
326
- }
357
+ async substituteInFile(file, search, replacement) {
358
+ const filePath = resolveInside(this.targetPath, file);
359
+ if (!(await fs.pathExists(filePath))) return;
360
+ const content = await fs.readFile(filePath, 'utf8');
361
+ if (!content.includes(search)) return;
362
+ await fs.writeFile(filePath, content.replace(search, replacement));
327
363
  }
328
364
 
329
365
  /**
330
- * Create embedded Frigg setup
366
+ * Write package.json with the `frigg` scripts and the dependencies the
367
+ * composed serverless configuration needs.
331
368
  */
332
- async createEmbeddedProject(config) {
333
- console.log(chalk.blue('Creating embedded Frigg setup...'));
334
-
335
- // Create a minimal setup for embedding
336
- const setupDir = path.join(this.targetPath, 'frigg-integration');
337
- await fs.ensureDir(setupDir);
338
-
339
- // Copy essential files
340
- const essentialFiles = ['index.js', 'infrastructure.js'];
341
- for (const file of essentialFiles) {
342
- const src = path.join(this.templatesDir, 'backend', file);
343
- const dest = path.join(setupDir, file);
344
- if (await fs.pathExists(src)) {
345
- await fs.copy(src, dest);
346
- }
347
- }
348
-
349
- // Validate copied app definition against schema
350
- const appDefPath = path.join(setupDir, 'index.js');
351
- if (await fs.pathExists(appDefPath)) {
352
- await this.validateGeneratedAppDefinition(appDefPath);
353
- }
354
-
355
- // Create integration guide
356
- const integrationGuide = `# Frigg Integration Guide
357
-
358
- ## Installation
359
-
360
- Add Frigg to your existing project:
361
-
362
- \`\`\`bash
363
- npm install @friggframework/core
364
- \`\`\`
365
-
366
- ## Integration Steps
367
-
368
- 1. Copy the files from \`frigg-integration/\` to your backend
369
- 2. Import and initialize Frigg in your application:
370
-
371
- \`\`\`javascript
372
- const { createFriggBackend } = require('@friggframework/core');
373
- const appDefinition = require('./app-definition');
374
-
375
- // In your Express app or serverless handler
376
- const friggRouter = await createFriggBackend(appDefinition);
377
- app.use('/api/frigg', friggRouter);
378
- \`\`\`
379
-
380
- 3. Configure your environment variables
381
- 4. Deploy your application
382
-
383
- ## Development
384
-
385
- Use \`frigg ui\` to manage your integrations during development.
386
- `;
387
-
388
- await fs.writeFile(
389
- path.join(this.targetPath, 'FRIGG_INTEGRATION.md'),
390
- integrationGuide
391
- );
392
-
393
- // Add package.json with Frigg dependency
369
+ async writePackageJson(dir, packageName) {
370
+ const { dependencies, devDependencies } = getScaffoldDependencies();
394
371
  const packageJson = {
395
- name: `${this.appName}-frigg-integration`,
372
+ name: packageName,
396
373
  version: '0.1.0',
397
374
  private: true,
398
- dependencies: {
399
- "@friggframework/core": "^2.0.0"
400
- }
375
+ main: 'index.js',
376
+ scripts: getScaffoldScripts(),
377
+ dependencies,
378
+ devDependencies,
401
379
  };
402
380
 
403
- await fs.writeJSON(
404
- path.join(setupDir, 'package.json'),
405
- packageJson,
406
- { spaces: 2 }
407
- );
381
+ await fs.writeJSON(resolveInside(dir, 'package.json'), packageJson, {
382
+ spaces: 2,
383
+ });
408
384
  }
409
385
 
410
386
  /**
411
- * Create demo frontend
387
+ * Ensure the directory the backend is written to is missing or empty
388
+ * (apart from a few harmless files), unless --force is given.
412
389
  */
413
- async createDemoFrontend(config) {
414
- console.log(chalk.blue('Creating demo frontend...'));
415
-
416
- const frontendDir = path.join(this.targetPath, 'frontend');
417
- await fs.ensureDir(frontendDir);
418
-
419
- // Copy framework-specific template
420
- const frameworkTemplate = path.join(this.templatesDir, config.frontendFramework);
421
- if (await fs.pathExists(frameworkTemplate)) {
422
- await fs.copy(frameworkTemplate, frontendDir);
423
- }
424
-
425
- // Add demo auth configuration
426
- if (config.demoAuthMode === 'mock') {
427
- await this.addMockAuth(frontendDir, config.frontendFramework);
390
+ async ensureSafeDirectory(directory = this.targetPath) {
391
+ const dir = resolveInside(this.targetPath, directory);
392
+ if (!(await fs.pathExists(dir))) {
393
+ return;
428
394
  }
429
395
 
430
- // Add demo notice to README
431
- const demoNotice = `# Frigg Demo Frontend
432
-
433
- > ⚠️ **This is a demonstration frontend only!**
434
- >
435
- > This frontend showcases how to integrate Frigg into your application.
436
- > For production use, integrate Frigg into your existing application.
437
- >
438
- > For development and management, use \`frigg ui\` instead.
439
-
440
- ## Purpose
441
-
442
- This demo shows:
443
- - How to authenticate with Frigg
444
- - How to display available integrations
445
- - How to handle OAuth flows
446
- - How to manage user connections
447
-
448
- ## Getting Started
449
-
450
- \`\`\`bash
451
- npm install
452
- npm run dev
453
- \`\`\`
454
-
455
- ## Production Integration
456
-
457
- To integrate Frigg into your production application:
458
- 1. Review the API calls in \`src/services/frigg.js\`
459
- 2. Copy the relevant components to your application
460
- 3. Adapt the authentication to your system
461
- 4. Style according to your design system
462
- `;
463
-
464
- await fs.writeFile(
465
- path.join(frontendDir, 'README.md'),
466
- demoNotice
467
- );
468
- }
469
-
470
- /**
471
- * Add mock authentication to demo
472
- */
473
- async addMockAuth(frontendDir, framework) {
474
- const mockAuthConfig = {
475
- users: [
476
- { username: 'demo', password: 'demo', name: 'Demo User' }
477
- ],
478
- message: 'Use demo/demo to login'
479
- };
480
-
481
- await fs.writeJSON(
482
- path.join(frontendDir, 'mock-auth.json'),
483
- mockAuthConfig,
484
- { spaces: 2 }
396
+ const files = await fs.readdir(dir);
397
+ const conflictingFiles = files.filter(
398
+ (f) => !ALLOWED_EXISTING_FILES.includes(f)
485
399
  );
486
- }
487
400
 
488
- /**
489
- * Ensure target directory is safe
490
- */
491
- async ensureSafeDirectory() {
492
- await fs.ensureDir(this.targetPath);
493
-
494
- const files = await fs.readdir(this.targetPath);
495
- const allowedFiles = ['.git', '.gitignore', 'README.md', '.DS_Store'];
496
- const conflictingFiles = files.filter(f => !allowedFiles.includes(f));
497
-
498
401
  if (conflictingFiles.length > 0 && !this.options.force) {
499
- console.log(chalk.red('\n❌ Directory is not empty!'));
500
- console.log(chalk.yellow('Found files:'), conflictingFiles.join(', '));
402
+ console.log(chalk.red(`\n❌ Directory is not empty: ${dir}`));
403
+ console.log(
404
+ chalk.yellow('Found files:'),
405
+ conflictingFiles.join(', ')
406
+ );
501
407
  console.log(chalk.gray('Use --force to override\n'));
502
408
  throw new Error('Directory not empty');
503
409
  }
504
410
  }
505
411
 
506
- /**
507
- * Configure AWS serverless
508
- */
509
- async configureAWSServerless() {
510
- // Update serverless.yml for AWS
511
- const serverlessPath = path.join(this.targetPath, 'serverless.yml');
512
- if (await fs.pathExists(serverlessPath)) {
513
- // Keep existing AWS configuration
514
- console.log(chalk.gray('AWS Lambda configuration ready'));
515
- }
516
- }
517
-
518
412
  /**
519
413
  * Initialize git repository
520
414
  */
521
415
  async initializeGit() {
522
- try {
523
- execSync('git init', { cwd: this.targetPath, stdio: 'ignore' });
524
- execSync('git add -A', { cwd: this.targetPath, stdio: 'ignore' });
525
- execSync('git commit -m "Initial commit from Frigg CLI"', {
526
- cwd: this.targetPath,
527
- stdio: 'ignore'
416
+ // Argument arrays, no shell: nothing here is parsed by a shell.
417
+ const git = (args) =>
418
+ spawnSync('git', args, {
419
+ cwd: this.projectDir,
420
+ stdio: 'ignore',
421
+ shell: false,
528
422
  });
529
- console.log(chalk.gray('Git repository initialized'));
530
- } catch (e) {
531
- // Git init failed, not critical
423
+ // Git is a convenience: a missing git or git identity is not fatal.
424
+ for (const args of [
425
+ ['init'],
426
+ ['add', '-A'],
427
+ ['commit', '-m', 'Initial commit from Frigg CLI'],
428
+ ]) {
429
+ const result = git(args);
430
+ if (result.error || result.status !== 0) {
431
+ return;
432
+ }
532
433
  }
434
+ console.log(chalk.gray('Git repository initialized'));
533
435
  }
534
436
 
535
437
  /**
536
438
  * Install dependencies
439
+ * @returns {boolean} whether the install succeeded
537
440
  */
538
- async installDependencies(config) {
441
+ async installDependencies() {
539
442
  console.log(chalk.blue('\n📦 Installing dependencies...'));
540
-
443
+
541
444
  const useYarn = this.isUsingYarn();
542
445
  const command = useYarn ? 'yarn' : 'npm';
543
446
  const args = useYarn ? [] : ['install'];
544
447
 
545
448
  const proc = spawn.sync(command, args, {
546
- cwd: this.targetPath,
547
- stdio: 'inherit'
449
+ cwd: this.projectDir,
450
+ stdio: 'inherit',
548
451
  });
549
452
 
550
453
  if (proc.status !== 0) {
551
454
  console.log(chalk.yellow('\n⚠️ Dependency installation failed'));
552
- console.log(chalk.gray(`You can install manually with: ${command} install`));
455
+ console.log(
456
+ chalk.gray(`You can install manually with: ${command} install`)
457
+ );
458
+ return false;
553
459
  }
460
+ return true;
554
461
  }
555
462
 
556
463
  /**
@@ -561,196 +468,132 @@ To integrate Frigg into your production application:
561
468
  }
562
469
 
563
470
  /**
564
- * Get available modules from npm
471
+ * Validate the generated app definition against the app-definition
472
+ * schema by loading the `Definition` the generated index.js exports.
473
+ *
474
+ * Validation problems are reported as warnings; they never abort init.
475
+ *
476
+ * @returns {boolean} true when the definition is valid
565
477
  */
566
- async getAvailableModules() {
478
+ async validateGeneratedAppDefinition(appDefPath) {
479
+ if (this.options.verbose) {
480
+ console.log(
481
+ chalk.gray('🔍 Validating app definition against schema...')
482
+ );
483
+ }
484
+
485
+ let definition;
567
486
  try {
568
- const modules = await npmRegistry.searchApiModules();
569
- return modules;
487
+ const resolved = require.resolve(appDefPath);
488
+ delete require.cache[resolved];
489
+ // eslint-disable-next-line global-require
490
+ ({ Definition: definition } = require(resolved));
570
491
  } catch (error) {
571
- console.error('Failed to fetch modules:', error.message);
572
- return [];
492
+ console.log(
493
+ chalk.yellow(
494
+ `⚠️ Could not load the generated app definition for validation: ${error.message}`
495
+ )
496
+ );
497
+ return false;
573
498
  }
574
- }
575
499
 
576
- /**
577
- * Select from default integrations when npm is unavailable
578
- */
579
- async selectDefaultIntegrations() {
580
- return await multiselect({
581
- message: 'Select starter integrations (space to select, enter to confirm):',
582
- choices: [
583
- { name: 'Salesforce - CRM integration', value: 'salesforce' },
584
- { name: 'HubSpot - Marketing automation', value: 'hubspot' },
585
- { name: 'Slack - Team communication', value: 'slack' },
586
- { name: 'Google Sheets - Spreadsheet integration', value: 'google-sheets' },
587
- { name: 'Stripe - Payment processing', value: 'stripe' },
588
- { name: 'Airtable - Database integration', value: 'airtable' },
589
- { name: 'Mailchimp - Email marketing', value: 'mailchimp' },
590
- { name: 'Zendesk - Customer support', value: 'zendesk' }
591
- ],
592
- instructions: '\n Press <space> to select, <a> to toggle all, <enter> to confirm\n'
593
- });
594
- }
595
-
596
- /**
597
- * Update index.js with selected integrations
598
- */
599
- async updateAppDefinition(integrations) {
600
- const appDefPath = path.join(this.targetPath, 'index.js');
601
- if (await fs.pathExists(appDefPath)) {
602
- let content = await fs.readFile(appDefPath, 'utf8');
603
-
604
- // Add import statements for selected integrations
605
- const importStatements = integrations.map(name => {
606
- const className = this.getIntegrationClassName(name);
607
- return `const ${className} = require('./src/integrations/${className}');`;
608
- }).join('\n');
609
-
610
- // Add imports after the existing comment block
611
- content = content.replace(
612
- '// Import your integrations here\n// const ExampleIntegration = require(\'./src/integrations/ExampleIntegration\');',
613
- `// Import your integrations here\n${importStatements}`
500
+ if (!definition) {
501
+ console.log(
502
+ chalk.yellow(
503
+ `⚠️ ${path.basename(
504
+ appDefPath
505
+ )} does not export a Definition`
506
+ )
614
507
  );
615
-
616
- // Add integrations to the array
617
- const integrationList = integrations.map(name => {
618
- const className = this.getIntegrationClassName(name);
619
- return ` ${className},`;
620
- }).join('\n');
621
-
622
- content = content.replace(
623
- ' // Add your integrations here as you install them\n // Example:\n // ExampleIntegration,',
624
- ` // Selected integrations\n${integrationList}`
625
- );
626
-
627
- await fs.writeFile(appDefPath, content);
508
+ return false;
628
509
  }
629
- }
630
-
631
- /**
632
- * Get integration class name from module name
633
- */
634
- getIntegrationClassName(moduleName) {
635
- const classNames = {
636
- 'salesforce': 'SalesforceIntegration',
637
- 'hubspot': 'HubSpotIntegration',
638
- 'slack': 'SlackIntegration',
639
- 'google-sheets': 'GoogleSheetsIntegration',
640
- 'stripe': 'StripeIntegration',
641
- 'airtable': 'AirtableIntegration',
642
- 'mailchimp': 'MailchimpIntegration',
643
- 'zendesk': 'ZendeskIntegration'
644
- };
645
-
646
- return classNames[moduleName] || `${moduleName.charAt(0).toUpperCase() + moduleName.slice(1)}Integration`;
647
- }
648
-
649
- /**
650
- * Validate generated app definition against schema
651
- */
652
- async validateGeneratedAppDefinition(appDefPath) {
653
- try {
654
- if (this.options.verbose) {
655
- console.log(chalk.gray('🔍 Validating app definition against schema...'));
656
- }
657
510
 
658
- // Read the generated index.js file
659
- const content = await fs.readFile(appDefPath, 'utf8');
660
-
661
- // Extract the appDefinition object (simplified approach)
662
- // In a real scenario, we might use AST parsing for more robust extraction
663
- const appDefinitionMatch = content.match(/const appDefinition = ({[\s\S]*?});/);
664
- if (!appDefinitionMatch) {
665
- throw new Error('Could not extract appDefinition from generated file');
666
- }
511
+ const result = validateAppDefinition(definition);
512
+ if (!result.valid) {
513
+ console.log(
514
+ chalk.yellow('⚠️ App definition has validation warnings:')
515
+ );
516
+ console.log(chalk.gray(formatErrors(result.errors)));
517
+ return false;
518
+ }
667
519
 
668
- // Create a minimal representation for validation
669
- // Since we can't easily execute the file, we'll validate the structure we know we generated
670
- const appDefinition = {
671
- integrations: [], // Will be populated based on selected integrations
672
- user: { password: true },
673
- encryption: { fieldLevelEncryptionMethod: 'kms' },
674
- vpc: { enable: true },
675
- security: {
676
- cors: {
677
- origin: 'http://localhost:3000',
678
- credentials: true
679
- }
680
- },
681
- logging: { level: 'info', retentionInDays: 30 },
682
- custom: {
683
- appName: 'My Frigg Application',
684
- version: '1.0.0',
685
- environment: 'development'
686
- }
687
- };
688
-
689
- // Validate against schema
690
- const result = validateAppDefinition(appDefinition);
691
-
692
- if (result.valid) {
693
- if (this.options.verbose) {
694
- console.log(chalk.green('✅ App definition passes schema validation'));
695
- }
696
- return true;
697
- } else {
698
- console.log(chalk.yellow('⚠️ App definition has validation warnings:'));
699
- console.log(chalk.gray(formatErrors(result.errors)));
700
- return false;
701
- }
702
- } catch (error) {
703
- if (this.options.verbose) {
704
- console.log(chalk.yellow(`⚠️ Schema validation skipped: ${error.message}`));
705
- }
706
- return true; // Don't fail the process for validation issues
520
+ if (this.options.verbose) {
521
+ console.log(
522
+ chalk.green('✅ App definition passes schema validation')
523
+ );
707
524
  }
525
+ return true;
708
526
  }
709
527
 
710
528
  /**
711
529
  * Display next steps
712
530
  */
713
531
  displayNextSteps(deploymentMode, config) {
714
- const relativePath = path.relative(process.cwd(), this.targetPath);
532
+ const relativePath = path.relative(process.cwd(), this.projectDir);
715
533
  const cdPath = relativePath || '.';
534
+ let step = 1;
535
+ const printStep = (text, command) => {
536
+ console.log(`${step}. ${text}`);
537
+ console.log(chalk.cyan(` ${command}\n`));
538
+ step += 1;
539
+ };
716
540
 
717
541
  console.log(chalk.bold('\n📋 Next Steps:\n'));
718
542
 
719
- console.log(`1. Navigate to your project:`);
720
- console.log(chalk.cyan(` cd ${cdPath}\n`));
721
-
722
- if (deploymentMode === 'standalone') {
723
- console.log(`2. Start the development server:`);
724
- console.log(chalk.cyan(` npm start\n`));
543
+ printStep('Navigate to your project:', `cd ${cdPath}`);
725
544
 
726
- console.log(`3. Open the Frigg UI for development:`);
727
- console.log(chalk.cyan(` frigg ui\n`));
545
+ if (!config.dependenciesInstalled) {
546
+ printStep('Install dependencies:', 'npm install');
547
+ }
728
548
 
729
- if (config.serverlessProvider === 'aws') {
730
- console.log(`4. Deploy to AWS Lambda:`);
731
- console.log(chalk.cyan(` npm run deploy\n`));
732
- }
549
+ printStep(
550
+ 'Start PostgreSQL and check DATABASE_URL in .env:',
551
+ 'docker run --name frigg-postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 -d postgres:16'
552
+ );
553
+ printStep('Set up the database:', 'npm run db:setup');
554
+ printStep('Start the development server:', 'npm start');
555
+
556
+ const integrations = config.starterIntegrations || [];
557
+ if (integrations.length > 0) {
558
+ printStep(
559
+ 'Install the API modules you selected (each adds src/integrations/<Name>Integration.js and lists it in index.js):',
560
+ integrations
561
+ .map((name) => `npx frigg install ${name}`)
562
+ .join('\n ')
563
+ );
733
564
  } else {
734
- console.log(`2. Follow the integration guide:`);
735
- console.log(chalk.cyan(` cat FRIGG_INTEGRATION.md\n`));
736
-
737
- console.log(`3. Install Frigg in your main project:`);
738
- console.log(chalk.cyan(` npm install @friggframework/core\n`));
565
+ printStep(
566
+ 'Add an integration from the API module library (adds src/integrations/<Name>Integration.js and lists it in index.js):',
567
+ 'npx frigg install <module> # e.g. npx frigg install hubspot'
568
+ );
569
+ }
739
570
 
740
- console.log(`4. Use Frigg UI for development:`);
741
- console.log(chalk.cyan(` frigg ui\n`));
571
+ if (config.serverlessProvider === 'aws') {
572
+ printStep(
573
+ 'Deploy to AWS Lambda with a hosted PostgreSQL (DATABASE_URL comes from your shell, not .env; see README.md):',
574
+ "DATABASE_URL='postgresql://...?sslmode=require' npm run deploy -- --stage prod"
575
+ );
742
576
  }
743
577
 
744
- if (config.includeDemoFrontend) {
745
- console.log(chalk.yellow('\n⚠️ Demo Frontend:'));
746
- console.log(chalk.gray(' The included frontend is for demonstration only.'));
747
- console.log(chalk.gray(' See frontend/README.md for integration guidance.'));
578
+ if (config.needsCustomApiModule) {
579
+ console.log(
580
+ chalk.gray(
581
+ 'To build an API module for your own application, see https://docs.friggframework.org (API modules).'
582
+ )
583
+ );
748
584
  }
749
585
 
750
586
  console.log(chalk.green('\n🎉 Happy integrating with Frigg!\n'));
751
- console.log(chalk.gray('Documentation: https://docs.frigg.dev'));
752
- console.log(chalk.gray('Support: https://github.com/friggframework/frigg/issues'));
587
+ console.log(
588
+ chalk.gray('Documentation: https://docs.friggframework.org')
589
+ );
590
+ console.log(
591
+ chalk.gray(
592
+ 'Support: https://github.com/friggframework/frigg/issues'
593
+ )
594
+ );
753
595
  }
754
596
  }
755
597
 
756
- module.exports = BackendFirstHandler;
598
+ module.exports = BackendFirstHandler;
599
+ module.exports.EMBEDDED_DIR = EMBEDDED_DIR;