@aifabrix/builder 2.41.0 → 2.42.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 (138) hide show
  1. package/.cursor/rules/docs-rules.mdc +30 -0
  2. package/README.md +1 -1
  3. package/integration/hubspot/README.md +8 -4
  4. package/integration/hubspot/application.json +54 -0
  5. package/integration/hubspot/create-hubspot.js +9 -136
  6. package/integration/hubspot/env.template +3 -4
  7. package/integration/hubspot/hubspot-datasource-company.json +343 -5
  8. package/integration/hubspot/hubspot-datasource-contact.json +413 -5
  9. package/integration/hubspot/hubspot-datasource-deal.json +341 -4
  10. package/integration/hubspot/hubspot-datasource-users.json +116 -0
  11. package/integration/hubspot/hubspot-deploy.json +1250 -108
  12. package/integration/hubspot/hubspot-system.json +15 -32
  13. package/integration/hubspot/test-dataplane-down-tests.js +17 -16
  14. package/integration/hubspot/test-dataplane-down.js +2 -2
  15. package/jest.config.manual.js +2 -1
  16. package/lib/api/external-test.api.js +111 -0
  17. package/lib/api/index.js +42 -19
  18. package/lib/api/pipeline.api.js +66 -120
  19. package/lib/api/types/pipeline.types.js +37 -0
  20. package/lib/api/wizard-platform.api.js +61 -0
  21. package/lib/api/wizard.api.js +34 -1
  22. package/lib/app/config.js +23 -11
  23. package/lib/app/index.js +3 -1
  24. package/lib/app/prompts.js +44 -29
  25. package/lib/app/readme.js +8 -3
  26. package/lib/app/run-env-compose.js +64 -1
  27. package/lib/app/run-helpers.js +1 -1
  28. package/lib/app/show-display.js +1 -1
  29. package/lib/cli/setup-app.js +42 -11
  30. package/lib/cli/setup-credential-deployment.js +31 -6
  31. package/lib/cli/setup-dev.js +27 -0
  32. package/lib/cli/setup-environment.js +12 -4
  33. package/lib/cli/setup-external-system.js +19 -4
  34. package/lib/cli/setup-infra.js +54 -14
  35. package/lib/cli/setup-utility.js +117 -21
  36. package/lib/commands/credential-env.js +162 -0
  37. package/lib/commands/credential-list.js +17 -22
  38. package/lib/commands/credential-push.js +96 -0
  39. package/lib/commands/datasource.js +77 -6
  40. package/lib/commands/dev-init.js +39 -1
  41. package/lib/commands/repair-auth-config.js +99 -0
  42. package/lib/commands/repair-datasource-keys.js +208 -0
  43. package/lib/commands/repair-datasource.js +235 -0
  44. package/lib/commands/repair-env-template.js +348 -0
  45. package/lib/commands/repair-internal.js +85 -0
  46. package/lib/commands/repair-rbac.js +158 -0
  47. package/lib/commands/repair.js +507 -0
  48. package/lib/commands/test-e2e-external.js +165 -0
  49. package/lib/commands/upload.js +71 -40
  50. package/lib/commands/wizard-core-helpers.js +226 -4
  51. package/lib/commands/wizard-core.js +67 -29
  52. package/lib/commands/wizard-dataplane.js +1 -1
  53. package/lib/commands/wizard-entity-selection.js +43 -0
  54. package/lib/commands/wizard-headless.js +44 -5
  55. package/lib/commands/wizard-helpers.js +7 -3
  56. package/lib/commands/wizard.js +86 -64
  57. package/lib/core/config.js +7 -1
  58. package/lib/core/secrets.js +33 -12
  59. package/lib/datasource/deploy.js +12 -3
  60. package/lib/datasource/test-e2e.js +219 -0
  61. package/lib/datasource/test-integration.js +154 -0
  62. package/lib/deployment/deployer.js +7 -5
  63. package/lib/external-system/download.js +182 -204
  64. package/lib/external-system/generator.js +204 -56
  65. package/lib/external-system/test-execution.js +2 -1
  66. package/lib/external-system/test-system-level.js +73 -0
  67. package/lib/external-system/test.js +51 -18
  68. package/lib/generator/external-controller-manifest.js +29 -2
  69. package/lib/generator/external-schema-utils.js +1 -1
  70. package/lib/generator/external.js +10 -3
  71. package/lib/generator/index.js +4 -1
  72. package/lib/generator/split-readme.js +1 -0
  73. package/lib/generator/split-variables.js +7 -1
  74. package/lib/generator/split.js +194 -54
  75. package/lib/generator/wizard-prompts-secondary.js +294 -0
  76. package/lib/generator/wizard-prompts.js +105 -106
  77. package/lib/generator/wizard-readme.js +88 -0
  78. package/lib/generator/wizard.js +147 -158
  79. package/lib/infrastructure/compose.js +11 -1
  80. package/lib/infrastructure/index.js +11 -3
  81. package/lib/infrastructure/services.js +22 -11
  82. package/lib/schema/application-schema.json +8 -5
  83. package/lib/schema/external-datasource.schema.json +49 -26
  84. package/lib/schema/external-system.schema.json +82 -6
  85. package/lib/schema/wizard-config.schema.json +16 -0
  86. package/lib/utils/api.js +38 -10
  87. package/lib/utils/auth-headers.js +8 -7
  88. package/lib/utils/compose-generator.js +1 -1
  89. package/lib/utils/compose-handlebars-helpers.js +11 -0
  90. package/lib/utils/config-format-preference.js +51 -0
  91. package/lib/utils/config-format.js +36 -0
  92. package/lib/utils/configuration-env-resolver.js +179 -0
  93. package/lib/utils/credential-display.js +83 -0
  94. package/lib/utils/credential-secrets-env.js +115 -25
  95. package/lib/utils/dataplane-pipeline-warning.js +28 -0
  96. package/lib/utils/deployment-validation-helpers.js +4 -4
  97. package/lib/utils/dev-ca-install.js +139 -0
  98. package/lib/utils/env-copy.js +23 -3
  99. package/lib/utils/error-formatters/http-status-errors.js +0 -1
  100. package/lib/utils/error-formatters/permission-errors.js +0 -1
  101. package/lib/utils/error-formatters/validation-errors.js +0 -1
  102. package/lib/utils/external-readme.js +56 -29
  103. package/lib/utils/external-system-display.js +59 -1
  104. package/lib/utils/external-system-test-helpers.js +21 -8
  105. package/lib/utils/external-system-validators.js +3 -0
  106. package/lib/utils/file-upload.js +20 -50
  107. package/lib/utils/help-builder.js +1 -0
  108. package/lib/utils/infra-status.js +50 -44
  109. package/lib/utils/local-secrets.js +5 -5
  110. package/lib/utils/paths.js +85 -4
  111. package/lib/utils/secrets-canonical.js +93 -0
  112. package/lib/utils/secrets-generator.js +20 -0
  113. package/lib/utils/secrets-helpers.js +75 -89
  114. package/lib/utils/test-log-writer.js +56 -0
  115. package/lib/utils/token-manager.js +24 -32
  116. package/lib/validation/env-template-auth.js +157 -0
  117. package/lib/validation/env-template-kv.js +41 -0
  118. package/lib/validation/external-manifest-validator.js +25 -0
  119. package/lib/validation/external-system-auth-rules.js +86 -0
  120. package/lib/validation/validate-batch.js +149 -0
  121. package/lib/validation/validate-datasource-keys-api.js +33 -0
  122. package/lib/validation/validate-display.js +94 -16
  123. package/lib/validation/validate.js +25 -12
  124. package/lib/validation/validator.js +7 -9
  125. package/lib/validation/wizard-datasource-validation.js +50 -0
  126. package/package.json +7 -2
  127. package/templates/applications/dataplane/application.yaml +1 -1
  128. package/templates/applications/dataplane/env.template +5 -5
  129. package/templates/applications/dataplane/rbac.yaml +2 -2
  130. package/templates/applications/miso-controller/env.template +1 -1
  131. package/templates/external-system/README.md.hbs +65 -25
  132. package/templates/external-system/deploy.js.hbs +4 -2
  133. package/templates/external-system/external-datasource.yaml.hbs +217 -0
  134. package/templates/external-system/external-system.json.hbs +1 -18
  135. package/templates/infra/compose.yaml.hbs +6 -0
  136. package/templates/python/docker-compose.hbs +4 -4
  137. package/templates/typescript/docker-compose.hbs +4 -4
  138. package/integration/hubspot/application.yaml +0 -37
@@ -126,7 +126,8 @@ function getDefaultConfig() {
126
126
  environment: 'dev',
127
127
  controller: undefined,
128
128
  environments: {},
129
- device: {}
129
+ device: {},
130
+ format: undefined
130
131
  };
131
132
  }
132
133
 
@@ -489,4 +490,9 @@ const { createPathConfigFunctions } = require('../utils/config-paths');
489
490
  const pathConfigFunctions = createPathConfigFunctions(getConfig, saveConfig);
490
491
  Object.assign(exportsObj, pathConfigFunctions);
491
492
 
493
+ // Format preference functions
494
+ const { createFormatFunctions } = require('../utils/config-format-preference');
495
+ const formatFunctions = createFormatFunctions(getConfig, saveConfig);
496
+ Object.assign(exportsObj, formatFunctions);
497
+
492
498
  module.exports = exportsObj;
@@ -206,6 +206,38 @@ async function loadMergedConfigAndUserSecrets() {
206
206
  }
207
207
  }
208
208
 
209
+ /**
210
+ * Loads merged secrets using config/user cascade, builder file merge, and default fallback.
211
+ * @async
212
+ * @returns {Promise<Object>} Merged secrets object (not decrypted)
213
+ */
214
+ async function loadSecretsWithFallbacks() {
215
+ let merged = await loadMergedConfigAndUserSecrets();
216
+ if (!merged || Object.keys(merged).length === 0) {
217
+ merged = loadPrimaryUserSecrets();
218
+ if (Object.keys(merged).length === 0) {
219
+ merged = loadUserSecrets();
220
+ }
221
+ merged = await applyCanonicalSecretsOverride(merged);
222
+ }
223
+ try {
224
+ const projectRoot = pathsUtil.getProjectRoot();
225
+ if (projectRoot) {
226
+ const builderPath = path.join(projectRoot, 'builder', 'secrets.local.yaml');
227
+ if (fs.existsSync(builderPath)) {
228
+ const builderSecrets = mergeUserWithConfigFile(merged || {}, builderPath);
229
+ if (builderSecrets) merged = builderSecrets;
230
+ }
231
+ }
232
+ } catch {
233
+ // Ignore (e.g. no project root or read error)
234
+ }
235
+ if (Object.keys(merged).length === 0) {
236
+ merged = loadDefaultSecrets();
237
+ }
238
+ return merged;
239
+ }
240
+
209
241
  async function loadSecrets(secretsPath, _appName) {
210
242
  if (secretsPath) {
211
243
  const resolvedPath = resolveSecretsPath(secretsPath);
@@ -218,18 +250,7 @@ async function loadSecrets(secretsPath, _appName) {
218
250
  }
219
251
  return await decryptSecretsObject(explicitSecrets);
220
252
  }
221
-
222
- let mergedSecrets = await loadMergedConfigAndUserSecrets();
223
- if (!mergedSecrets || Object.keys(mergedSecrets).length === 0) {
224
- mergedSecrets = loadPrimaryUserSecrets();
225
- if (Object.keys(mergedSecrets).length === 0) {
226
- mergedSecrets = loadUserSecrets();
227
- }
228
- mergedSecrets = await applyCanonicalSecretsOverride(mergedSecrets);
229
- }
230
- if (Object.keys(mergedSecrets).length === 0) {
231
- mergedSecrets = loadDefaultSecrets();
232
- }
253
+ const mergedSecrets = await loadSecretsWithFallbacks();
233
254
  ensureNonEmptySecrets(mergedSecrets);
234
255
  return await decryptSecretsObject(mergedSecrets);
235
256
  }
@@ -16,6 +16,11 @@ const { getEnvironmentApplication } = require('../api/environments.api');
16
16
  const { publishDatasourceViaPipeline } = require('../api/pipeline.api');
17
17
  const { formatApiError } = require('../utils/api-error-handler');
18
18
  const logger = require('../utils/logger');
19
+ const { logDataplanePipelineWarning } = require('../utils/dataplane-pipeline-warning');
20
+ const {
21
+ buildResolvedEnvMapForIntegration,
22
+ resolveConfigurationValues
23
+ } = require('../utils/configuration-env-resolver');
19
24
  const { validateDatasourceFile } = require('./validate');
20
25
 
21
26
  /**
@@ -50,7 +55,7 @@ async function getDataplaneUrl(controllerUrl, appKey, environment, authConfig) {
50
55
  if (!dataplaneUrl) {
51
56
  const appType = application.configuration?.type || application.type;
52
57
  if (appType === 'external') {
53
- throw new Error('Dataplane URL not found for external system. Provide --dataplane <url>.');
58
+ throw new Error('Dataplane URL not found for external system in application configuration.');
54
59
  }
55
60
  throw new Error('Dataplane URL not found in application configuration');
56
61
  }
@@ -107,8 +112,6 @@ async function validateAndLoadDatasourceFile(filePath) {
107
112
  * @param {string} controllerUrl - Controller URL
108
113
  * @param {string} environment - Environment key
109
114
  * @param {string} appKey - Application key
110
- * @param {Object} [options] - Options
111
- * @param {string} [options.dataplane] - Dataplane URL override
112
115
  * @returns {Promise<Object>} Object with authConfig and dataplaneUrl
113
116
  */
114
117
  async function setupDeploymentAuth(controllerUrl, environment, appKey) {
@@ -154,6 +157,7 @@ async function setupDeploymentAuth(controllerUrl, environment, appKey) {
154
157
  async function publishDatasourceToDataplane(dataplaneUrl, systemKey, authConfig, datasourceConfig) {
155
158
  requireBearerForDataplanePipeline(authConfig);
156
159
  logger.log(chalk.blue('\nšŸš€ Publishing datasource to dataplane...'));
160
+ logDataplanePipelineWarning();
157
161
 
158
162
  const publishResponse = await publishDatasourceViaPipeline(dataplaneUrl, systemKey, authConfig, datasourceConfig);
159
163
 
@@ -228,6 +232,11 @@ async function deployDatasource(appKey, filePath, _options) {
228
232
  throw new Error('systemKey is required in datasource configuration');
229
233
  }
230
234
 
235
+ if (Array.isArray(datasourceConfig.configuration) && datasourceConfig.configuration.length > 0) {
236
+ const { envMap, secrets } = await buildResolvedEnvMapForIntegration(systemKey);
237
+ resolveConfigurationValues(datasourceConfig.configuration, envMap, secrets, systemKey);
238
+ }
239
+
231
240
  // Setup authentication and get dataplane URL
232
241
  const { authConfig, dataplaneUrl } = await setupDeploymentAuth(controllerUrl, environment, appKey);
233
242
 
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Datasource E2E test - run full E2E test via dataplane external API
3
+ * @fileoverview Datasource E2E test logic (config, credential, sync, data, CIP)
4
+ * @author AI Fabrix Team
5
+ * @version 2.0.0
6
+ */
7
+ /* eslint-disable max-statements -- Auth setup, API call, polling, debug log */
8
+
9
+ const path = require('path');
10
+ const fs = require('fs').promises;
11
+ const chalk = require('chalk');
12
+ const logger = require('../utils/logger');
13
+ const { getIntegrationPath, resolveIntegrationAppKeyFromCwd } = require('../utils/paths');
14
+ const { resolveDataplaneUrl } = require('../utils/dataplane-resolver');
15
+ const { resolveControllerUrl } = require('../utils/controller-url');
16
+ const { getDeviceOnlyAuth } = require('../utils/token-manager');
17
+ const { testDatasourceE2E, getE2ETestRun } = require('../api/external-test.api');
18
+ const { writeTestLog } = require('../utils/test-log-writer');
19
+
20
+ const DEFAULT_POLL_INTERVAL_MS = 2500;
21
+ const DEFAULT_POLL_TIMEOUT_MS = 15 * 60 * 1000;
22
+
23
+ /**
24
+ * Resolve appKey for datasource test-e2e
25
+ * @param {string} [appKey] - Explicit app key from --app
26
+ * @returns {string}
27
+ */
28
+ function resolveAppKey(appKey) {
29
+ if (appKey) return appKey;
30
+ const fromCwd = resolveIntegrationAppKeyFromCwd();
31
+ if (fromCwd) return fromCwd;
32
+ throw new Error(
33
+ 'Could not determine app context. Use --app <appKey> or run from integration/<appKey>/ directory.'
34
+ );
35
+ }
36
+
37
+ /**
38
+ * Resolve primaryKeyValue for request body: string as-is, or read and parse JSON from @path
39
+ * @param {string} [value] - Literal value or path prefixed with @ (e.g. @pk.json)
40
+ * @returns {Promise<string|Object|null>} Resolved value for body.primaryKeyValue, or null if absent
41
+ */
42
+ async function resolvePrimaryKeyValue(value) {
43
+ if (value === null || value === undefined || value === '') return null;
44
+ const str = String(value).trim();
45
+ if (str.startsWith('@')) {
46
+ const filePath = path.resolve(str.slice(1).trim());
47
+ const content = await fs.readFile(filePath, 'utf8');
48
+ return JSON.parse(content);
49
+ }
50
+ return str;
51
+ }
52
+
53
+ /**
54
+ * Build E2E request body from options
55
+ * @param {Object} options - Command options
56
+ * @returns {Promise<Object>} Request body
57
+ */
58
+ async function buildE2EBody(options) {
59
+ const body = {};
60
+ if (options.debug) body.includeDebug = true;
61
+ if (options.testCrud === true) body.testCrud = true;
62
+ if (options.recordId !== undefined && options.recordId !== null && options.recordId !== '') body.recordId = String(options.recordId);
63
+ if (options.cleanup === false) body.cleanup = false;
64
+ else if (options.cleanup === true) body.cleanup = true;
65
+ const pk = await resolvePrimaryKeyValue(options.primaryKeyValue);
66
+ if (pk !== null && pk !== undefined) body.primaryKeyValue = pk;
67
+ return body;
68
+ }
69
+
70
+ /**
71
+ * Poll E2E test run until completed or failed
72
+ * @param {string} dataplaneUrl - Dataplane URL
73
+ * @param {string} sourceIdOrKey - Source ID or key
74
+ * @param {string} testRunId - Test run ID
75
+ * @param {Object} authConfig - Auth config
76
+ * @param {Object} opts - Poll options
77
+ * @param {number} [opts.intervalMs] - Poll interval (ms)
78
+ * @param {number} [opts.timeoutMs] - Max wait (ms)
79
+ * @param {boolean} [opts.verbose] - Log each poll
80
+ * @returns {Promise<Object>} Final poll result (status completed or failed)
81
+ */
82
+ async function pollE2ETestRun(dataplaneUrl, sourceIdOrKey, testRunId, authConfig, opts = {}) {
83
+ const intervalMs = opts.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
84
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_POLL_TIMEOUT_MS;
85
+ const verbose = opts.verbose === true;
86
+ const deadline = Date.now() + timeoutMs;
87
+ let last;
88
+ while (Date.now() < deadline) {
89
+ last = await getE2ETestRun(dataplaneUrl, sourceIdOrKey, testRunId, authConfig);
90
+ if (last.status === 'completed' || last.status === 'failed') {
91
+ return last;
92
+ }
93
+ if (verbose) {
94
+ const steps = last.completedActions || [];
95
+ logger.log(chalk.gray(` Polling… status: ${last.status}, ${steps.length} step(s) completed`));
96
+ }
97
+ await new Promise(r => setTimeout(r, intervalMs));
98
+ }
99
+ throw new Error(
100
+ `E2E test run did not complete within ${timeoutMs / 1000}s (run ID: ${testRunId})`
101
+ );
102
+ }
103
+
104
+ /**
105
+ * Run E2E test for one datasource (Bearer token or API key required; no client credentials).
106
+ * Default: async start + polling until completed/failed. Use options.async === false for sync.
107
+ *
108
+ * @async
109
+ * @param {string} datasourceKey - Datasource key (used as sourceIdOrKey)
110
+ * @param {Object} options - Options
111
+ * @param {string} [options.app] - App key (or resolve from cwd)
112
+ * @param {string} [options.environment] - Environment (dev, tst, pro)
113
+ * @param {boolean} [options.debug] - Include debug, write log file
114
+ * @param {boolean} [options.verbose] - Verbose output (e.g. poll progress)
115
+ * @param {boolean} [options.async] - If false, use sync mode (no polling). Default true.
116
+ * @param {boolean} [options.testCrud] - Set body testCrud true
117
+ * @param {string} [options.recordId] - Set body recordId
118
+ * @param {boolean} [options.cleanup] - Set body cleanup (default true)
119
+ * @param {string} [options.primaryKeyValue] - Set body primaryKeyValue (string or @path to JSON)
120
+ * @param {number} [options.pollIntervalMs] - Poll interval in ms (default 2500)
121
+ * @param {number} [options.pollTimeoutMs] - Poll timeout in ms (default 15 min)
122
+ * @returns {Promise<Object>} E2E test result (steps, success, error, etc.)
123
+ */
124
+ async function runDatasourceTestE2E(datasourceKey, options = {}) {
125
+ if (!datasourceKey || typeof datasourceKey !== 'string') {
126
+ throw new Error('Datasource key is required');
127
+ }
128
+ const appKey = resolveAppKey(options.app);
129
+ const controllerUrl = await resolveControllerUrl();
130
+ const { resolveEnvironment } = require('../core/config');
131
+ const environment = options.environment || await resolveEnvironment();
132
+ const authConfig = await getDeviceOnlyAuth(controllerUrl);
133
+ const dataplaneUrl = await resolveDataplaneUrl(controllerUrl, environment, authConfig);
134
+
135
+ logger.log(chalk.blue(`\n🧪 Running E2E test for datasource: ${datasourceKey}`));
136
+
137
+ const body = await buildE2EBody(options);
138
+ const useAsync = options.async !== false;
139
+ const requestMeta = {
140
+ sourceIdOrKey: datasourceKey,
141
+ includeDebug: options.debug,
142
+ testCrud: options.testCrud,
143
+ recordId: options.recordId,
144
+ cleanup: options.cleanup,
145
+ primaryKeyValue: options.primaryKeyValue !== undefined && options.primaryKeyValue !== null
146
+ };
147
+
148
+ const execOpts = {
149
+ dataplaneUrl,
150
+ datasourceKey,
151
+ authConfig,
152
+ body,
153
+ useAsync,
154
+ verbose: options.verbose,
155
+ pollIntervalMs: options.pollIntervalMs,
156
+ pollTimeoutMs: options.pollTimeoutMs
157
+ };
158
+ let data;
159
+ try {
160
+ data = await executeE2EWithOptionalPoll(execOpts);
161
+ } catch (error) {
162
+ if (options.debug) {
163
+ const appPath = getIntegrationPath(appKey);
164
+ const integrationDir = path.dirname(appPath);
165
+ await writeTestLog(appKey, { request: requestMeta, error: error.message }, 'test-e2e', integrationDir);
166
+ }
167
+ throw error;
168
+ }
169
+
170
+ if (options.debug) {
171
+ const appPath = getIntegrationPath(appKey);
172
+ const integrationDir = path.dirname(appPath);
173
+ const logPath = await writeTestLog(appKey, { request: requestMeta, response: data }, 'test-e2e', integrationDir);
174
+ logger.log(chalk.gray(` Debug log: ${logPath}`));
175
+ }
176
+
177
+ return data;
178
+ }
179
+
180
+ /**
181
+ * Call E2E API and optionally poll until completed. On throw, caller should log if debug.
182
+ * @param {Object} opts - Options
183
+ * @param {string} opts.dataplaneUrl - Dataplane URL
184
+ * @param {string} opts.datasourceKey - Source key
185
+ * @param {Object} opts.authConfig - Auth config
186
+ * @param {Object} opts.body - Request body
187
+ * @param {boolean} opts.useAsync - Whether to use async + poll
188
+ * @param {boolean} opts.verbose - Verbose poll progress
189
+ * @param {number} [opts.pollIntervalMs] - Override poll interval (ms)
190
+ * @param {number} [opts.pollTimeoutMs] - Override poll timeout (ms)
191
+ * @returns {Promise<Object>} Final result data
192
+ */
193
+ /* eslint-disable-next-line max-params -- single opts object; destructuring in body */
194
+ async function executeE2EWithOptionalPoll(opts) {
195
+ const { dataplaneUrl, datasourceKey, authConfig, body, useAsync, verbose, pollIntervalMs, pollTimeoutMs } = opts;
196
+ const response = await testDatasourceE2E(dataplaneUrl, datasourceKey, authConfig, body, {
197
+ asyncRun: useAsync
198
+ });
199
+ let data = response.data || response;
200
+ if (useAsync && data !== null && data !== undefined && data.testRunId) {
201
+ data = await pollE2ETestRun(
202
+ dataplaneUrl,
203
+ datasourceKey,
204
+ data.testRunId,
205
+ authConfig,
206
+ {
207
+ intervalMs: pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS,
208
+ timeoutMs: pollTimeoutMs ?? DEFAULT_POLL_TIMEOUT_MS,
209
+ verbose
210
+ }
211
+ );
212
+ }
213
+ return data;
214
+ }
215
+
216
+ module.exports = {
217
+ runDatasourceTestE2E,
218
+ resolveAppKey
219
+ };
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Datasource integration test - run config test for one datasource via pipeline
3
+ * @fileoverview Datasource integration test logic
4
+ * @author AI Fabrix Team
5
+ * @version 2.0.0
6
+ */
7
+ /* eslint-disable max-lines-per-function,max-statements,complexity -- Load config, resolve datasource, call pipeline test */
8
+
9
+ const path = require('path');
10
+ const chalk = require('chalk');
11
+ const logger = require('../utils/logger');
12
+ const { getIntegrationPath, resolveIntegrationAppKeyFromCwd } = require('../utils/paths');
13
+ const { resolveApplicationConfigPath } = require('../utils/app-config-resolver');
14
+ const { loadConfigFile } = require('../utils/config-format');
15
+ const { setupIntegrationTestAuth } = require('../external-system/test-auth');
16
+ const { getConfig } = require('../core/config');
17
+ const { testDatasourceViaPipeline } = require('../api/pipeline.api');
18
+ const { writeTestLog } = require('../utils/test-log-writer');
19
+ const testHelpers = require('../utils/external-system-test-helpers');
20
+ const fs = require('fs').promises;
21
+
22
+ /**
23
+ * Resolve systemKey and appKey for datasource test-integration
24
+ * @param {string} [appKey] - Explicit app key from --app
25
+ * @returns {Promise<{appKey: string, systemKey: string}>}
26
+ */
27
+ async function resolveSystemKey(appKey) {
28
+ let resolvedAppKey = appKey;
29
+ if (!resolvedAppKey) {
30
+ resolvedAppKey = resolveIntegrationAppKeyFromCwd();
31
+ }
32
+ if (!resolvedAppKey) {
33
+ throw new Error(
34
+ 'Could not determine app context. Use --app <appKey> or run from integration/<appKey>/ directory.'
35
+ );
36
+ }
37
+ const appPath = getIntegrationPath(resolvedAppKey);
38
+ const configPath = resolveApplicationConfigPath(appPath);
39
+ const config = loadConfigFile(configPath);
40
+ if (!config.externalIntegration || !config.externalIntegration.systems || config.externalIntegration.systems.length === 0) {
41
+ throw new Error(`No externalIntegration.systems found in ${configPath}`);
42
+ }
43
+ const systemFile = config.externalIntegration.systems[0];
44
+ const systemPath = path.isAbsolute(systemFile)
45
+ ? systemFile
46
+ : path.join(appPath, systemFile);
47
+ const systemContent = await fs.readFile(systemPath, 'utf8');
48
+ const yaml = require('js-yaml');
49
+ const systemConfig = yaml.load(systemContent);
50
+ const systemKey = systemConfig?.key || path.basename(systemFile, '-system.yaml').replace('-system', '');
51
+ return { appKey: resolvedAppKey, systemKey };
52
+ }
53
+
54
+ /**
55
+ * Run integration test for one datasource
56
+ * @async
57
+ * @param {string} datasourceKey - Datasource key
58
+ * @param {Object} options - Options
59
+ * @param {string} [options.app] - App key (or resolve from cwd)
60
+ * @param {string} [options.payload] - Path to custom payload file
61
+ * @param {string} [options.environment] - Environment (dev, tst, pro)
62
+ * @param {boolean} [options.debug] - Include debug, write log file
63
+ * @param {number} [options.timeout] - Request timeout ms
64
+ * @returns {Promise<Object>} Test result
65
+ */
66
+ async function runDatasourceTestIntegration(datasourceKey, options = {}) {
67
+ if (!datasourceKey || typeof datasourceKey !== 'string') {
68
+ throw new Error('Datasource key is required');
69
+ }
70
+ const { appKey, systemKey } = await resolveSystemKey(options.app);
71
+ const appPath = getIntegrationPath(appKey);
72
+ const config = loadConfigFile(resolveApplicationConfigPath(appPath));
73
+ const schemaBasePath = config.externalIntegration?.schemaBasePath || './';
74
+ const datasourceFiles = config.externalIntegration?.dataSources || [];
75
+ const datasourceFile = datasourceFiles.find(f => {
76
+ const base = path.basename(f, path.extname(f));
77
+ return base === datasourceKey || base.includes(datasourceKey);
78
+ });
79
+ if (!datasourceFile) {
80
+ throw new Error(`Datasource '${datasourceKey}' not found in application config`);
81
+ }
82
+ const datasourcePath = path.isAbsolute(schemaBasePath)
83
+ ? path.join(schemaBasePath, datasourceFile)
84
+ : path.join(appPath, schemaBasePath, datasourceFile);
85
+ const datasourceContent = await fs.readFile(datasourcePath, 'utf8');
86
+ const datasource = JSON.parse(datasourceContent);
87
+ if (datasource.key !== datasourceKey) {
88
+ throw new Error(`Datasource key mismatch: file has '${datasource.key}', expected '${datasourceKey}'`);
89
+ }
90
+
91
+ const configObj = await getConfig();
92
+ const { authConfig, dataplaneUrl } = await setupIntegrationTestAuth(appKey, options, configObj);
93
+ const customPayload = await testHelpers.loadCustomPayload(options.payload);
94
+ const payloadTemplate = testHelpers.determinePayloadTemplate(datasource, datasourceKey, customPayload);
95
+ if (!payloadTemplate) {
96
+ throw new Error(`No test payload found for datasource '${datasourceKey}'`);
97
+ }
98
+
99
+ logger.log(chalk.blue(`\nšŸ“” Testing datasource: ${datasourceKey} (system: ${systemKey})`));
100
+
101
+ const testData = { payloadTemplate };
102
+ if (options.debug) {
103
+ testData.includeDebug = true;
104
+ }
105
+ const timeout = parseInt(options.timeout, 10) || 30000;
106
+
107
+ let response;
108
+ try {
109
+ response = await testDatasourceViaPipeline({
110
+ dataplaneUrl,
111
+ systemKey,
112
+ datasourceKey,
113
+ authConfig,
114
+ testData,
115
+ options: { timeout }
116
+ });
117
+ } catch (error) {
118
+ const result = { key: datasourceKey, success: false, error: error.message };
119
+ if (options.debug) {
120
+ await writeTestLog(appKey, { request: { systemKey, datasourceKey }, error: error.message }, 'test-integration');
121
+ }
122
+ return result;
123
+ }
124
+
125
+ const data = response.data || response;
126
+ const success = data.success !== false;
127
+ const result = {
128
+ key: datasourceKey,
129
+ systemKey,
130
+ success,
131
+ skipped: false,
132
+ validationResults: data.validationResults || {},
133
+ fieldMappingResults: data.fieldMappingResults || {},
134
+ endpointTestResults: data.endpointTestResults || {}
135
+ };
136
+ if (data.error) {
137
+ result.error = data.error;
138
+ }
139
+
140
+ if (options.debug) {
141
+ const logPath = await writeTestLog(appKey, {
142
+ request: { systemKey, datasourceKey, includeDebug: true },
143
+ response: data
144
+ }, 'test-integration');
145
+ logger.log(chalk.gray(` Debug log: ${logPath}`));
146
+ }
147
+
148
+ return result;
149
+ }
150
+
151
+ module.exports = {
152
+ runDatasourceTestIntegration,
153
+ resolveSystemKey
154
+ };
@@ -193,14 +193,16 @@ function buildDeploymentData(validateToken, authConfig, options) {
193
193
  * @throws {Error} If deployment failed
194
194
  */
195
195
  function handleDeploymentResponse(response) {
196
- if (response.success) {
196
+ const bodyFailed = response.data?.success === false;
197
+ if (response.success && !bodyFailed) {
197
198
  return response.data.data || response.data;
198
199
  }
199
200
 
200
- // Handle deployment errors
201
- if (response.status >= 400) {
202
- const error = new Error(`Deployment request failed: ${response.formattedError || response.error || 'Unknown error'}`);
203
- error.status = response.status;
201
+ // Handle deployment errors (HTTP error or 200 with success: false in body)
202
+ if (!response.success || bodyFailed || response.status >= 400) {
203
+ const msg = response.formattedError || response.error || response.data?.formattedError || response.data?.error || 'Unknown error';
204
+ const error = new Error(`Deployment request failed: ${msg}`);
205
+ error.status = response.status || (bodyFailed ? 400 : undefined);
204
206
  error.data = response.data;
205
207
  throw error;
206
208
  }