@friggframework/devtools 2.0.0--canary.702.d5e6de1.0 → 2.0.0--canary.666.abcf913.0

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