@aifabrix/builder 2.1.6 → 2.2.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 (38) hide show
  1. package/lib/app-deploy.js +73 -29
  2. package/lib/app-list.js +132 -0
  3. package/lib/app-readme.js +11 -4
  4. package/lib/app-register.js +435 -0
  5. package/lib/app-rotate-secret.js +164 -0
  6. package/lib/app-run.js +98 -84
  7. package/lib/app.js +13 -0
  8. package/lib/audit-logger.js +195 -15
  9. package/lib/build.js +57 -37
  10. package/lib/cli.js +90 -8
  11. package/lib/commands/app.js +8 -391
  12. package/lib/commands/login.js +130 -36
  13. package/lib/config.js +257 -4
  14. package/lib/deployer.js +221 -183
  15. package/lib/infra.js +177 -112
  16. package/lib/secrets.js +85 -99
  17. package/lib/utils/api-error-handler.js +465 -0
  18. package/lib/utils/api.js +165 -16
  19. package/lib/utils/auth-headers.js +84 -0
  20. package/lib/utils/build-copy.js +144 -0
  21. package/lib/utils/cli-utils.js +21 -0
  22. package/lib/utils/compose-generator.js +43 -14
  23. package/lib/utils/deployment-errors.js +90 -0
  24. package/lib/utils/deployment-validation.js +60 -0
  25. package/lib/utils/dev-config.js +83 -0
  26. package/lib/utils/env-template.js +30 -10
  27. package/lib/utils/health-check.js +18 -1
  28. package/lib/utils/infra-containers.js +101 -0
  29. package/lib/utils/local-secrets.js +0 -2
  30. package/lib/utils/secrets-path.js +18 -21
  31. package/lib/utils/secrets-utils.js +206 -0
  32. package/lib/utils/token-manager.js +381 -0
  33. package/package.json +1 -1
  34. package/templates/applications/README.md.hbs +155 -23
  35. package/templates/applications/miso-controller/Dockerfile +7 -119
  36. package/templates/infra/compose.yaml.hbs +93 -0
  37. package/templates/python/docker-compose.hbs +25 -17
  38. package/templates/typescript/docker-compose.hbs +25 -17
@@ -0,0 +1,465 @@
1
+ /**
2
+ * AI Fabrix Builder API Error Handler
3
+ *
4
+ * Parses and formats structured error responses from the controller API
5
+ * Handles permission errors, validation errors, authentication errors,
6
+ * network errors, and server errors with user-friendly formatting
7
+ *
8
+ * @fileoverview API error handling utilities for AI Fabrix Builder
9
+ * @author AI Fabrix Team
10
+ * @version 2.0.0
11
+ */
12
+
13
+ const chalk = require('chalk');
14
+
15
+ /**
16
+ * Formats permission error with missing and required permissions
17
+ * @param {Object} errorData - Error response data
18
+ * @returns {string} Formatted permission error message
19
+ */
20
+ function formatPermissionError(errorData) {
21
+ const lines = [];
22
+ lines.push(chalk.red('❌ Permission Denied\n'));
23
+
24
+ // Handle detail message if present
25
+ if (errorData.detail) {
26
+ lines.push(chalk.yellow(errorData.detail));
27
+ lines.push('');
28
+ }
29
+
30
+ // Extract missing permissions (support both flat and nested structures)
31
+ let missingPerms = [];
32
+ if (errorData.missingPermissions && Array.isArray(errorData.missingPermissions)) {
33
+ missingPerms = errorData.missingPermissions;
34
+ } else if (errorData.missing && errorData.missing.permissions && Array.isArray(errorData.missing.permissions)) {
35
+ missingPerms = errorData.missing.permissions;
36
+ }
37
+
38
+ if (missingPerms.length > 0) {
39
+ lines.push(chalk.yellow('Missing permissions:'));
40
+ missingPerms.forEach(perm => {
41
+ lines.push(chalk.gray(` - ${perm}`));
42
+ });
43
+ lines.push('');
44
+ }
45
+
46
+ // Extract required permissions (support both flat and nested structures)
47
+ let requiredPerms = [];
48
+ if (errorData.requiredPermissions && Array.isArray(errorData.requiredPermissions)) {
49
+ requiredPerms = errorData.requiredPermissions;
50
+ } else if (errorData.required && errorData.required.permissions && Array.isArray(errorData.required.permissions)) {
51
+ requiredPerms = errorData.required.permissions;
52
+ }
53
+
54
+ if (requiredPerms.length > 0) {
55
+ lines.push(chalk.yellow('Required permissions:'));
56
+ requiredPerms.forEach(perm => {
57
+ lines.push(chalk.gray(` - ${perm}`));
58
+ });
59
+ lines.push('');
60
+ }
61
+
62
+ // Use instance (from RFC 7807) or url field
63
+ const requestUrl = errorData.instance || errorData.url;
64
+ const method = errorData.method || 'POST';
65
+ if (requestUrl) {
66
+ lines.push(chalk.gray(`Request: ${method} ${requestUrl}`));
67
+ }
68
+
69
+ if (errorData.correlationId) {
70
+ lines.push(chalk.gray(`Correlation ID: ${errorData.correlationId}`));
71
+ }
72
+
73
+ return lines.join('\n');
74
+ }
75
+
76
+ /**
77
+ * Formats validation error with field-level details
78
+ * Handles unified error API response format (RFC 7807 Problem Details)
79
+ * @param {Object} errorData - Error response data
80
+ * @returns {string} Formatted validation error message
81
+ */
82
+ function formatValidationError(errorData) {
83
+ const lines = [];
84
+ lines.push(chalk.red('❌ Validation Error\n'));
85
+
86
+ // Handle RFC 7807 Problem Details format
87
+ // Priority: detail > title > message
88
+ if (errorData.detail) {
89
+ lines.push(chalk.yellow(errorData.detail));
90
+ lines.push('');
91
+ } else if (errorData.title) {
92
+ lines.push(chalk.yellow(errorData.title));
93
+ lines.push('');
94
+ } else if (errorData.message) {
95
+ lines.push(chalk.yellow(errorData.message));
96
+ lines.push('');
97
+ }
98
+
99
+ // Handle errors array - this is the most important part
100
+ if (errorData.errors && Array.isArray(errorData.errors) && errorData.errors.length > 0) {
101
+ lines.push(chalk.yellow('Validation errors:'));
102
+ errorData.errors.forEach(err => {
103
+ const field = err.field || err.path || 'validation';
104
+ const message = err.message || 'Invalid value';
105
+ // If field is 'validation' or generic, just show the message
106
+ if (field === 'validation' || field === 'unknown') {
107
+ lines.push(chalk.gray(` • ${message}`));
108
+ } else {
109
+ lines.push(chalk.gray(` • ${field}: ${message}`));
110
+ }
111
+ });
112
+ lines.push('');
113
+ }
114
+
115
+ // Show instance (endpoint) if available (RFC 7807)
116
+ if (errorData.instance) {
117
+ lines.push(chalk.gray(`Endpoint: ${errorData.instance}`));
118
+ }
119
+
120
+ // Show correlation ID if available
121
+ if (errorData.correlationId) {
122
+ lines.push(chalk.gray(`Correlation ID: ${errorData.correlationId}`));
123
+ }
124
+
125
+ return lines.join('\n');
126
+ }
127
+
128
+ /**
129
+ * Formats authentication error
130
+ * @param {Object} errorData - Error response data
131
+ * @returns {string} Formatted authentication error message
132
+ */
133
+ function formatAuthenticationError(errorData) {
134
+ const lines = [];
135
+ lines.push(chalk.red('❌ Authentication Failed\n'));
136
+
137
+ if (errorData.message) {
138
+ lines.push(chalk.yellow(errorData.message));
139
+ } else {
140
+ lines.push(chalk.yellow('Invalid credentials or token expired.'));
141
+ }
142
+ lines.push('');
143
+ lines.push(chalk.gray('Run: aifabrix login'));
144
+
145
+ if (errorData.correlationId) {
146
+ lines.push(chalk.gray(`Correlation ID: ${errorData.correlationId}`));
147
+ }
148
+
149
+ return lines.join('\n');
150
+ }
151
+
152
+ /**
153
+ * Formats network error
154
+ * @param {string} errorMessage - Error message
155
+ * @param {Object} errorData - Error response data (optional)
156
+ * @returns {string} Formatted network error message
157
+ */
158
+ function formatNetworkError(errorMessage, errorData) {
159
+ const lines = [];
160
+ lines.push(chalk.red('❌ Network Error\n'));
161
+
162
+ if (errorMessage.includes('ECONNREFUSED') || errorMessage.includes('Cannot connect')) {
163
+ lines.push(chalk.yellow('Cannot connect to controller.'));
164
+ lines.push(chalk.gray('Check if the controller is running.'));
165
+ } else if (errorMessage.includes('ENOTFOUND') || errorMessage.includes('hostname not found')) {
166
+ lines.push(chalk.yellow('Controller hostname not found.'));
167
+ lines.push(chalk.gray('Check your controller URL.'));
168
+ } else if (errorMessage.includes('timeout') || errorMessage.includes('timed out')) {
169
+ lines.push(chalk.yellow('Request timed out.'));
170
+ lines.push(chalk.gray('The controller may be overloaded.'));
171
+ } else {
172
+ lines.push(chalk.yellow(errorMessage));
173
+ }
174
+
175
+ if (errorData && errorData.correlationId) {
176
+ lines.push(chalk.gray(`Correlation ID: ${errorData.correlationId}`));
177
+ }
178
+
179
+ return lines.join('\n');
180
+ }
181
+
182
+ /**
183
+ * Formats server error (500+)
184
+ * @param {Object} errorData - Error response data
185
+ * @returns {string} Formatted server error message
186
+ */
187
+ function formatServerError(errorData) {
188
+ const lines = [];
189
+ lines.push(chalk.red('❌ Server Error\n'));
190
+
191
+ // Check for RFC 7807 Problem Details format (detail field)
192
+ if (errorData.detail) {
193
+ lines.push(chalk.yellow(errorData.detail));
194
+ } else if (errorData.message) {
195
+ lines.push(chalk.yellow(errorData.message));
196
+ } else {
197
+ lines.push(chalk.yellow('An internal server error occurred.'));
198
+ }
199
+ lines.push('');
200
+ lines.push(chalk.gray('Please try again later or contact support.'));
201
+
202
+ if (errorData.correlationId) {
203
+ lines.push('');
204
+ lines.push(chalk.gray(`Correlation ID: ${errorData.correlationId}`));
205
+ }
206
+
207
+ return lines.join('\n');
208
+ }
209
+
210
+ /**
211
+ * Formats conflict error (409)
212
+ * @param {Object} errorData - Error response data
213
+ * @returns {string} Formatted conflict error message
214
+ */
215
+ function formatConflictError(errorData) {
216
+ const lines = [];
217
+ lines.push(chalk.red('❌ Conflict\n'));
218
+
219
+ // Check if it's an application already exists error
220
+ const detail = errorData.detail || errorData.message || '';
221
+ if (detail.toLowerCase().includes('application already exists')) {
222
+ lines.push(chalk.yellow('This application already exists in this environment.'));
223
+ lines.push('');
224
+ lines.push(chalk.gray('Options:'));
225
+ lines.push(chalk.gray(' • Use a different environment'));
226
+ lines.push(chalk.gray(' • Check existing applications: aifabrix app list -e <environment>'));
227
+ lines.push(chalk.gray(' • Update the existing application if needed'));
228
+ } else if (detail) {
229
+ lines.push(chalk.yellow(detail));
230
+ } else if (errorData.message) {
231
+ lines.push(chalk.yellow(errorData.message));
232
+ } else {
233
+ lines.push(chalk.yellow('A conflict occurred. The resource may already exist.'));
234
+ }
235
+
236
+ if (errorData.correlationId) {
237
+ lines.push('');
238
+ lines.push(chalk.gray(`Correlation ID: ${errorData.correlationId}`));
239
+ }
240
+
241
+ return lines.join('\n');
242
+ }
243
+
244
+ /**
245
+ * Formats not found error (404)
246
+ * @param {Object} errorData - Error response data
247
+ * @returns {string} Formatted not found error message
248
+ */
249
+ function formatNotFoundError(errorData) {
250
+ const lines = [];
251
+ lines.push(chalk.red('❌ Not Found\n'));
252
+
253
+ // Extract detail from RFC 7807 Problem Details format
254
+ const detail = errorData.detail || errorData.message || '';
255
+
256
+ if (detail) {
257
+ lines.push(chalk.yellow(detail));
258
+ lines.push('');
259
+ }
260
+
261
+ // Provide actionable guidance based on error context
262
+ if (detail.toLowerCase().includes('environment')) {
263
+ lines.push(chalk.gray('Options:'));
264
+ lines.push(chalk.gray(' • Check the environment key spelling'));
265
+ lines.push(chalk.gray(' • List available environments: aifabrix app list -e <environment>'));
266
+ lines.push(chalk.gray(' • Verify you have access to this environment'));
267
+ } else if (detail.toLowerCase().includes('application')) {
268
+ lines.push(chalk.gray('Options:'));
269
+ lines.push(chalk.gray(' • Check the application key spelling'));
270
+ lines.push(chalk.gray(' • List applications: aifabrix app list -e <environment>'));
271
+ lines.push(chalk.gray(' • Verify the application exists in this environment'));
272
+ } else {
273
+ lines.push(chalk.gray('Options:'));
274
+ lines.push(chalk.gray(' • Check the resource identifier'));
275
+ lines.push(chalk.gray(' • Verify the resource exists'));
276
+ lines.push(chalk.gray(' • Check your permissions'));
277
+ }
278
+
279
+ if (errorData.correlationId) {
280
+ lines.push('');
281
+ lines.push(chalk.gray(`Correlation ID: ${errorData.correlationId}`));
282
+ }
283
+
284
+ return lines.join('\n');
285
+ }
286
+
287
+ /**
288
+ * Formats generic error
289
+ * @param {Object} errorData - Error response data
290
+ * @param {number} statusCode - HTTP status code
291
+ * @returns {string} Formatted error message
292
+ */
293
+ function formatGenericError(errorData, statusCode) {
294
+ const lines = [];
295
+ lines.push(chalk.red(`❌ Error (HTTP ${statusCode})\n`));
296
+
297
+ // Check for RFC 7807 Problem Details format (detail field)
298
+ if (errorData.detail) {
299
+ lines.push(chalk.yellow(errorData.detail));
300
+ } else if (errorData.message) {
301
+ lines.push(chalk.yellow(errorData.message));
302
+ } else if (errorData.error) {
303
+ lines.push(chalk.yellow(errorData.error));
304
+ } else {
305
+ lines.push(chalk.yellow('An error occurred while processing your request.'));
306
+ }
307
+
308
+ if (errorData.correlationId) {
309
+ lines.push('');
310
+ lines.push(chalk.gray(`Correlation ID: ${errorData.correlationId}`));
311
+ }
312
+
313
+ return lines.join('\n');
314
+ }
315
+
316
+ /**
317
+ * Parses error response and determines error type
318
+ * @param {string|Object} errorResponse - Error response (string or parsed JSON)
319
+ * @param {number} statusCode - HTTP status code
320
+ * @param {boolean} isNetworkError - Whether this is a network error
321
+ * @returns {Object} Parsed error object with type, message, and formatted output
322
+ */
323
+ function parseErrorResponse(errorResponse, statusCode, isNetworkError) {
324
+ let errorData = {};
325
+
326
+ // Handle undefined or null error response
327
+ if (errorResponse === undefined || errorResponse === null) {
328
+ errorData = { message: 'Unknown error occurred' };
329
+ } else if (typeof errorResponse === 'string') {
330
+ // Parse error response
331
+ try {
332
+ errorData = JSON.parse(errorResponse);
333
+ } catch {
334
+ errorData = { message: errorResponse };
335
+ }
336
+ } else if (typeof errorResponse === 'object') {
337
+ errorData = errorResponse;
338
+ } else {
339
+ // Fallback for unexpected types
340
+ errorData = { message: String(errorResponse) };
341
+ }
342
+
343
+ // Handle nested response structure (some APIs wrap errors in data field)
344
+ if (errorData.data && typeof errorData.data === 'object') {
345
+ errorData = errorData.data;
346
+ }
347
+
348
+ // Handle network errors
349
+ if (isNetworkError) {
350
+ const errorMessage = errorData.message || errorResponse || 'Network error';
351
+ return {
352
+ type: 'network',
353
+ message: errorMessage,
354
+ formatted: formatNetworkError(errorMessage, errorData),
355
+ data: errorData
356
+ };
357
+ }
358
+
359
+ // Handle different HTTP status codes
360
+ if (statusCode === 403) {
361
+ // Permission error
362
+ return {
363
+ type: 'permission',
364
+ message: 'Permission denied',
365
+ formatted: formatPermissionError(errorData),
366
+ data: errorData
367
+ };
368
+ }
369
+
370
+ if (statusCode === 401) {
371
+ // Authentication error
372
+ return {
373
+ type: 'authentication',
374
+ message: 'Authentication failed',
375
+ formatted: formatAuthenticationError(errorData),
376
+ data: errorData
377
+ };
378
+ }
379
+
380
+ if (statusCode === 400) {
381
+ // Validation error
382
+ // Extract message from unified error format (RFC 7807)
383
+ const errorMessage = errorData.detail || errorData.title || errorData.message || 'Validation error';
384
+ return {
385
+ type: 'validation',
386
+ message: errorMessage,
387
+ formatted: formatValidationError(errorData),
388
+ data: errorData
389
+ };
390
+ }
391
+
392
+ if (statusCode === 404) {
393
+ // Not found error
394
+ return {
395
+ type: 'notfound',
396
+ message: errorData.detail || errorData.message || 'Not found',
397
+ formatted: formatNotFoundError(errorData),
398
+ data: errorData
399
+ };
400
+ }
401
+
402
+ if (statusCode === 409) {
403
+ // Conflict error
404
+ return {
405
+ type: 'conflict',
406
+ message: errorData.detail || errorData.message || 'Conflict',
407
+ formatted: formatConflictError(errorData),
408
+ data: errorData
409
+ };
410
+ }
411
+
412
+ if (statusCode >= 500) {
413
+ // Server error
414
+ return {
415
+ type: 'server',
416
+ message: 'Server error',
417
+ formatted: formatServerError(errorData),
418
+ data: errorData
419
+ };
420
+ }
421
+
422
+ // Generic error
423
+ return {
424
+ type: 'generic',
425
+ message: errorData.message || errorData.error || 'Unknown error',
426
+ formatted: formatGenericError(errorData, statusCode),
427
+ data: errorData
428
+ };
429
+ }
430
+
431
+ /**
432
+ * Formats error for display in CLI
433
+ * @param {Object} apiResponse - API response object from makeApiCall
434
+ * @returns {string} Formatted error message
435
+ */
436
+ function formatApiError(apiResponse) {
437
+ if (!apiResponse || apiResponse.success !== false) {
438
+ return chalk.red('❌ Unknown error occurred');
439
+ }
440
+
441
+ // Use formattedError if already available
442
+ if (apiResponse.formattedError) {
443
+ return apiResponse.formattedError;
444
+ }
445
+
446
+ const errorResponse = apiResponse.error || apiResponse.data || '';
447
+ const statusCode = apiResponse.status || 0;
448
+ const isNetworkError = apiResponse.network === true;
449
+
450
+ const parsed = parseErrorResponse(errorResponse, statusCode, isNetworkError);
451
+ return parsed.formatted;
452
+ }
453
+
454
+ module.exports = {
455
+ parseErrorResponse,
456
+ formatApiError,
457
+ formatPermissionError,
458
+ formatValidationError,
459
+ formatAuthenticationError,
460
+ formatConflictError,
461
+ formatNetworkError,
462
+ formatServerError,
463
+ formatGenericError
464
+ };
465
+