@nordsym/apiclaw 2.2.0 → 2.3.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 (176) hide show
  1. package/README.md +15 -2
  2. package/dist/bin-http.js +0 -0
  3. package/dist/bin.bundled.js +79288 -0
  4. package/dist/gateway-client.d.ts.map +1 -1
  5. package/dist/gateway-client.js +24 -2
  6. package/dist/gateway-client.js.map +1 -1
  7. package/dist/index.bundled.js +61263 -0
  8. package/dist/index.js +2 -2
  9. package/dist/index.js.map +1 -1
  10. package/package.json +7 -2
  11. package/.claude/settings.local.json +0 -13
  12. package/.env.prod +0 -1
  13. package/apiclaw-README.md +0 -494
  14. package/convex/_generated/api.d.ts +0 -145
  15. package/convex/_generated/api.js +0 -23
  16. package/convex/_generated/dataModel.d.ts +0 -60
  17. package/convex/_generated/server.d.ts +0 -143
  18. package/convex/_generated/server.js +0 -93
  19. package/convex/_listWorkspaces.ts +0 -13
  20. package/convex/adminActivate.ts +0 -53
  21. package/convex/adminStats.ts +0 -306
  22. package/convex/agents.ts +0 -939
  23. package/convex/analytics.ts +0 -187
  24. package/convex/apiKeys.ts +0 -220
  25. package/convex/backfillAnalytics.ts +0 -272
  26. package/convex/backfillSearchLogs.ts +0 -35
  27. package/convex/billing.ts +0 -834
  28. package/convex/capabilities.ts +0 -157
  29. package/convex/chains.ts +0 -1318
  30. package/convex/credits.ts +0 -211
  31. package/convex/crons.ts +0 -65
  32. package/convex/debugFilestackLogs.ts +0 -16
  33. package/convex/debugGetToken.ts +0 -18
  34. package/convex/directCall.ts +0 -713
  35. package/convex/earnProgress.ts +0 -753
  36. package/convex/email.ts +0 -329
  37. package/convex/feedback.ts +0 -265
  38. package/convex/funnel.ts +0 -431
  39. package/convex/guards.ts +0 -174
  40. package/convex/http.ts +0 -3756
  41. package/convex/inbound.ts +0 -32
  42. package/convex/logs.ts +0 -701
  43. package/convex/migrateFilestack.ts +0 -81
  44. package/convex/migratePartnersProd.ts +0 -174
  45. package/convex/migratePratham.ts +0 -126
  46. package/convex/migrateProviderWorkspaces.ts +0 -175
  47. package/convex/mou.ts +0 -91
  48. package/convex/nurture.ts +0 -355
  49. package/convex/providerKeys.ts +0 -289
  50. package/convex/providers.ts +0 -1135
  51. package/convex/purchases.ts +0 -183
  52. package/convex/ratelimit.ts +0 -104
  53. package/convex/schema.ts +0 -926
  54. package/convex/searchLogs.ts +0 -265
  55. package/convex/seedAPILayerAPIs.ts +0 -191
  56. package/convex/seedDirectCallConfigs.ts +0 -336
  57. package/convex/seedPratham.ts +0 -149
  58. package/convex/spendAlerts.ts +0 -442
  59. package/convex/stripeActions.ts +0 -607
  60. package/convex/teams.ts +0 -243
  61. package/convex/telemetry.ts +0 -81
  62. package/convex/tsconfig.json +0 -25
  63. package/convex/updateAPIStatus.ts +0 -44
  64. package/convex/usage.ts +0 -260
  65. package/convex/usageReports.ts +0 -357
  66. package/convex/waitlist.ts +0 -55
  67. package/convex/webhooks.ts +0 -494
  68. package/convex/workspaceSettings.ts +0 -143
  69. package/convex/workspaces.ts +0 -1331
  70. package/convex.json +0 -3
  71. package/direct-test.mjs +0 -51
  72. package/email-templates/filestack-provider-outreach.html +0 -162
  73. package/email-templates/partnership-template.html +0 -116
  74. package/email-templates/pratham-draft-preview.txt +0 -57
  75. package/email-templates/pratham-partnership-draft.html +0 -141
  76. package/reports/APIClaw-Session-Report-2026-04-05.pdf +0 -0
  77. package/reports/pipeline/PIPELINE-REPORT.json +0 -153
  78. package/reports/pipeline/acquire_apisguru.json +0 -17
  79. package/reports/pipeline/capabilities.json +0 -38
  80. package/reports/pipeline/discover_azure_recursive.json +0 -1551
  81. package/reports/pipeline/discover_github.json +0 -25
  82. package/reports/pipeline/discover_github_repos.json +0 -49
  83. package/reports/pipeline/discover_swaggerhub.json +0 -24
  84. package/reports/pipeline/discover_well_known.json +0 -23
  85. package/reports/pipeline/fetch_specs.json +0 -19
  86. package/reports/pipeline/generate_providers.json +0 -14
  87. package/reports/pipeline/match_registry.json +0 -11
  88. package/reports/pipeline/parse_specs.json +0 -17
  89. package/reports/pipeline/promote_candidates.json +0 -34
  90. package/reports/pipeline/validate.json +0 -30
  91. package/reports/pipeline/validate_smoke_details.json +0 -3835
  92. package/reports/session-report-2026-04-05.html +0 -433
  93. package/seed-apis-direct.mjs +0 -106
  94. package/src/access-control.ts +0 -174
  95. package/src/adapters/base.ts +0 -364
  96. package/src/adapters/claude-desktop.ts +0 -41
  97. package/src/adapters/cline.ts +0 -88
  98. package/src/adapters/continue.ts +0 -91
  99. package/src/adapters/cursor.ts +0 -43
  100. package/src/adapters/custom.ts +0 -188
  101. package/src/adapters/detect.ts +0 -202
  102. package/src/adapters/index.ts +0 -47
  103. package/src/adapters/windsurf.ts +0 -44
  104. package/src/bin-http.ts +0 -45
  105. package/src/bin.ts +0 -34
  106. package/src/capability-router.ts +0 -331
  107. package/src/chainExecutor.ts +0 -730
  108. package/src/chainResolver.test.ts +0 -246
  109. package/src/chainResolver.ts +0 -658
  110. package/src/cli/commands/demo.ts +0 -109
  111. package/src/cli/commands/doctor.ts +0 -435
  112. package/src/cli/commands/index.ts +0 -9
  113. package/src/cli/commands/login.ts +0 -203
  114. package/src/cli/commands/mcp-install.ts +0 -373
  115. package/src/cli/commands/restore.ts +0 -333
  116. package/src/cli/commands/setup.ts +0 -297
  117. package/src/cli/commands/uninstall.ts +0 -240
  118. package/src/cli/index.ts +0 -148
  119. package/src/cli.ts +0 -370
  120. package/src/confirmation.ts +0 -296
  121. package/src/credentials.ts +0 -455
  122. package/src/credits.ts +0 -329
  123. package/src/crypto.ts +0 -75
  124. package/src/discovery.ts +0 -568
  125. package/src/enterprise/env.ts +0 -156
  126. package/src/enterprise/index.ts +0 -7
  127. package/src/enterprise/script-generator.ts +0 -481
  128. package/src/execute-dynamic.ts +0 -617
  129. package/src/execute.ts +0 -2386
  130. package/src/funnel-client.ts +0 -168
  131. package/src/funnel.test.ts +0 -187
  132. package/src/gateway-client.ts +0 -192
  133. package/src/hivr-whitelist.ts +0 -110
  134. package/src/http-api.ts +0 -286
  135. package/src/http-server-minimal.ts +0 -154
  136. package/src/index.ts +0 -2702
  137. package/src/intelligent-gateway.ts +0 -339
  138. package/src/mcp-analytics.ts +0 -156
  139. package/src/metered.ts +0 -149
  140. package/src/open-apis-generated.ts +0 -157
  141. package/src/open-apis.ts +0 -558
  142. package/src/postinstall.ts +0 -40
  143. package/src/product-whitelist.ts +0 -246
  144. package/src/proxy.ts +0 -36
  145. package/src/registration-guard.ts +0 -117
  146. package/src/session.ts +0 -129
  147. package/src/stripe.ts +0 -497
  148. package/src/telemetry.ts +0 -71
  149. package/src/test.ts +0 -135
  150. package/src/types/convex-api.d.ts +0 -20
  151. package/src/types/convex-api.ts +0 -21
  152. package/src/types.ts +0 -109
  153. package/src/ui/colors.ts +0 -219
  154. package/src/ui/errors.ts +0 -394
  155. package/src/ui/index.ts +0 -17
  156. package/src/ui/prompts.ts +0 -390
  157. package/src/ui/spinner.ts +0 -325
  158. package/src/utils/backup.ts +0 -224
  159. package/src/utils/config.ts +0 -318
  160. package/src/utils/os.ts +0 -124
  161. package/src/utils/paths.ts +0 -203
  162. package/src/webhook.ts +0 -107
  163. package/test-10-working.cjs +0 -97
  164. package/test-14-final.cjs +0 -96
  165. package/test-actual-handlers.ts +0 -92
  166. package/test-apilayer-all-14.ts +0 -249
  167. package/test-apilayer-fixed.ts +0 -248
  168. package/test-direct-endpoints.ts +0 -174
  169. package/test-exact-endpoints.ts +0 -144
  170. package/test-final.ts +0 -83
  171. package/test-full-routing.ts +0 -100
  172. package/test-handlers-correct.ts +0 -217
  173. package/test-numverify-key.ts +0 -41
  174. package/test-via-handlers.ts +0 -92
  175. package/test-worldnews.mjs +0 -26
  176. package/tsconfig.json +0 -20
@@ -1,730 +0,0 @@
1
- /**
2
- * APIClaw Chain Executor
3
- *
4
- * Orchestrates multi-step API chains with:
5
- * - Sequential execution
6
- * - Parallel batches
7
- * - Conditional branching
8
- * - ForEach loops
9
- * - Error handling and retry
10
- * - Full execution trace
11
- */
12
-
13
- import { executeAPICall } from './execute.js';
14
- import {
15
- ChainContext,
16
- ChainStep,
17
- ChainStepUnion,
18
- ParallelStep,
19
- ConditionalStep,
20
- ForEachStep,
21
- ErrorConfig,
22
- resolveReferences,
23
- validateReferences,
24
- evaluateCondition,
25
- ReferenceError,
26
- } from './chainResolver.js';
27
-
28
- // ============================================================================
29
- // TYPES
30
- // ============================================================================
31
-
32
- export interface ChainDefinition {
33
- id?: string;
34
- name?: string;
35
- description?: string;
36
- steps: ChainStepUnion[];
37
- inputs?: Record<string, InputDefinition>;
38
- errorPolicy?: ErrorPolicy;
39
- limits?: ChainLimits;
40
- timeout?: number;
41
- }
42
-
43
- export interface InputDefinition {
44
- type: 'string' | 'number' | 'boolean' | 'array' | 'object';
45
- required?: boolean;
46
- default?: any;
47
- description?: string;
48
- }
49
-
50
- export interface ErrorPolicy {
51
- mode: 'fail-fast' | 'best-effort' | 'transactional';
52
- rollback?: RollbackStep[];
53
- }
54
-
55
- export interface RollbackStep {
56
- if: string;
57
- do: ChainStep;
58
- }
59
-
60
- export interface ChainLimits {
61
- maxSteps?: number;
62
- maxParallel?: number;
63
- maxCost?: { cents: number };
64
- }
65
-
66
- export interface Credentials {
67
- userId?: string;
68
- customerKeys?: Record<string, string>; // providerId → API key
69
- }
70
-
71
- export interface ChainOptions {
72
- dryRun?: boolean;
73
- verbose?: boolean;
74
- onStepComplete?: (step: StepTrace) => void;
75
- onStepStart?: (stepId: string, stepIndex: number) => void;
76
- }
77
-
78
- export interface ChainResult {
79
- success: boolean;
80
- chainId: string;
81
- startedAt: string;
82
- completedAt: string;
83
- totalLatencyMs: number;
84
- totalCost: { cents: number };
85
-
86
- // Results
87
- finalResult?: any;
88
- results: Record<string, any>;
89
-
90
- // Error info (if failed)
91
- error?: ChainError;
92
- completedSteps: string[];
93
- failedStep?: StepTrace;
94
-
95
- // Full trace
96
- trace: StepTrace[];
97
-
98
- // Resume capability
99
- canResume: boolean;
100
- resumeToken?: string;
101
- }
102
-
103
- export interface ChainError {
104
- stepId: string;
105
- code: string;
106
- message: string;
107
- retryAfter?: number;
108
- }
109
-
110
- export interface StepTrace {
111
- stepId: string;
112
- stepIndex: number;
113
- provider: string;
114
- action: string;
115
- startedAt: string;
116
- completedAt: string;
117
- latencyMs: number;
118
- success: boolean;
119
- input: Record<string, any>;
120
- output?: any;
121
- error?: string;
122
- errorCode?: string;
123
- cost?: { cents: number };
124
- retries?: number;
125
- }
126
-
127
- // ============================================================================
128
- // MAIN EXECUTOR
129
- // ============================================================================
130
-
131
- /**
132
- * Execute a chain of API calls
133
- */
134
- export async function executeChain(
135
- chain: ChainDefinition,
136
- credentials: Credentials,
137
- inputs?: Record<string, any>,
138
- options: ChainOptions = {}
139
- ): Promise<ChainResult> {
140
- const chainId = chain.id || generateChainId();
141
- const startedAt = new Date().toISOString();
142
- const startTime = Date.now();
143
-
144
- // Initialize context
145
- const context: ChainContext = {
146
- results: {},
147
- inputs: inputs || {},
148
- currentIndex: 0,
149
- startedAt,
150
- env: process.env as Record<string, string>,
151
- };
152
-
153
- // Initialize result
154
- const result: ChainResult = {
155
- success: false,
156
- chainId,
157
- startedAt,
158
- completedAt: '',
159
- totalLatencyMs: 0,
160
- totalCost: { cents: 0 },
161
- results: {},
162
- completedSteps: [],
163
- trace: [],
164
- canResume: false,
165
- };
166
-
167
- try {
168
- // Validate inputs
169
- if (chain.inputs) {
170
- validateInputs(inputs || {}, chain.inputs);
171
- }
172
-
173
- // Validate references before execution
174
- const validation = validateReferences(chain.steps);
175
- if (!validation.valid) {
176
- const errorMsg = validation.errors.map(e => `${e.stepId}: ${e.message}`).join('; ');
177
- throw new Error(`Reference validation failed: ${errorMsg}`);
178
- }
179
-
180
- // Log warnings
181
- if (options.verbose && validation.warnings.length > 0) {
182
- console.log('[Chain] Warnings:', validation.warnings);
183
- }
184
-
185
- // Check limits
186
- if (chain.limits?.maxSteps && chain.steps.length > chain.limits.maxSteps) {
187
- throw new Error(`Chain exceeds maxSteps limit (${chain.steps.length} > ${chain.limits.maxSteps})`);
188
- }
189
-
190
- // Execute steps
191
- let lastStepResult: any;
192
-
193
- for (let i = 0; i < chain.steps.length; i++) {
194
- const step = chain.steps[i];
195
- context.currentIndex = i;
196
-
197
- // Check timeout
198
- if (chain.timeout && Date.now() - startTime > chain.timeout) {
199
- throw new TimeoutError(`Chain exceeded timeout of ${chain.timeout}ms`);
200
- }
201
-
202
- // Execute based on step type
203
- if (isParallelStep(step)) {
204
- lastStepResult = await executeParallelStep(step, context, credentials, options, result);
205
- } else if (isConditionalStep(step)) {
206
- lastStepResult = await executeConditionalStep(step, context, credentials, options, result);
207
- } else if (isForEachStep(step)) {
208
- lastStepResult = await executeForEachStep(step, context, credentials, options, result, chain.limits);
209
- } else {
210
- lastStepResult = await executeSingleStep(step, context, credentials, options, result, chain.errorPolicy);
211
- }
212
- }
213
-
214
- // Success!
215
- result.success = true;
216
- result.finalResult = lastStepResult;
217
- result.results = { ...context.results };
218
-
219
- } catch (error: any) {
220
- // Handle failure
221
- result.success = false;
222
- result.error = {
223
- stepId: result.failedStep?.stepId || 'unknown',
224
- code: error.code || 'CHAIN_ERROR',
225
- message: error.message,
226
- retryAfter: error.retryAfter,
227
- };
228
- result.results = { ...context.results };
229
-
230
- // Handle rollback for transactional mode
231
- if (chain.errorPolicy?.mode === 'transactional' && chain.errorPolicy.rollback) {
232
- await executeRollback(chain.errorPolicy.rollback, context, credentials, options, result);
233
- }
234
-
235
- // Can resume if we have completed steps
236
- result.canResume = result.completedSteps.length > 0;
237
- if (result.canResume) {
238
- result.resumeToken = `${chainId}_step_${result.completedSteps.length}`;
239
- }
240
- }
241
-
242
- // Finalize
243
- result.completedAt = new Date().toISOString();
244
- result.totalLatencyMs = Date.now() - startTime;
245
-
246
- return result;
247
- }
248
-
249
- // ============================================================================
250
- // STEP TYPE GUARDS
251
- // ============================================================================
252
-
253
- function isParallelStep(step: ChainStepUnion): step is ParallelStep {
254
- return 'parallel' in step;
255
- }
256
-
257
- function isConditionalStep(step: ChainStepUnion): step is ConditionalStep {
258
- return 'if' in step;
259
- }
260
-
261
- function isForEachStep(step: ChainStepUnion): step is ForEachStep {
262
- return 'forEach' in step;
263
- }
264
-
265
- // ============================================================================
266
- // SINGLE STEP EXECUTION
267
- // ============================================================================
268
-
269
- async function executeSingleStep(
270
- step: ChainStep,
271
- context: ChainContext,
272
- credentials: Credentials,
273
- options: ChainOptions,
274
- result: ChainResult,
275
- errorPolicy?: ErrorPolicy
276
- ): Promise<any> {
277
- const stepStart = Date.now();
278
- const stepTrace: StepTrace = {
279
- stepId: step.id,
280
- stepIndex: context.currentIndex,
281
- provider: step.provider,
282
- action: step.action,
283
- startedAt: new Date().toISOString(),
284
- completedAt: '',
285
- latencyMs: 0,
286
- success: false,
287
- input: {},
288
- };
289
-
290
- options.onStepStart?.(step.id, context.currentIndex);
291
-
292
- try {
293
- // Resolve references in params
294
- const resolvedParams = step.params ? resolveReferences(step.params, context) : {};
295
- stepTrace.input = resolvedParams;
296
-
297
- // Execute with retry if configured
298
- const maxRetries = step.onError?.retry?.attempts || 0;
299
- let lastError: any;
300
-
301
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
302
- try {
303
- // Get customer key for this provider
304
- const customerKey = credentials.customerKeys?.[step.provider];
305
-
306
- // Execute the API call
307
- const apiResult = await executeAPICall(
308
- step.provider,
309
- step.action,
310
- resolvedParams,
311
- credentials.userId,
312
- customerKey
313
- );
314
-
315
- if (!apiResult.success) {
316
- throw new StepError(apiResult.error || 'API call failed', apiResult.code || 'PROVIDER_ERROR');
317
- }
318
-
319
- // Success!
320
- stepTrace.success = true;
321
- stepTrace.output = apiResult.data;
322
- stepTrace.cost = apiResult.cost ? { cents: Math.round(apiResult.cost * 100) } : undefined;
323
-
324
- // Update context
325
- context.results[step.id] = apiResult.data;
326
- context.prevStepId = step.id;
327
-
328
- // Update result
329
- result.completedSteps.push(step.id);
330
- if (stepTrace.cost) {
331
- result.totalCost.cents += stepTrace.cost.cents;
332
- }
333
-
334
- return apiResult.data;
335
-
336
- } catch (error: any) {
337
- lastError = error;
338
- stepTrace.retries = attempt;
339
-
340
- if (attempt < maxRetries) {
341
- // Wait before retry
342
- const backoff = step.onError?.retry?.backoff?.[attempt] || 1000 * Math.pow(2, attempt);
343
- await sleep(backoff);
344
- }
345
- }
346
- }
347
-
348
- // All retries exhausted
349
- throw lastError;
350
-
351
- } catch (error: any) {
352
- stepTrace.success = false;
353
- stepTrace.error = error.message;
354
- stepTrace.errorCode = error.code;
355
-
356
- // Handle error based on policy
357
- const shouldAbort = step.onError?.abort !== false && errorPolicy?.mode !== 'best-effort';
358
-
359
- // Try fallback if configured
360
- if (step.onError?.fallback && !options.dryRun) {
361
- try {
362
- const fallbackResult = await executeSingleStep(
363
- step.onError.fallback,
364
- context,
365
- credentials,
366
- options,
367
- result,
368
- errorPolicy
369
- );
370
-
371
- // Use fallback result as this step's result
372
- context.results[step.id] = fallbackResult;
373
- context.prevStepId = step.id;
374
- stepTrace.success = true;
375
- stepTrace.output = { fallback: true, result: fallbackResult };
376
- result.completedSteps.push(step.id);
377
-
378
- return fallbackResult;
379
- } catch (fallbackError: any) {
380
- // Fallback also failed
381
- stepTrace.error = `Original: ${error.message}; Fallback: ${fallbackError.message}`;
382
- }
383
- }
384
-
385
- result.failedStep = stepTrace;
386
-
387
- if (shouldAbort) {
388
- throw error;
389
- }
390
-
391
- // Best-effort mode: continue despite failure
392
- context.results[step.id] = { error: error.message };
393
- context.prevStepId = step.id;
394
- return { error: error.message };
395
-
396
- } finally {
397
- stepTrace.completedAt = new Date().toISOString();
398
- stepTrace.latencyMs = Date.now() - stepStart;
399
- result.trace.push(stepTrace);
400
- options.onStepComplete?.(stepTrace);
401
- }
402
- }
403
-
404
- // ============================================================================
405
- // PARALLEL EXECUTION
406
- // ============================================================================
407
-
408
- async function executeParallelStep(
409
- step: ParallelStep,
410
- context: ChainContext,
411
- credentials: Credentials,
412
- options: ChainOptions,
413
- result: ChainResult
414
- ): Promise<any[]> {
415
- const parallelResults = await Promise.all(
416
- step.parallel.map(async (ps, idx) => {
417
- // Create a copy of context for each parallel step
418
- const parallelContext: ChainContext = {
419
- ...context,
420
- currentIndex: context.currentIndex,
421
- };
422
-
423
- try {
424
- return await executeSingleStep(ps, parallelContext, credentials, options, result);
425
- } catch (error) {
426
- // Return error as result for best-effort
427
- return { error: (error as Error).message };
428
- }
429
- })
430
- );
431
-
432
- // Store parallel results
433
- context.parallelResults = parallelResults;
434
-
435
- // Copy results from parallel steps to main context
436
- for (let i = 0; i < step.parallel.length; i++) {
437
- const ps = step.parallel[i];
438
- context.results[ps.id] = parallelResults[i];
439
- }
440
-
441
- // Last parallel step becomes prev
442
- context.prevStepId = step.parallel[step.parallel.length - 1].id;
443
-
444
- return parallelResults;
445
- }
446
-
447
- // ============================================================================
448
- // CONDITIONAL EXECUTION
449
- // ============================================================================
450
-
451
- async function executeConditionalStep(
452
- step: ConditionalStep,
453
- context: ChainContext,
454
- credentials: Credentials,
455
- options: ChainOptions,
456
- result: ChainResult
457
- ): Promise<any> {
458
- // Evaluate condition
459
- const conditionResult = evaluateCondition(step.if, context);
460
-
461
- // Choose branch
462
- const branch = conditionResult ? step.then : step.else;
463
-
464
- if (!branch) {
465
- // No else branch and condition is false
466
- return null;
467
- }
468
-
469
- // Execute branch (can be single step or array)
470
- const steps = Array.isArray(branch) ? branch : [branch];
471
- let lastResult: any;
472
-
473
- for (const branchStep of steps) {
474
- lastResult = await executeSingleStep(branchStep, context, credentials, options, result);
475
- }
476
-
477
- return lastResult;
478
- }
479
-
480
- // ============================================================================
481
- // FOREACH EXECUTION
482
- // ============================================================================
483
-
484
- async function executeForEachStep(
485
- step: ForEachStep,
486
- context: ChainContext,
487
- credentials: Credentials,
488
- options: ChainOptions,
489
- result: ChainResult,
490
- limits?: ChainLimits
491
- ): Promise<any[]> {
492
- // Resolve the array to iterate over
493
- const arrayRef = step.forEach;
494
- let items: any[];
495
-
496
- // Handle reference vs direct array
497
- if (arrayRef.startsWith('$')) {
498
- // It's a reference - resolve it
499
- const resolved = resolveReferences({ items: arrayRef }, context);
500
- items = resolved.items;
501
- } else {
502
- // Try to parse as JSON array
503
- try {
504
- items = JSON.parse(arrayRef);
505
- } catch {
506
- throw new Error(`forEach value must be a reference or JSON array: ${arrayRef}`);
507
- }
508
- }
509
-
510
- if (!Array.isArray(items)) {
511
- throw new Error(`forEach target must resolve to an array, got: ${typeof items}`);
512
- }
513
-
514
- // Check max iterations
515
- if (limits?.maxSteps && items.length > limits.maxSteps) {
516
- throw new Error(`forEach exceeds maxSteps limit (${items.length} iterations)`);
517
- }
518
-
519
- const forEachResults: any[] = [];
520
-
521
- for (let i = 0; i < items.length; i++) {
522
- // Set up forEach context
523
- context.forEachItem = items[i];
524
- context.forEachIndex = i;
525
- context.forEachResults = forEachResults;
526
-
527
- // Create step with dynamic ID
528
- const dynamicStep: ChainStep = {
529
- ...step.do,
530
- id: step.do.id.replace(/\$index/g, String(i)),
531
- };
532
-
533
- const itemResult = await executeSingleStep(
534
- dynamicStep,
535
- context,
536
- credentials,
537
- options,
538
- result
539
- );
540
-
541
- forEachResults.push(itemResult);
542
- }
543
-
544
- // Clean up forEach context
545
- delete context.forEachItem;
546
- delete context.forEachIndex;
547
- context.forEachResults = forEachResults;
548
-
549
- // Store aggregate results
550
- context.results['$forEach'] = { results: forEachResults };
551
-
552
- return forEachResults;
553
- }
554
-
555
- // ============================================================================
556
- // ROLLBACK EXECUTION
557
- // ============================================================================
558
-
559
- async function executeRollback(
560
- rollbackSteps: RollbackStep[],
561
- context: ChainContext,
562
- credentials: Credentials,
563
- options: ChainOptions,
564
- result: ChainResult
565
- ): Promise<void> {
566
- for (const rb of rollbackSteps) {
567
- try {
568
- const shouldRollback = evaluateCondition(rb.if, context);
569
-
570
- if (shouldRollback) {
571
- await executeSingleStep(rb.do, context, credentials, { ...options, verbose: false }, result);
572
- }
573
- } catch (error) {
574
- // Log but don't fail on rollback errors
575
- console.error('[Chain] Rollback failed:', error);
576
- }
577
- }
578
- }
579
-
580
- // ============================================================================
581
- // INPUT VALIDATION
582
- // ============================================================================
583
-
584
- function validateInputs(inputs: Record<string, any>, definitions: Record<string, InputDefinition>): void {
585
- for (const [name, def] of Object.entries(definitions)) {
586
- const value = inputs[name];
587
-
588
- // Check required
589
- if (def.required && value === undefined) {
590
- if (def.default !== undefined) {
591
- inputs[name] = def.default;
592
- } else {
593
- throw new Error(`Missing required input: ${name}`);
594
- }
595
- }
596
-
597
- // Apply default
598
- if (value === undefined && def.default !== undefined) {
599
- inputs[name] = def.default;
600
- }
601
-
602
- // Type check (if value provided)
603
- if (inputs[name] !== undefined) {
604
- const actualType = Array.isArray(inputs[name]) ? 'array' : typeof inputs[name];
605
- if (actualType !== def.type) {
606
- throw new Error(`Input '${name}' must be ${def.type}, got ${actualType}`);
607
- }
608
- }
609
- }
610
- }
611
-
612
- // ============================================================================
613
- // UTILITIES
614
- // ============================================================================
615
-
616
- function generateChainId(): string {
617
- return `chain_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
618
- }
619
-
620
- function sleep(ms: number): Promise<void> {
621
- return new Promise(resolve => setTimeout(resolve, ms));
622
- }
623
-
624
- // ============================================================================
625
- // CUSTOM ERRORS
626
- // ============================================================================
627
-
628
- export class StepError extends Error {
629
- code: string;
630
- retryAfter?: number;
631
-
632
- constructor(message: string, code: string, retryAfter?: number) {
633
- super(message);
634
- this.name = 'StepError';
635
- this.code = code;
636
- this.retryAfter = retryAfter;
637
- }
638
- }
639
-
640
- export class TimeoutError extends Error {
641
- code = 'TIMEOUT';
642
-
643
- constructor(message: string) {
644
- super(message);
645
- this.name = 'TimeoutError';
646
- }
647
- }
648
-
649
- // ============================================================================
650
- // CHAIN STATUS & RESUME (Stubs for future implementation)
651
- // ============================================================================
652
-
653
- // In-memory store for running chains (would be Redis/DB in production)
654
- const runningChains = new Map<string, { status: string; result?: ChainResult }>();
655
-
656
- /**
657
- * Get status of a running or completed chain
658
- */
659
- export async function getChainStatus(chainId: string): Promise<{
660
- chainId: string;
661
- status: 'running' | 'completed' | 'failed' | 'not_found';
662
- result?: ChainResult;
663
- }> {
664
- const entry = runningChains.get(chainId);
665
-
666
- if (!entry) {
667
- return { chainId, status: 'not_found' };
668
- }
669
-
670
- return {
671
- chainId,
672
- status: entry.status as 'running' | 'completed' | 'failed',
673
- result: entry.result,
674
- };
675
- }
676
-
677
- /**
678
- * Resume a failed chain from a resume token
679
- */
680
- export async function resumeChain(
681
- resumeToken: string,
682
- chain: ChainDefinition,
683
- credentials: Credentials,
684
- inputs?: Record<string, any>,
685
- overrides?: Record<string, Record<string, any>>,
686
- options: ChainOptions = {}
687
- ): Promise<ChainResult> {
688
- // Parse resume token: chain_xyz_step_N
689
- const match = resumeToken.match(/^(.+)_step_(\d+)$/);
690
-
691
- if (!match) {
692
- throw new Error(`Invalid resume token: ${resumeToken}`);
693
- }
694
-
695
- const [, chainId, stepIndexStr] = match;
696
- const resumeFromIndex = parseInt(stepIndexStr, 10);
697
-
698
- // Create a modified chain starting from the resume point
699
- const resumedChain: ChainDefinition = {
700
- ...chain,
701
- id: chainId,
702
- steps: chain.steps.slice(resumeFromIndex),
703
- };
704
-
705
- // Apply any overrides to the resumed steps
706
- if (overrides) {
707
- for (const step of resumedChain.steps) {
708
- if ('id' in step && overrides[step.id]) {
709
- step.params = { ...step.params, ...overrides[step.id] };
710
- }
711
- }
712
- }
713
-
714
- // Execute the resumed chain
715
- // Note: In a real implementation, we'd restore the context from the previous run
716
- return executeChain(resumedChain, credentials, inputs, options);
717
- }
718
-
719
- // ============================================================================
720
- // RE-EXPORTS
721
- // ============================================================================
722
-
723
- export {
724
- ChainContext,
725
- ChainStep,
726
- ChainStepUnion,
727
- resolveReferences,
728
- validateReferences,
729
- evaluateCondition,
730
- } from './chainResolver.js';