@centrali-io/centrali-sdk 4.4.2 → 4.4.5

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 (4) hide show
  1. package/README.md +110 -8
  2. package/dist/index.js +148 -8
  3. package/index.ts +215 -7
  4. package/package.json +1 -1
package/README.md CHANGED
@@ -4,6 +4,8 @@ Official Node.js SDK for Centrali - Build modern web applications without managi
4
4
 
5
5
  [![npm version](https://badge.fury.io/js/%40centrali-io%2Fcentrali-sdk.svg)](https://www.npmjs.com/package/@centrali-io/centrali-sdk)
6
6
 
7
+ > **Full documentation:** [docs.centrali.io](https://docs.centrali.io) — SDK guide, API reference, compute functions, orchestrations, and more.
8
+
7
9
  > **Try it now!** Explore the SDK in our [Live Playground on StackBlitz](https://stackblitz.com/~/github.com/centrali-demo/sdk-playground) - no setup required.
8
10
 
9
11
  ## Installation
@@ -20,7 +22,7 @@ import { CentraliSDK } from '@centrali-io/centrali-sdk';
20
22
  // Initialize the SDK
21
23
  const centrali = new CentraliSDK({
22
24
  baseUrl: 'https://centrali.io',
23
- workspaceId: 'your-workspace',
25
+ workspaceId: 'your-workspace-slug', // This is the workspace slug, not a UUID
24
26
  token: 'your-api-key'
25
27
  });
26
28
 
@@ -40,7 +42,16 @@ console.log('Found:', results.data.totalHits, 'results');
40
42
 
41
43
  ## Authentication
42
44
 
43
- The SDK supports three authentication methods. See the [full authentication guide](../docs/sdk/authentication.md) for details.
45
+ The SDK supports three authentication methods. See the [full authentication guide](https://docs.centrali.io/guides/centrali-sdk#authentication) for details.
46
+
47
+ ### Recommended Auth by Context
48
+
49
+ | Context | Method | Why |
50
+ |---------|--------|-----|
51
+ | **Browser / frontend app** | Publishable key | Safe to expose in client code, scoped to specific resources |
52
+ | **Server app / API route** | Service account | Server-to-server, automatic token refresh |
53
+ | **MCP agent** | Service account (env vars) | `CENTRALI_CLIENT_ID` + `CENTRALI_CLIENT_SECRET` + `CENTRALI_WORKSPACE_ID` |
54
+ | **App with its own auth (Clerk, Auth0)** | External token / BYOT | Dynamic token callback |
44
55
 
45
56
  ### Publishable Key (Frontend Apps)
46
57
 
@@ -49,7 +60,7 @@ Safe to use in browser code. Scoped to specific resources.
49
60
  ```typescript
50
61
  const centrali = new CentraliSDK({
51
62
  baseUrl: 'https://centrali.io',
52
- workspaceId: 'your-workspace',
63
+ workspaceId: 'your-workspace-slug',
53
64
  publishableKey: 'pk_live_your_key_here'
54
65
  });
55
66
  ```
@@ -61,7 +72,7 @@ Dynamic token callback for apps with their own auth.
61
72
  ```typescript
62
73
  const centrali = new CentraliSDK({
63
74
  baseUrl: 'https://centrali.io',
64
- workspaceId: 'your-workspace',
75
+ workspaceId: 'your-workspace-slug',
65
76
  getToken: async () => await clerk.session.getToken()
66
77
  });
67
78
  ```
@@ -73,12 +84,14 @@ Never use in browser code. Client secret must stay on the server.
73
84
  ```typescript
74
85
  const centrali = new CentraliSDK({
75
86
  baseUrl: 'https://centrali.io',
76
- workspaceId: 'your-workspace',
87
+ workspaceId: 'your-workspace-slug',
77
88
  clientId: process.env.CENTRALI_CLIENT_ID,
78
89
  clientSecret: process.env.CENTRALI_CLIENT_SECRET
79
90
  });
80
91
  ```
81
92
 
93
+ > **Note:** `workspaceId` is always the **workspace slug** (e.g., `"acme"`), not a UUID.
94
+
82
95
  ## Features
83
96
 
84
97
  - ✅ **Type-safe API** with full TypeScript support
@@ -403,17 +416,106 @@ const realtime = new RealtimeManager(
403
416
  );
404
417
  ```
405
418
 
406
- ### Compute Functions (via Triggers)
419
+ ### Compute Functions
420
+
421
+ Compute functions are JavaScript code blocks that execute in a sandboxed environment. Every function uses the same signature:
422
+
423
+ ```javascript
424
+ async function run() {
425
+ // Three variables are available:
426
+ // - api: SDK for records, HTTP, files, crypto, logging
427
+ // - triggerParams: static config from the trigger definition
428
+ // - executionParams: dynamic data from the current invocation
429
+
430
+ const result = await api.httpRequest({
431
+ url: 'https://api.example.com/data',
432
+ method: 'POST',
433
+ body: JSON.stringify(executionParams.payload)
434
+ });
435
+
436
+ return { success: true, data: result };
437
+ }
438
+ ```
439
+
440
+ > **Important:** Use `async function run() { ... }`. Do NOT use `module.exports`.
441
+
442
+ #### Compute Input Contract
443
+
444
+ What `triggerParams` and `executionParams` contain depends on how the function is invoked:
445
+
446
+ | Trigger type | `triggerParams` | `executionParams` |
447
+ |--------------|-----------------|-------------------|
448
+ | **HTTP trigger** | Static params from trigger definition | `{ payload }` — parsed request body |
449
+ | **Endpoint trigger** | Static params from trigger definition | `{ payload, method, headers, query }` — full HTTP context |
450
+ | **Scheduled trigger** | Static params from trigger definition (max 64KB) | `{}` — empty |
451
+ | **Pages action** | `{ input, token }` — from page action invocation | `{}` — empty |
452
+ | **Orchestration step** | Orchestration input + previous step outputs + decrypted encrypted params | Not used (all input arrives via `triggerParams`) |
453
+
454
+ #### The `api` Object
455
+
456
+ Every compute function has access to `api`, which provides:
457
+
458
+ | Category | Methods |
459
+ |----------|---------|
460
+ | **Records** | `queryRecords`, `fetchRecord`, `createRecord`, `updateRecord`, `deleteRecord`, `bulkCreateRecords`, `bulkUpdateRecords`, `bulkDeleteRecords` |
461
+ | **HTTP** | `httpRequest`, `httpFetch` (outbound calls to allowed domains) |
462
+ | **Files** | `storeFile`, `storeAsCSV`, `storeAsJSON` |
463
+ | **Crypto** | `crypto.sha256`, `crypto.hmacSha256`, `crypto.rsaSign`, `crypto.signJwt` |
464
+ | **Utilities** | `uuid`, `formatDate`, `chunk`, `merge`, `math`, `evaluate`, `renderTemplate`, `log`, `logError` |
465
+ | **Conversion** | `toCSV`, `toJSON` |
466
+
467
+ #### Secrets in Compute Functions
468
+
469
+ Compute functions have **no built-in environment variables or secrets field**. To pass secrets (API keys, credentials) to a compute function:
470
+
471
+ - **Recommended:** Wrap the function in an orchestration and use **encrypted params** on the compute step. Encrypted params are stored with AES-256-GCM at rest and decrypted at execution time — they arrive in `triggerParams`.
472
+ - **Alternative:** Pass secrets in the trigger invocation payload via `executionParams`. This works but means the calling app is the courier for the secret.
473
+
474
+ See [Orchestrations](#orchestrations) for encrypted params usage.
475
+
476
+ #### Invoking Triggers
477
+
478
+ Trigger invocation is **asynchronous** — it returns a job ID, not the execution result. Use the function runs API to poll for the result.
407
479
 
408
480
  ```typescript
409
- // Invoke an on-demand trigger to execute a compute function
481
+ // Invoke an on-demand trigger
410
482
  const job = await centrali.triggers.invoke('trigger-id', {
411
483
  payload: { data: 'your-input-data' }
412
484
  });
413
-
414
485
  console.log('Job queued:', job.data);
486
+
487
+ // Poll for the result using function runs
488
+ // (The job ID maps to a function run — query by trigger to find it)
489
+ const runs = await centrali.runs.listByTrigger('trigger-id', { limit: 1 });
490
+ const latestRun = runs.data.data[0];
491
+ console.log('Status:', latestRun.status); // pending | running | completed | failure | timeout
492
+ console.log('Result:', latestRun.runData); // execution output (once completed)
493
+ console.log('Error:', latestRun.errorMessage); // error details (if failed)
494
+ ```
495
+
496
+ #### Function Runs (Execution History)
497
+
498
+ Query execution history for debugging and observability:
499
+
500
+ ```typescript
501
+ // Get a specific run by ID
502
+ const run = await centrali.runs.get('run-uuid');
503
+ console.log('Status:', run.data.status);
504
+ console.log('Output:', run.data.runData);
505
+ console.log('Duration:', run.data.startedAt, '→', run.data.endedAt);
506
+
507
+ // List runs for a trigger (most recent first)
508
+ const triggerRuns = await centrali.runs.listByTrigger('trigger-uuid', {
509
+ status: 'failure', // Filter by status
510
+ limit: 10
511
+ });
512
+
513
+ // List runs for a function
514
+ const functionRuns = await centrali.runs.listByFunction('function-uuid');
415
515
  ```
416
516
 
517
+ Run statuses: `pending` → `running` → `completed` | `failure` | `timeout`
518
+
417
519
  ### File Uploads
418
520
 
419
521
  ```typescript
package/dist/index.js CHANGED
@@ -51,7 +51,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
51
51
  return (mod && mod.__esModule) ? mod : { "default": mod };
52
52
  };
53
53
  Object.defineProperty(exports, "__esModule", { value: true });
54
- exports.CentraliSDK = exports.ComputeFunctionsManager = exports.CollectionsManager = exports.StructuresManager = exports.AllowedDomainsManager = exports.ValidationManager = exports.AnomalyInsightsManager = exports.SmartQueriesManager = exports.TriggersManager = exports.OrchestrationsManager = exports.RealtimeManager = exports.CentraliError = void 0;
54
+ exports.CentraliSDK = exports.FunctionRunsManager = exports.ComputeFunctionsManager = exports.CollectionsManager = exports.StructuresManager = exports.AllowedDomainsManager = exports.ValidationManager = exports.AnomalyInsightsManager = exports.SmartQueriesManager = exports.TriggersManager = exports.OrchestrationsManager = exports.RealtimeManager = exports.CentraliError = void 0;
55
55
  exports.isCentraliError = isCentraliError;
56
56
  exports.getApiUrl = getApiUrl;
57
57
  exports.getAuthUrl = getAuthUrl;
@@ -84,6 +84,9 @@ exports.getCollectionBySlugApiPath = getCollectionBySlugApiPath;
84
84
  exports.getCollectionValidateApiPath = getCollectionValidateApiPath;
85
85
  exports.getComputeFunctionsApiPath = getComputeFunctionsApiPath;
86
86
  exports.getComputeFunctionTestApiPath = getComputeFunctionTestApiPath;
87
+ exports.getFunctionRunsApiPath = getFunctionRunsApiPath;
88
+ exports.getFunctionRunsByTriggerApiPath = getFunctionRunsByTriggerApiPath;
89
+ exports.getFunctionRunsByFunctionApiPath = getFunctionRunsByFunctionApiPath;
87
90
  exports.getSmartQueryTestApiPath = getSmartQueryTestApiPath;
88
91
  exports.getValidationSuggestionsApiPath = getValidationSuggestionsApiPath;
89
92
  exports.getValidationSuggestionAcceptApiPath = getValidationSuggestionAcceptApiPath;
@@ -656,6 +659,28 @@ function getComputeFunctionTestApiPath(workspaceId) {
656
659
  return `data/workspace/${workspaceId}/api/v1/compute-functions/test`;
657
660
  }
658
661
  // =====================================================
662
+ // Function Runs API Path Helpers
663
+ // =====================================================
664
+ /**
665
+ * Generate Function Runs base API URL PATH.
666
+ */
667
+ function getFunctionRunsApiPath(workspaceId, runId) {
668
+ const basePath = `data/workspace/${workspaceId}/api/v1/function-runs`;
669
+ return runId ? `${basePath}/${runId}` : basePath;
670
+ }
671
+ /**
672
+ * Generate Function Runs by trigger API URL PATH.
673
+ */
674
+ function getFunctionRunsByTriggerApiPath(workspaceId, triggerId) {
675
+ return `data/workspace/${workspaceId}/api/v1/function-runs/trigger/${triggerId}`;
676
+ }
677
+ /**
678
+ * Generate Function Runs by function API URL PATH.
679
+ */
680
+ function getFunctionRunsByFunctionApiPath(workspaceId, functionId) {
681
+ return `data/workspace/${workspaceId}/api/v1/function-runs/function/${functionId}`;
682
+ }
683
+ // =====================================================
659
684
  // Smart Query Test API Path Helper (Configuration-as-Code)
660
685
  // =====================================================
661
686
  /**
@@ -2382,12 +2407,12 @@ exports.CollectionsManager = CollectionsManager;
2382
2407
  * // Create a new function
2383
2408
  * const fn = await client.functions.create({
2384
2409
  * name: 'Process Order',
2385
- * code: 'module.exports = async (ctx) => { return { processed: true }; }'
2410
+ * code: 'async function run() { return { processed: true }; }'
2386
2411
  * });
2387
2412
  *
2388
2413
  * // Test execute code without saving
2389
2414
  * const result = await client.functions.testExecute({
2390
- * code: 'module.exports = async (ctx) => { return ctx.executionParams; }',
2415
+ * code: 'async function run() { return executionParams; }',
2391
2416
  * params: { orderId: '123' }
2392
2417
  * });
2393
2418
  * ```
@@ -2439,7 +2464,7 @@ class ComputeFunctionsManager {
2439
2464
  * ```ts
2440
2465
  * const fn = await client.functions.create({
2441
2466
  * name: 'Process Order',
2442
- * code: 'module.exports = async (ctx) => { return { processed: true }; }',
2467
+ * code: 'async function run() { return { processed: true }; }',
2443
2468
  * description: 'Processes incoming orders',
2444
2469
  * timeoutMs: 60000
2445
2470
  * });
@@ -2459,7 +2484,7 @@ class ComputeFunctionsManager {
2459
2484
  * @example
2460
2485
  * ```ts
2461
2486
  * const updated = await client.functions.update('function-uuid', {
2462
- * code: 'module.exports = async (ctx) => { return { v2: true }; }',
2487
+ * code: 'async function run() { return { v2: true }; }',
2463
2488
  * timeoutMs: 120000
2464
2489
  * });
2465
2490
  * ```
@@ -2492,7 +2517,7 @@ class ComputeFunctionsManager {
2492
2517
  * @example
2493
2518
  * ```ts
2494
2519
  * const result = await client.functions.testExecute({
2495
- * code: 'module.exports = async (ctx) => { return { sum: ctx.executionParams.a + ctx.executionParams.b }; }',
2520
+ * code: 'async function run() { return { sum: executionParams.a + executionParams.b }; }',
2496
2521
  * params: { a: 1, b: 2 }
2497
2522
  * });
2498
2523
  * console.log('Output:', result.data.output); // { sum: 3 }
@@ -2505,6 +2530,97 @@ class ComputeFunctionsManager {
2505
2530
  }
2506
2531
  }
2507
2532
  exports.ComputeFunctionsManager = ComputeFunctionsManager;
2533
+ /**
2534
+ * Manager for querying function execution runs.
2535
+ *
2536
+ * Provides read access to function run history — useful for checking
2537
+ * whether jobs completed, inspecting outputs, and monitoring trigger activity.
2538
+ *
2539
+ * Access via `client.runs`.
2540
+ */
2541
+ class FunctionRunsManager {
2542
+ constructor(workspaceId, requestFn) {
2543
+ this.workspaceId = workspaceId;
2544
+ this.requestFn = requestFn;
2545
+ }
2546
+ /**
2547
+ * Get a function run by ID.
2548
+ *
2549
+ * @param runId - The function run UUID
2550
+ * @returns The function run details
2551
+ *
2552
+ * @example
2553
+ * ```ts
2554
+ * const run = await client.runs.get('run-uuid');
2555
+ * console.log('Status:', run.data.status);
2556
+ * console.log('Duration:', run.data.endedAt ? Date.parse(run.data.endedAt) - Date.parse(run.data.startedAt) : 'still running');
2557
+ * ```
2558
+ */
2559
+ get(runId) {
2560
+ const path = getFunctionRunsApiPath(this.workspaceId, runId);
2561
+ return this.requestFn('GET', path);
2562
+ }
2563
+ /**
2564
+ * List runs for a specific trigger.
2565
+ *
2566
+ * @param triggerId - The trigger UUID
2567
+ * @param options - Optional pagination and status filter
2568
+ * @returns Paginated list of function runs
2569
+ *
2570
+ * @example
2571
+ * ```ts
2572
+ * // List recent runs for a trigger
2573
+ * const runs = await client.runs.listByTrigger('trigger-uuid');
2574
+ *
2575
+ * // Filter to only failed runs
2576
+ * const failed = await client.runs.listByTrigger('trigger-uuid', {
2577
+ * status: 'failure'
2578
+ * });
2579
+ * ```
2580
+ */
2581
+ listByTrigger(triggerId, options) {
2582
+ const path = getFunctionRunsByTriggerApiPath(this.workspaceId, triggerId);
2583
+ const queryParams = {};
2584
+ if (options === null || options === void 0 ? void 0 : options.page)
2585
+ queryParams.page = options.page;
2586
+ if (options === null || options === void 0 ? void 0 : options.limit)
2587
+ queryParams.limit = options.limit;
2588
+ if (options === null || options === void 0 ? void 0 : options.status)
2589
+ queryParams.status = options.status;
2590
+ return this.requestFn('GET', path, null, queryParams);
2591
+ }
2592
+ /**
2593
+ * List runs for a specific compute function.
2594
+ *
2595
+ * @param functionId - The compute function UUID
2596
+ * @param options - Optional pagination and status filter
2597
+ * @returns Paginated list of function runs
2598
+ *
2599
+ * @example
2600
+ * ```ts
2601
+ * // List recent runs for a function
2602
+ * const runs = await client.runs.listByFunction('function-uuid');
2603
+ *
2604
+ * // Only completed runs, page 2
2605
+ * const completed = await client.runs.listByFunction('function-uuid', {
2606
+ * status: 'completed',
2607
+ * page: 2
2608
+ * });
2609
+ * ```
2610
+ */
2611
+ listByFunction(functionId, options) {
2612
+ const path = getFunctionRunsByFunctionApiPath(this.workspaceId, functionId);
2613
+ const queryParams = {};
2614
+ if (options === null || options === void 0 ? void 0 : options.page)
2615
+ queryParams.page = options.page;
2616
+ if (options === null || options === void 0 ? void 0 : options.limit)
2617
+ queryParams.limit = options.limit;
2618
+ if (options === null || options === void 0 ? void 0 : options.status)
2619
+ queryParams.status = options.status;
2620
+ return this.requestFn('GET', path, null, queryParams);
2621
+ }
2622
+ }
2623
+ exports.FunctionRunsManager = FunctionRunsManager;
2508
2624
  /**
2509
2625
  * Main Centrali SDK client.
2510
2626
  */
@@ -2521,6 +2637,7 @@ class CentraliSDK {
2521
2637
  this._structures = null;
2522
2638
  this._collections = null;
2523
2639
  this._functions = null;
2640
+ this._runs = null;
2524
2641
  this.isRefreshingToken = false;
2525
2642
  this.tokenRefreshPromise = null;
2526
2643
  this.options = options;
@@ -2897,12 +3014,12 @@ class CentraliSDK {
2897
3014
  * // Create a function
2898
3015
  * const fn = await client.functions.create({
2899
3016
  * name: 'Process Order',
2900
- * code: 'module.exports = async (ctx) => { return { ok: true }; }'
3017
+ * code: 'async function run() { return { ok: true }; }'
2901
3018
  * });
2902
3019
  *
2903
3020
  * // Test execute without saving
2904
3021
  * const result = await client.functions.testExecute({
2905
- * code: 'module.exports = async (ctx) => { return ctx.executionParams; }',
3022
+ * code: 'async function run() { return executionParams; }',
2906
3023
  * params: { test: true }
2907
3024
  * });
2908
3025
  * ```
@@ -2913,6 +3030,29 @@ class CentraliSDK {
2913
3030
  }
2914
3031
  return this._functions;
2915
3032
  }
3033
+ /**
3034
+ * Runs namespace for querying execution history.
3035
+ *
3036
+ * Usage:
3037
+ * ```ts
3038
+ * // Get a specific run
3039
+ * const run = await client.runs.get('run-id');
3040
+ *
3041
+ * // List runs for a trigger
3042
+ * const runs = await client.runs.listByTrigger('trigger-id');
3043
+ *
3044
+ * // List failed runs for a compute definition
3045
+ * const failed = await client.runs.listByFunction('fn-id', {
3046
+ * status: 'failure'
3047
+ * });
3048
+ * ```
3049
+ */
3050
+ get runs() {
3051
+ if (!this._runs) {
3052
+ this._runs = new FunctionRunsManager(this.options.workspaceId, this.request.bind(this));
3053
+ }
3054
+ return this._runs;
3055
+ }
2916
3056
  /**
2917
3057
  * Manually set or update the bearer token for subsequent requests.
2918
3058
  */
package/index.ts CHANGED
@@ -1780,6 +1780,66 @@ export interface TestComputeFunctionResult {
1780
1780
  error?: string;
1781
1781
  }
1782
1782
 
1783
+ // =====================================================
1784
+ // Function Run Types
1785
+ // =====================================================
1786
+
1787
+ /**
1788
+ * Execution source for a function run.
1789
+ */
1790
+ export type FunctionRunExecutionSource = 'trigger' | 'rerun' | 'manual' | 'scheduled' | 'http-trigger' | 'orchestration' | 'endpoint';
1791
+
1792
+ /**
1793
+ * Status of a function run.
1794
+ */
1795
+ export type FunctionRunStatus = 'pending' | 'running' | 'completed' | 'failure' | 'timeout';
1796
+
1797
+ /**
1798
+ * A function run record representing a single execution of a compute function.
1799
+ */
1800
+ export interface FunctionRun {
1801
+ id: string;
1802
+ createdBy: string;
1803
+ functionId: string;
1804
+ workspaceSlug: string;
1805
+ jobId: string;
1806
+ status: FunctionRunStatus;
1807
+ runData: any | null;
1808
+ startedAt: string;
1809
+ endedAt?: string | null;
1810
+ createdAt?: string;
1811
+ updatedAt?: string;
1812
+ executionId: string;
1813
+ triggerId?: string | null;
1814
+ triggerType?: string | null;
1815
+ orchestrationRunId?: string | null;
1816
+ orchestrationStepId?: string | null;
1817
+ originalRunId?: string | null;
1818
+ isRerun: boolean;
1819
+ rerunCount: number;
1820
+ rerunBy?: string | null;
1821
+ rerunReason?: string | null;
1822
+ functionCodeHash?: string | null;
1823
+ functionVersion?: string | null;
1824
+ executionSource: FunctionRunExecutionSource;
1825
+ memoryUsageBytes?: number | null;
1826
+ cpuUsageSeconds?: number | null;
1827
+ errorCode?: string | null;
1828
+ errorMessage?: string | null;
1829
+ dataStrippedAt?: string | null;
1830
+ archiveStorageAddress?: string | null;
1831
+ archivedAt?: string | null;
1832
+ }
1833
+
1834
+ /**
1835
+ * Options for listing function runs by trigger or function.
1836
+ */
1837
+ export interface ListFunctionRunsOptions {
1838
+ page?: number;
1839
+ limit?: number;
1840
+ status?: FunctionRunStatus;
1841
+ }
1842
+
1783
1843
  // =====================================================
1784
1844
  // Trigger CRUD Types (Configuration-as-Code)
1785
1845
  // =====================================================
@@ -2734,6 +2794,32 @@ export function getComputeFunctionTestApiPath(workspaceId: string): string {
2734
2794
  return `data/workspace/${workspaceId}/api/v1/compute-functions/test`;
2735
2795
  }
2736
2796
 
2797
+ // =====================================================
2798
+ // Function Runs API Path Helpers
2799
+ // =====================================================
2800
+
2801
+ /**
2802
+ * Generate Function Runs base API URL PATH.
2803
+ */
2804
+ export function getFunctionRunsApiPath(workspaceId: string, runId?: string): string {
2805
+ const basePath = `data/workspace/${workspaceId}/api/v1/function-runs`;
2806
+ return runId ? `${basePath}/${runId}` : basePath;
2807
+ }
2808
+
2809
+ /**
2810
+ * Generate Function Runs by trigger API URL PATH.
2811
+ */
2812
+ export function getFunctionRunsByTriggerApiPath(workspaceId: string, triggerId: string): string {
2813
+ return `data/workspace/${workspaceId}/api/v1/function-runs/trigger/${triggerId}`;
2814
+ }
2815
+
2816
+ /**
2817
+ * Generate Function Runs by function API URL PATH.
2818
+ */
2819
+ export function getFunctionRunsByFunctionApiPath(workspaceId: string, functionId: string): string {
2820
+ return `data/workspace/${workspaceId}/api/v1/function-runs/function/${functionId}`;
2821
+ }
2822
+
2737
2823
  // =====================================================
2738
2824
  // Smart Query Test API Path Helper (Configuration-as-Code)
2739
2825
  // =====================================================
@@ -4626,12 +4712,12 @@ export class CollectionsManager {
4626
4712
  * // Create a new function
4627
4713
  * const fn = await client.functions.create({
4628
4714
  * name: 'Process Order',
4629
- * code: 'module.exports = async (ctx) => { return { processed: true }; }'
4715
+ * code: 'async function run() { return { processed: true }; }'
4630
4716
  * });
4631
4717
  *
4632
4718
  * // Test execute code without saving
4633
4719
  * const result = await client.functions.testExecute({
4634
- * code: 'module.exports = async (ctx) => { return ctx.executionParams; }',
4720
+ * code: 'async function run() { return executionParams; }',
4635
4721
  * params: { orderId: '123' }
4636
4722
  * });
4637
4723
  * ```
@@ -4692,7 +4778,7 @@ export class ComputeFunctionsManager {
4692
4778
  * ```ts
4693
4779
  * const fn = await client.functions.create({
4694
4780
  * name: 'Process Order',
4695
- * code: 'module.exports = async (ctx) => { return { processed: true }; }',
4781
+ * code: 'async function run() { return { processed: true }; }',
4696
4782
  * description: 'Processes incoming orders',
4697
4783
  * timeoutMs: 60000
4698
4784
  * });
@@ -4713,7 +4799,7 @@ export class ComputeFunctionsManager {
4713
4799
  * @example
4714
4800
  * ```ts
4715
4801
  * const updated = await client.functions.update('function-uuid', {
4716
- * code: 'module.exports = async (ctx) => { return { v2: true }; }',
4802
+ * code: 'async function run() { return { v2: true }; }',
4717
4803
  * timeoutMs: 120000
4718
4804
  * });
4719
4805
  * ```
@@ -4748,7 +4834,7 @@ export class ComputeFunctionsManager {
4748
4834
  * @example
4749
4835
  * ```ts
4750
4836
  * const result = await client.functions.testExecute({
4751
- * code: 'module.exports = async (ctx) => { return { sum: ctx.executionParams.a + ctx.executionParams.b }; }',
4837
+ * code: 'async function run() { return { sum: executionParams.a + executionParams.b }; }',
4752
4838
  * params: { a: 1, b: 2 }
4753
4839
  * });
4754
4840
  * console.log('Output:', result.data.output); // { sum: 3 }
@@ -4761,6 +4847,100 @@ export class ComputeFunctionsManager {
4761
4847
  }
4762
4848
  }
4763
4849
 
4850
+ /**
4851
+ * Manager for querying function execution runs.
4852
+ *
4853
+ * Provides read access to function run history — useful for checking
4854
+ * whether jobs completed, inspecting outputs, and monitoring trigger activity.
4855
+ *
4856
+ * Access via `client.runs`.
4857
+ */
4858
+ export class FunctionRunsManager {
4859
+ private requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>) => Promise<ApiResponse<T>>;
4860
+ private workspaceId: string;
4861
+
4862
+ constructor(
4863
+ workspaceId: string,
4864
+ requestFn: <T>(method: Method, path: string, data?: any, queryParams?: Record<string, any>) => Promise<ApiResponse<T>>
4865
+ ) {
4866
+ this.workspaceId = workspaceId;
4867
+ this.requestFn = requestFn;
4868
+ }
4869
+
4870
+ /**
4871
+ * Get a function run by ID.
4872
+ *
4873
+ * @param runId - The function run UUID
4874
+ * @returns The function run details
4875
+ *
4876
+ * @example
4877
+ * ```ts
4878
+ * const run = await client.runs.get('run-uuid');
4879
+ * console.log('Status:', run.data.status);
4880
+ * console.log('Duration:', run.data.endedAt ? Date.parse(run.data.endedAt) - Date.parse(run.data.startedAt) : 'still running');
4881
+ * ```
4882
+ */
4883
+ public get(runId: string): Promise<ApiResponse<FunctionRun>> {
4884
+ const path = getFunctionRunsApiPath(this.workspaceId, runId);
4885
+ return this.requestFn<FunctionRun>('GET', path);
4886
+ }
4887
+
4888
+ /**
4889
+ * List runs for a specific trigger.
4890
+ *
4891
+ * @param triggerId - The trigger UUID
4892
+ * @param options - Optional pagination and status filter
4893
+ * @returns Paginated list of function runs
4894
+ *
4895
+ * @example
4896
+ * ```ts
4897
+ * // List recent runs for a trigger
4898
+ * const runs = await client.runs.listByTrigger('trigger-uuid');
4899
+ *
4900
+ * // Filter to only failed runs
4901
+ * const failed = await client.runs.listByTrigger('trigger-uuid', {
4902
+ * status: 'failure'
4903
+ * });
4904
+ * ```
4905
+ */
4906
+ public listByTrigger(triggerId: string, options?: ListFunctionRunsOptions): Promise<ApiResponse<PaginatedResponse<FunctionRun>>> {
4907
+ const path = getFunctionRunsByTriggerApiPath(this.workspaceId, triggerId);
4908
+ const queryParams: Record<string, any> = {};
4909
+ if (options?.page) queryParams.page = options.page;
4910
+ if (options?.limit) queryParams.limit = options.limit;
4911
+ if (options?.status) queryParams.status = options.status;
4912
+ return this.requestFn<PaginatedResponse<FunctionRun>>('GET', path, null, queryParams);
4913
+ }
4914
+
4915
+ /**
4916
+ * List runs for a specific compute function.
4917
+ *
4918
+ * @param functionId - The compute function UUID
4919
+ * @param options - Optional pagination and status filter
4920
+ * @returns Paginated list of function runs
4921
+ *
4922
+ * @example
4923
+ * ```ts
4924
+ * // List recent runs for a function
4925
+ * const runs = await client.runs.listByFunction('function-uuid');
4926
+ *
4927
+ * // Only completed runs, page 2
4928
+ * const completed = await client.runs.listByFunction('function-uuid', {
4929
+ * status: 'completed',
4930
+ * page: 2
4931
+ * });
4932
+ * ```
4933
+ */
4934
+ public listByFunction(functionId: string, options?: ListFunctionRunsOptions): Promise<ApiResponse<PaginatedResponse<FunctionRun>>> {
4935
+ const path = getFunctionRunsByFunctionApiPath(this.workspaceId, functionId);
4936
+ const queryParams: Record<string, any> = {};
4937
+ if (options?.page) queryParams.page = options.page;
4938
+ if (options?.limit) queryParams.limit = options.limit;
4939
+ if (options?.status) queryParams.status = options.status;
4940
+ return this.requestFn<PaginatedResponse<FunctionRun>>('GET', path, null, queryParams);
4941
+ }
4942
+ }
4943
+
4764
4944
  /**
4765
4945
  * Main Centrali SDK client.
4766
4946
  */
@@ -4778,6 +4958,7 @@ export class CentraliSDK {
4778
4958
  private _structures: StructuresManager | null = null;
4779
4959
  private _collections: CollectionsManager | null = null;
4780
4960
  private _functions: ComputeFunctionsManager | null = null;
4961
+ private _runs: FunctionRunsManager | null = null;
4781
4962
  private isRefreshingToken: boolean = false;
4782
4963
  private tokenRefreshPromise: Promise<string> | null = null;
4783
4964
 
@@ -5228,12 +5409,12 @@ export class CentraliSDK {
5228
5409
  * // Create a function
5229
5410
  * const fn = await client.functions.create({
5230
5411
  * name: 'Process Order',
5231
- * code: 'module.exports = async (ctx) => { return { ok: true }; }'
5412
+ * code: 'async function run() { return { ok: true }; }'
5232
5413
  * });
5233
5414
  *
5234
5415
  * // Test execute without saving
5235
5416
  * const result = await client.functions.testExecute({
5236
- * code: 'module.exports = async (ctx) => { return ctx.executionParams; }',
5417
+ * code: 'async function run() { return executionParams; }',
5237
5418
  * params: { test: true }
5238
5419
  * });
5239
5420
  * ```
@@ -5248,6 +5429,33 @@ export class CentraliSDK {
5248
5429
  return this._functions;
5249
5430
  }
5250
5431
 
5432
+ /**
5433
+ * Runs namespace for querying execution history.
5434
+ *
5435
+ * Usage:
5436
+ * ```ts
5437
+ * // Get a specific run
5438
+ * const run = await client.runs.get('run-id');
5439
+ *
5440
+ * // List runs for a trigger
5441
+ * const runs = await client.runs.listByTrigger('trigger-id');
5442
+ *
5443
+ * // List failed runs for a compute definition
5444
+ * const failed = await client.runs.listByFunction('fn-id', {
5445
+ * status: 'failure'
5446
+ * });
5447
+ * ```
5448
+ */
5449
+ public get runs(): FunctionRunsManager {
5450
+ if (!this._runs) {
5451
+ this._runs = new FunctionRunsManager(
5452
+ this.options.workspaceId,
5453
+ this.request.bind(this)
5454
+ );
5455
+ }
5456
+ return this._runs;
5457
+ }
5458
+
5251
5459
  /**
5252
5460
  * Manually set or update the bearer token for subsequent requests.
5253
5461
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@centrali-io/centrali-sdk",
3
- "version": "4.4.2",
3
+ "version": "4.4.5",
4
4
  "description": "Centrali Node SDK",
5
5
  "main": "dist/index.js",
6
6
  "type": "commonjs",