@friggframework/devtools 2.0.0--canary.666.abcf913.0 → 2.0.0--canary.701.3b01ea3.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.
package/README.md CHANGED
@@ -23,6 +23,7 @@ The Frigg CLI is a command-line interface tool that helps developers manage and
23
23
  - Automatically update project files
24
24
  - Handle environment variables
25
25
  - Validate package existence and backend paths
26
+ - Validate an API module Definition with `frigg validate --module` (or `frigg validate module`)
26
27
  - Run your Frigg instance locally
27
28
  - Deploy your Frigg application to your configured provider
28
29
 
@@ -159,21 +159,29 @@ Found 5 modules matching "crm"
159
159
 
160
160
  #### `frigg validate [options]`
161
161
 
162
- Validate the app definition (`index.js`) before you build or deploy it (ADR-051).
162
+ Validate the app definition (`index.js`) before you build or deploy it (ADR-051), or validate an API module Definition from a module directory.
163
163
 
164
164
  **Usage:**
165
165
  ```bash
166
- frigg validate # schema + runtime checks
166
+ frigg validate # schema + runtime checks (app mode)
167
167
  frigg validate --stage prod # also the stage checks (encryption, deploy-time environment)
168
168
  frigg validate --json # machine-readable report for CI
169
+ frigg validate --module # API module mode (from the module directory)
170
+ frigg validate module # same as --module
169
171
  ```
170
172
 
171
- **What it does:**
173
+ **What it does (app mode):**
172
174
  1. Loads `index.js` the way `frigg build` does (current directory, or the nearest `backend/`)
173
175
  2. Validates it against the app-definition schema: unknown keys (with "did you mean"), types, and the values the infrastructure builders accept
174
176
  3. Checks what the schema cannot: integration classes (static `Definition` with a valid, unique `name`, `version`, `modules`, and API module definitions that pass core's checks), an enabled database, management settings that conflict or lack ids, encryption (`aes` keys in `environment`, KMS key source, stages that never encrypt), a user config with which login works, `'ssm'` entries without `ssm.enable`, and keys that have no effect
175
177
  4. Prints each problem with its JSON pointer and a fix; exits `1` when there are errors
176
178
 
179
+ **What it does (module mode):**
180
+ 1. Loads `{ Definition }` from `./index.js` in the current directory
181
+ 2. Validates it with `validateApiModuleDefinition` (api-module-definition schema)
182
+ 3. Runs the structural checks from `checkModuleDefinition` (API class, required auth methods as functions)
183
+ 4. Supports `--json` and `-v` like app mode; exits `1` listing JSON field paths on failure
184
+
177
185
  **Example output:**
178
186
  ```
179
187
  Validating /path/to/backend/index.js (stage: prod)
@@ -118,12 +118,18 @@ program
118
118
  .action(startCommand);
119
119
 
120
120
  program
121
- .command('validate')
122
- .description('Validate the app definition (index.js) against the schema and the runtime rules')
121
+ .command('validate [target]')
122
+ .description(
123
+ 'Validate the app definition (index.js), or an API module Definition with --module / module'
124
+ )
125
+ .option(
126
+ '--module',
127
+ 'validate an API module Definition in the current directory (also: frigg validate module)'
128
+ )
123
129
  .option('-s, --stage <stage>', 'also run the checks for this stage (encryption, deploy-time environment)')
124
130
  .option('--json', 'print the report as JSON')
125
131
  .option('-v, --verbose', 'enable verbose output')
126
- .action(validateCommand);
132
+ .action((target, options) => validateCommand({ ...options, target }));
127
133
 
128
134
  program
129
135
  .command('build')
@@ -0,0 +1,119 @@
1
+ const fs = require('fs');
2
+ const os = require('os');
3
+ const path = require('path');
4
+
5
+ const {
6
+ validateCommand,
7
+ runModuleValidation,
8
+ } = require('..');
9
+
10
+ const FIXTURES = path.join(__dirname, '..', 'fixtures');
11
+ const FATHOM_DIR = path.join(FIXTURES, 'fathom-module');
12
+ const BAD_DIR = path.join(FIXTURES, 'bad-module');
13
+
14
+ describe('frigg validate --module', () => {
15
+ let log;
16
+ let cwdSpy;
17
+
18
+ beforeEach(() => {
19
+ log = jest.spyOn(console, 'log').mockImplementation(() => {});
20
+ process.exitCode = undefined;
21
+ });
22
+
23
+ afterEach(() => {
24
+ jest.restoreAllMocks();
25
+ process.exitCode = undefined;
26
+ });
27
+
28
+ const inDir = (dir) => {
29
+ cwdSpy = jest.spyOn(process, 'cwd').mockReturnValue(dir);
30
+ return dir;
31
+ };
32
+
33
+ it('passes the Fathom fixture with --module', async () => {
34
+ inDir(FATHOM_DIR);
35
+
36
+ const report = await validateCommand({ module: true });
37
+
38
+ expect(report.errors).toEqual([]);
39
+ expect(process.exitCode).toBeUndefined();
40
+ expect(report.source).toBe(path.join(FATHOM_DIR, 'index.js'));
41
+ });
42
+
43
+ it('passes when target is "module" (frigg validate module)', async () => {
44
+ inDir(FATHOM_DIR);
45
+
46
+ const report = await validateCommand({ target: 'module' });
47
+
48
+ expect(report.errors).toEqual([]);
49
+ expect(process.exitCode).toBeUndefined();
50
+ });
51
+
52
+ it('fails the bad fixture listing JSON field paths', async () => {
53
+ inDir(BAD_DIR);
54
+
55
+ const report = await validateCommand({ module: true });
56
+ const output = log.mock.calls.flat().join('\n');
57
+ const pointers = report.errors.map((e) => e.pointer);
58
+
59
+ expect(process.exitCode).toBe(1);
60
+ expect(pointers).toEqual(
61
+ expect.arrayContaining([
62
+ '/notARealField',
63
+ '/moduleName',
64
+ '/getName',
65
+ '/requiredAuthMethods/getEntityDetails',
66
+ '/requiredAuthMethods/getCredentialDetails',
67
+ '/requiredAuthMethods/testAuthRequest',
68
+ '/requiredAuthMethods/apiPropertiesToPersist',
69
+ ])
70
+ );
71
+ expect(output).toContain('/notARealField');
72
+ expect(output).toContain('/moduleName');
73
+ });
74
+
75
+ it('--json prints a machine-readable report for module mode', async () => {
76
+ inDir(BAD_DIR);
77
+
78
+ await validateCommand({ module: true, json: true });
79
+ const json = JSON.parse(log.mock.calls[0][0]);
80
+
81
+ expect(json).toEqual(
82
+ expect.objectContaining({
83
+ valid: false,
84
+ source: path.join(BAD_DIR, 'index.js'),
85
+ errors: expect.arrayContaining([
86
+ expect.objectContaining({
87
+ pointer: '/notARealField',
88
+ code: 'unknown-key',
89
+ severity: 'error',
90
+ }),
91
+ ]),
92
+ })
93
+ );
94
+ });
95
+
96
+ it('runModuleValidation reports a missing index.js', () => {
97
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'frigg-mod-'));
98
+ try {
99
+ expect(runModuleValidation({ cwd: dir }).errors).toEqual([
100
+ expect.objectContaining({ code: 'module-index-not-found' }),
101
+ ]);
102
+ } finally {
103
+ fs.rmSync(dir, { recursive: true, force: true });
104
+ }
105
+ });
106
+
107
+ it('does not change app-mode when --module is absent', async () => {
108
+ // No backend in Fathom fixture dir: app mode should fail to find a backend.
109
+ inDir(FATHOM_DIR);
110
+
111
+ const report = await validateCommand({});
112
+
113
+ expect(report.errors).toEqual([
114
+ expect.objectContaining({ code: 'backend-not-found' }),
115
+ ]);
116
+ expect(process.exitCode).toBe(1);
117
+ expect(cwdSpy).toHaveBeenCalled();
118
+ });
119
+ });
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Intentionally invalid API module for frigg validate --module fail tests.
3
+ */
4
+ class BadApi {}
5
+
6
+ module.exports = {
7
+ Api: BadApi,
8
+ Definition: {
9
+ // missing moduleName, getName; unknown top-level key; auth methods incomplete
10
+ API: BadApi,
11
+ modelName: 'Bad',
12
+ notARealField: true,
13
+ requiredAuthMethods: {
14
+ // missing getEntityDetails, getCredentialDetails, testAuthRequest, apiPropertiesToPersist
15
+ getAuthorizationRequirements: () => ({ type: 'apiKey' }),
16
+ },
17
+ },
18
+ };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Fixture reproducing the Fathom API module Definition from
3
+ * friggframework/api-module-library `next`, packages/v1-ready/fathom.
4
+ */
5
+
6
+ class FathomApi {
7
+ static requesterType = 'apiKey';
8
+
9
+ setApiKey(apiKey) {
10
+ this.api_key = apiKey;
11
+ }
12
+
13
+ async listMeetings() {
14
+ return { items: [] };
15
+ }
16
+ }
17
+
18
+ const Definition = {
19
+ API: FathomApi,
20
+ getName: () => 'fathom',
21
+ moduleName: 'fathom',
22
+ modelName: 'Fathom',
23
+ requiredAuthMethods: {
24
+ getAuthorizationRequirements: () => ({
25
+ type: 'apiKey',
26
+ data: {
27
+ jsonSchema: {
28
+ title: 'Fathom Authentication',
29
+ type: 'object',
30
+ required: ['api_key'],
31
+ properties: {
32
+ api_key: {
33
+ type: 'string',
34
+ title: 'API Key',
35
+ },
36
+ },
37
+ },
38
+ uiSchema: {
39
+ api_key: {
40
+ 'ui:widget': 'password',
41
+ 'ui:help':
42
+ 'Generate an API key in Fathom under User Settings > API Access. Sent as the X-Api-Key header.',
43
+ },
44
+ },
45
+ },
46
+ }),
47
+ setAuthParams: async (api, params) => {
48
+ const apiKey = params?.api_key || params?.access_token || null;
49
+ api.setApiKey(apiKey);
50
+ },
51
+ getEntityDetails: async (api, callbackParams, tokenResponse, userId) => {
52
+ return {
53
+ identifiers: { externalId: 'fixture@example.com', userId },
54
+ details: { name: 'Fathom' },
55
+ };
56
+ },
57
+ getCredentialDetails: async (api, userId) => {
58
+ return {
59
+ identifiers: { externalId: 'fixture@example.com', userId },
60
+ details: {},
61
+ };
62
+ },
63
+ apiPropertiesToPersist: {
64
+ credential: ['api_key'],
65
+ entity: [],
66
+ },
67
+ testAuthRequest: async (api) => {
68
+ return api.listMeetings({});
69
+ },
70
+ },
71
+ env: {
72
+ api_key: 'test-fathom-api-key',
73
+ },
74
+ };
75
+
76
+ module.exports = { Definition, Api: FathomApi };
@@ -0,0 +1,6 @@
1
+ const { Api, Definition } = require('./definition');
2
+
3
+ module.exports = {
4
+ Api,
5
+ Definition,
6
+ };
@@ -21,15 +21,17 @@ function formatIssue(issue) {
21
21
  */
22
22
  function formatReport(report) {
23
23
  const { errors, warnings, source, stage } = report;
24
+ const noun =
25
+ report.kind === 'module' ? 'module definition' : 'app definition';
24
26
  const lines = [];
25
- const header = `Validating ${source || 'the app definition'}${
27
+ const header = `Validating ${source || `the ${noun}`}${
26
28
  stage ? ` (stage: ${stage})` : ''
27
29
  }`;
28
30
  lines.push(chalk.bold(header));
29
31
  for (const issue of errors) lines.push(formatIssue(issue));
30
32
  for (const issue of warnings) lines.push(formatIssue(issue));
31
33
  if (errors.length === 0 && warnings.length === 0) {
32
- lines.push(chalk.green(' ✓ The app definition is valid.'));
34
+ lines.push(chalk.green(` ✓ The ${noun} is valid.`));
33
35
  } else {
34
36
  const summary = `${errors.length} error(s), ${warnings.length} warning(s)`;
35
37
  lines.push(
@@ -1,11 +1,16 @@
1
1
  /**
2
2
  * `frigg validate` and the validation step that `frigg build`, `frigg deploy`,
3
3
  * `frigg start` and `frigg init` run first (ADR-051).
4
+ *
5
+ * Module mode (`frigg validate --module` / `frigg validate module`) validates
6
+ * an API module Definition in the current directory; app mode is unchanged.
4
7
  */
5
8
 
6
9
  const chalk = require('chalk');
7
10
  const { loadAppDefinition } = require('./load-app-definition');
11
+ const { loadModuleDefinition } = require('./load-module-definition');
8
12
  const { validateDefinition } = require('./validate-app-definition');
13
+ const { validateModuleDefinition } = require('./validate-module-definition');
9
14
  const { formatReport, toJsonReport } = require('./format-report');
10
15
 
11
16
  /**
@@ -31,10 +36,33 @@ function runValidation({ cwd = process.cwd(), stage, env = process.env } = {}) {
31
36
  }
32
37
 
33
38
  /**
34
- * `frigg validate [--json] [--stage <stage>]`. Exits non-zero on errors.
39
+ * Load an API module Definition from `./index.js` and validate it.
40
+ *
41
+ * @param {object} [params]
42
+ * @param {string} [params.cwd]
43
+ * @returns {{ errors: object[], warnings: object[], source: string }}
35
44
  */
36
- async function validateCommand(options = {}) {
37
- const report = runValidation({ stage: options.stage });
45
+ function runModuleValidation({ cwd = process.cwd() } = {}) {
46
+ const loaded = loadModuleDefinition({ cwd });
47
+ if (!loaded.ok) {
48
+ return { errors: [loaded.issue], warnings: [], source: cwd };
49
+ }
50
+ const { errors, warnings } = validateModuleDefinition({
51
+ definition: loaded.definition,
52
+ });
53
+ return { errors, warnings, source: loaded.indexPath, kind: 'module' };
54
+ }
55
+
56
+ function isModuleMode(options = {}) {
57
+ return Boolean(options.module) || options.target === 'module';
58
+ }
59
+
60
+ /**
61
+ * Print a validation report and set exitCode on errors.
62
+ * @param {object} report
63
+ * @param {object} options
64
+ */
65
+ function printReport(report, options = {}) {
38
66
  if (options.json) {
39
67
  console.log(JSON.stringify(toJsonReport(report), null, 2));
40
68
  } else {
@@ -45,6 +73,17 @@ async function validateCommand(options = {}) {
45
73
  if (report.errors.length > 0) {
46
74
  process.exitCode = 1;
47
75
  }
76
+ }
77
+
78
+ /**
79
+ * `frigg validate [--module] [module] [--json] [--stage <stage>]`.
80
+ * Exits non-zero on errors. Module mode does not change app-mode behavior.
81
+ */
82
+ async function validateCommand(options = {}) {
83
+ const report = isModuleMode(options)
84
+ ? runModuleValidation({})
85
+ : runValidation({ stage: options.stage });
86
+ printReport(report, options);
48
87
  return report;
49
88
  }
50
89
 
@@ -104,4 +143,9 @@ function preflightValidation({ command, options = {}, failOnErrors }) {
104
143
  return true;
105
144
  }
106
145
 
107
- module.exports = { validateCommand, runValidation, preflightValidation };
146
+ module.exports = {
147
+ validateCommand,
148
+ runValidation,
149
+ runModuleValidation,
150
+ preflightValidation,
151
+ };
@@ -0,0 +1,64 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ /**
5
+ * Load the `Definition` exported by an API module's `./index.js`
6
+ * (`{ Api, Definition }`). Used by `frigg validate --module`.
7
+ *
8
+ * @param {object} [params]
9
+ * @param {string} [params.cwd]
10
+ * @returns {{ ok: true, definition: object, indexPath: string }
11
+ * | { ok: false, issue: object }}
12
+ */
13
+ function loadModuleDefinition({ cwd = process.cwd() } = {}) {
14
+ const indexPath = path.join(cwd, 'index.js');
15
+ if (!fs.existsSync(indexPath)) {
16
+ return {
17
+ ok: false,
18
+ issue: {
19
+ severity: 'error',
20
+ code: 'module-index-not-found',
21
+ pointer: '',
22
+ message: `No API module index.js found at ${indexPath}.`,
23
+ hint: 'Run `frigg validate --module` from the module directory (the one that exports `{ Api, Definition }`).',
24
+ },
25
+ };
26
+ }
27
+
28
+ let mod;
29
+ try {
30
+ const resolved = require.resolve(indexPath);
31
+ delete require.cache[resolved];
32
+ mod = require(indexPath);
33
+ } catch (error) {
34
+ return {
35
+ ok: false,
36
+ issue: {
37
+ severity: 'error',
38
+ code: 'load-failed',
39
+ pointer: '',
40
+ message: `${indexPath} failed to load: ${error.message}`,
41
+ hint: 'Fix the error above; the module must load cleanly.',
42
+ stack: error.stack,
43
+ },
44
+ };
45
+ }
46
+
47
+ const definition = mod && mod.Definition;
48
+ if (!definition || typeof definition !== 'object') {
49
+ return {
50
+ ok: false,
51
+ issue: {
52
+ severity: 'error',
53
+ code: 'definition-not-exported',
54
+ pointer: '',
55
+ message: `${indexPath} does not export a Definition object.`,
56
+ hint: 'Export `{ Api, Definition }` from index.js.',
57
+ },
58
+ };
59
+ }
60
+
61
+ return { ok: true, definition, indexPath };
62
+ }
63
+
64
+ module.exports = { loadModuleDefinition };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Validate an API module Definition: the JSON Schema plus the structural
3
+ * checks `checkModuleDefinition` runs for modules listed on an app
4
+ * (ADR-051). Pure: no I/O.
5
+ */
6
+
7
+ const {
8
+ validateApiModuleDefinition,
9
+ getSchema,
10
+ } = require('@friggframework/schemas');
11
+ const { schemaErrorsToIssues } = require('./schema-issues');
12
+ const { checkModuleDefinition } = require('./checks/integrations');
13
+
14
+ /**
15
+ * @param {object} params
16
+ * @param {object} params.definition the `Definition` exported by the module
17
+ * @returns {{ errors: object[], warnings: object[] }}
18
+ */
19
+ function validateModuleDefinition({ definition }) {
20
+ const schemaResult = validateApiModuleDefinition(definition);
21
+ const issues = schemaErrorsToIssues(
22
+ schemaResult.errors,
23
+ getSchema('api-module-definition')
24
+ );
25
+
26
+ const structural =
27
+ definition && typeof definition === 'object'
28
+ ? checkModuleDefinition(definition, '')
29
+ : [];
30
+
31
+ const seen = new Set(issues.map((i) => `${i.code}:${i.pointer}`));
32
+ for (const issue of structural) {
33
+ const key = `${issue.code}:${issue.pointer}`;
34
+ if (!seen.has(key)) {
35
+ seen.add(key);
36
+ issues.push(issue);
37
+ }
38
+ }
39
+
40
+ return {
41
+ errors: issues.filter((i) => i.severity === 'error'),
42
+ warnings: issues.filter((i) => i.severity !== 'error'),
43
+ };
44
+ }
45
+
46
+ module.exports = { validateModuleDefinition };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/devtools",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.666.abcf913.0",
4
+ "version": "2.0.0--canary.701.3b01ea3.0",
5
5
  "bin": {
6
6
  "frigg": "./frigg-cli/index.js"
7
7
  },
@@ -28,9 +28,9 @@
28
28
  "@babel/eslint-parser": "^7.18.9",
29
29
  "@babel/parser": "^7.25.3",
30
30
  "@babel/traverse": "^7.25.3",
31
- "@friggframework/core": "2.0.0--canary.666.abcf913.0",
32
- "@friggframework/schemas": "2.0.0--canary.666.abcf913.0",
33
- "@friggframework/test": "2.0.0--canary.666.abcf913.0",
31
+ "@friggframework/core": "2.0.0--canary.701.3b01ea3.0",
32
+ "@friggframework/schemas": "2.0.0--canary.701.3b01ea3.0",
33
+ "@friggframework/test": "2.0.0--canary.701.3b01ea3.0",
34
34
  "@hapi/boom": "^10.0.1",
35
35
  "@inquirer/prompts": "^5.3.8",
36
36
  "axios": "^1.18.0",
@@ -58,8 +58,8 @@
58
58
  "validate-npm-package-name": "^5.0.0"
59
59
  },
60
60
  "devDependencies": {
61
- "@friggframework/eslint-config": "2.0.0--canary.666.abcf913.0",
62
- "@friggframework/prettier-config": "2.0.0--canary.666.abcf913.0",
61
+ "@friggframework/eslint-config": "2.0.0--canary.701.3b01ea3.0",
62
+ "@friggframework/prettier-config": "2.0.0--canary.701.3b01ea3.0",
63
63
  "aws-sdk-client-mock": "^4.1.0",
64
64
  "aws-sdk-client-mock-jest": "^4.1.0",
65
65
  "jest": "^30.1.3",
@@ -91,5 +91,5 @@
91
91
  "publishConfig": {
92
92
  "access": "public"
93
93
  },
94
- "gitHead": "abcf913cf7580597fd286b2f5b93d3ccf4609ef6"
94
+ "gitHead": "3b01ea3abd65f1771e9bb1f143168da6acff4125"
95
95
  }