@tasker-systems/tasker 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,17 +1,15 @@
1
- import { T as TaskerRuntime, C as ClientTaskResponse, a as ClientTaskListResponse, b as ClientStepResponse, c as ClientStepAuditResponse, d as ClientHealthResponse, F as FfiDomainEvent, H as HandlerDefinitionDto } from './runtime-interface-D940vUzy.js';
2
- export { B as BaseTaskerRuntime, g as ClientPaginationInfo, h as ClientResult, i as ClientStepReadiness, j as ClientTaskRequest, D as DependencyResult, e as FfiBootstrapConfig, f as FfiBootstrapResult, k as FfiDispatchMetrics, L as FfiLogFields, l as FfiStepEvent, q as FfiStopResult, W as FfiWorkerStatus, m as HandlerDefinition, O as OrchestrationMetadata, R as RetryConfiguration, S as StepDefinition, n as StepExecutionError, o as StepExecutionMetadata, p as StepExecutionResult, r as Task, s as WorkflowStep } from './runtime-interface-D940vUzy.js';
3
- import { FfiLayer, FfiLayerConfig } from './ffi/index.js';
4
- export { DenoRuntime, NodeRuntime, RuntimeInfo, RuntimeType, detectRuntime, getLibraryPath, getRuntimeInfo, isBun, isDeno, isNode } from './ffi/index.js';
5
- import { S as StepHandlerResult, a as StepHandler, B as BatchWorkerConfig, b as StepContext, E as ExecutableHandler, c as StepHandlerClass, T as TaskerEventEmitter, d as EventPoller, e as StepExecutionSubscriber, f as EventSystem } from './index-CTl8lGpU.js';
6
- export { y as ErrorCallback, I as ErrorType, n as EventName, o as EventNames, z as EventPollerConfig, F as EventSystemConfig, G as EventSystemStats, A as MetricsCallback, p as MetricsEventName, q as MetricsEventNames, M as MetricsPayload, P as PollerCyclePayload, r as PollerEventName, s as PollerEventNames, C as PollerState, g as StepCompletionSentPayload, L as StepContextParams, D as StepEventCallback, t as StepEventName, u as StepEventNames, h as StepExecutionCompletedPayload, i as StepExecutionFailedPayload, j as StepExecutionReceivedPayload, k as StepExecutionStartedPayload, H as StepExecutionSubscriberConfig, N as StepHandlerResultParams, l as TaskerEventMap, W as WorkerErrorPayload, v as WorkerEventName, w as WorkerEventNames, m as WorkerEventPayload, x as createEventPoller, J as isStandardErrorType, K as isTypicallyRetryable } from './index-CTl8lGpU.js';
1
+ import { NapiModule, FfiLayer, FfiDomainEvent, FfiLayerConfig } from './ffi/index.js';
2
+ export { BootstrapConfig as FfiBootstrapConfig, BootstrapResult as FfiBootstrapResult, FfiDispatchMetrics, LogFields as FfiLogFields, FfiStepEvent, StopResult as FfiStopResult, WorkerStatus as FfiWorkerStatus, NapiBackoffHint, NapiCheckpointYieldData, NapiClientResult, NapiDependencyResult, NapiDispatchMetrics, NapiDomainEvent, NapiDomainEventMetadata, NapiListTasksParams, NapiOrchestrationMetadata, NapiStepDefinition, NapiStepEvent, NapiStepExecutionError, NapiStepExecutionMetadata, NapiStepExecutionResult, NapiTaskInfo, NapiTaskRequest, NapiWorkflowStep, StepExecutionResult } from './ffi/index.js';
3
+ import { S as StepHandlerResult, a as StepHandler, B as BatchWorkerConfig, b as StepContext, c as StepHandlerClass, E as ExecutableHandler, T as TaskerEventEmitter, d as EventPoller, e as StepExecutionSubscriber, f as EventSystem } from './index-CRCYa9Xk.js';
4
+ export { y as ErrorCallback, I as ErrorType, n as EventName, o as EventNames, z as EventPollerConfig, F as EventSystemConfig, G as EventSystemStats, A as MetricsCallback, p as MetricsEventName, q as MetricsEventNames, M as MetricsPayload, P as PollerCyclePayload, r as PollerEventName, s as PollerEventNames, C as PollerState, g as StepCompletionSentPayload, L as StepContextParams, D as StepEventCallback, t as StepEventName, u as StepEventNames, h as StepExecutionCompletedPayload, i as StepExecutionFailedPayload, j as StepExecutionReceivedPayload, k as StepExecutionStartedPayload, H as StepExecutionSubscriberConfig, N as StepHandlerResultParams, l as TaskerEventMap, W as WorkerErrorPayload, v as WorkerEventName, w as WorkerEventNames, m as WorkerEventPayload, x as createEventPoller, J as isStandardErrorType, K as isTypicallyRetryable } from './index-CRCYa9Xk.js';
7
5
  import { Logger } from 'pino';
8
6
  import 'eventemitter3';
9
7
 
10
8
  /**
11
9
  * Bootstrap configuration and result types.
12
10
  *
13
- * These types extend the FFI types with TypeScript-friendly interfaces
14
- * for worker lifecycle management.
11
+ * TAS-290: With napi-rs, FFI types are already camelCase, so conversion
12
+ * functions are simplified (mostly pass-through).
15
13
  */
16
14
 
17
15
  /**
@@ -33,8 +31,6 @@ interface BootstrapConfig {
33
31
  }
34
32
  /**
35
33
  * Result from worker bootstrap.
36
- *
37
- * Contains information about the bootstrapped worker instance.
38
34
  */
39
35
  interface BootstrapResult {
40
36
  /** Whether bootstrap was successful. */
@@ -50,8 +46,6 @@ interface BootstrapResult {
50
46
  }
51
47
  /**
52
48
  * Current worker status.
53
- *
54
- * Contains detailed information about the worker's state and resources.
55
49
  */
56
50
  interface WorkerStatus {
57
51
  /** Whether the status query succeeded. */
@@ -99,8 +93,9 @@ interface StopResult {
99
93
  *
100
94
  * Matches Python's bootstrap.py and Ruby's bootstrap.rb (TAS-92 aligned).
101
95
  *
102
- * All functions require an explicit runtime parameter. Use FfiLayer to load
103
- * the runtime before calling these functions.
96
+ * TAS-290: Uses NapiModule directly instead of TaskerRuntime abstraction.
97
+ * All functions require an explicit module parameter. Use FfiLayer to load
98
+ * the module before calling these functions.
104
99
  */
105
100
 
106
101
  /**
@@ -113,7 +108,7 @@ interface StopResult {
113
108
  * - Subscribing to domain events
114
109
  *
115
110
  * @param config - Optional bootstrap configuration
116
- * @param runtime - The loaded FFI runtime (required)
111
+ * @param module - The loaded napi-rs module (required)
117
112
  * @returns BootstrapResult with worker details and status
118
113
  * @throws Error if bootstrap fails critically
119
114
  *
@@ -121,41 +116,41 @@ interface StopResult {
121
116
  * ```typescript
122
117
  * const ffiLayer = new FfiLayer();
123
118
  * await ffiLayer.load();
124
- * const result = await bootstrapWorker({ namespace: 'payments' }, ffiLayer.getRuntime());
119
+ * const result = await bootstrapWorker({ namespace: 'payments' }, ffiLayer.getModule());
125
120
  * console.log(`Worker ${result.workerId} started`);
126
121
  * ```
127
122
  */
128
- declare function bootstrapWorker(config: BootstrapConfig | undefined, runtime: TaskerRuntime): Promise<BootstrapResult>;
123
+ declare function bootstrapWorker(config: BootstrapConfig | undefined, module: NapiModule): Promise<BootstrapResult>;
129
124
  /**
130
125
  * Stop the worker system gracefully.
131
126
  *
132
127
  * This function stops the worker system and releases all resources.
133
128
  * Safe to call even if the worker is not running.
134
129
  *
135
- * @param runtime - The loaded FFI runtime (optional - returns success if not loaded)
130
+ * @param module - The loaded napi-rs module (optional - returns success if not loaded)
136
131
  * @returns StopResult indicating the outcome
137
132
  *
138
133
  * @example
139
134
  * ```typescript
140
- * const result = stopWorker(runtime);
135
+ * const result = stopWorker(module);
141
136
  * if (result.success) {
142
137
  * console.log('Worker stopped successfully');
143
138
  * }
144
139
  * ```
145
140
  */
146
- declare function stopWorker(runtime?: TaskerRuntime): StopResult;
141
+ declare function stopWorker(module?: NapiModule): StopResult;
147
142
  /**
148
143
  * Get the current worker system status.
149
144
  *
150
145
  * Returns detailed information about the worker's current state,
151
146
  * including resource usage and operational status.
152
147
  *
153
- * @param runtime - The loaded FFI runtime (optional - returns stopped if not loaded)
148
+ * @param module - The loaded napi-rs module (optional - returns stopped if not loaded)
154
149
  * @returns WorkerStatus with current state and metrics
155
150
  *
156
151
  * @example
157
152
  * ```typescript
158
- * const status = getWorkerStatus(runtime);
153
+ * const status = getWorkerStatus(module);
159
154
  * if (status.running) {
160
155
  * console.log(`Pool size: ${status.databasePoolSize}`);
161
156
  * } else {
@@ -163,7 +158,7 @@ declare function stopWorker(runtime?: TaskerRuntime): StopResult;
163
158
  * }
164
159
  * ```
165
160
  */
166
- declare function getWorkerStatus(runtime?: TaskerRuntime): WorkerStatus;
161
+ declare function getWorkerStatus(module?: NapiModule): WorkerStatus;
167
162
  /**
168
163
  * Initiate graceful shutdown of the worker system.
169
164
  *
@@ -171,69 +166,66 @@ declare function getWorkerStatus(runtime?: TaskerRuntime): WorkerStatus;
171
166
  * in-flight operations to complete before fully stopping.
172
167
  * Call stopWorker() after this to fully stop the worker.
173
168
  *
174
- * @param runtime - The loaded FFI runtime (optional - returns success if not loaded)
169
+ * @param module - The loaded napi-rs module (optional - returns success if not loaded)
175
170
  * @returns StopResult indicating the transition status
176
171
  *
177
172
  * @example
178
173
  * ```typescript
179
174
  * // Start graceful shutdown
180
- * transitionToGracefulShutdown(runtime);
175
+ * transitionToGracefulShutdown(module);
181
176
  *
182
177
  * // Wait for in-flight operations...
183
178
  * await new Promise(resolve => setTimeout(resolve, 5000));
184
179
  *
185
180
  * // Fully stop
186
- * stopWorker(runtime);
181
+ * stopWorker(module);
187
182
  * ```
188
183
  */
189
- declare function transitionToGracefulShutdown(runtime?: TaskerRuntime): StopResult;
184
+ declare function transitionToGracefulShutdown(module?: NapiModule): StopResult;
190
185
  /**
191
186
  * Check if the worker system is currently running.
192
187
  *
193
188
  * Lightweight check that doesn't query the full status.
194
189
  *
195
- * @param runtime - The loaded FFI runtime (optional - returns false if not loaded)
190
+ * @param module - The loaded napi-rs module (optional - returns false if not loaded)
196
191
  * @returns True if the worker is running
197
192
  *
198
193
  * @example
199
194
  * ```typescript
200
- * if (!isWorkerRunning(runtime)) {
201
- * await bootstrapWorker(config, runtime);
195
+ * if (!isWorkerRunning(module)) {
196
+ * await bootstrapWorker(config, module);
202
197
  * }
203
198
  * ```
204
199
  */
205
- declare function isWorkerRunning(runtime?: TaskerRuntime): boolean;
200
+ declare function isWorkerRunning(module?: NapiModule): boolean;
206
201
  /**
207
202
  * Get version information for the worker system.
208
203
  *
209
- * @param runtime - The loaded FFI runtime (optional)
204
+ * @param module - The loaded napi-rs module (optional)
210
205
  * @returns Version string from the Rust library
211
206
  */
212
- declare function getVersion(runtime?: TaskerRuntime): string;
207
+ declare function getVersion(module?: NapiModule): string;
213
208
  /**
214
209
  * Get detailed Rust library version.
215
210
  *
216
- * @param runtime - The loaded FFI runtime (optional)
211
+ * @param module - The loaded napi-rs module (optional)
217
212
  * @returns Detailed version information
218
213
  */
219
- declare function getRustVersion(runtime?: TaskerRuntime): string;
214
+ declare function getRustVersion(module?: NapiModule): string;
220
215
  /**
221
216
  * Perform a health check on the FFI module.
222
217
  *
223
- * @param runtime - The loaded FFI runtime (optional - returns false if not loaded)
218
+ * @param module - The loaded napi-rs module (optional - returns false if not loaded)
224
219
  * @returns True if the FFI module is functional
225
220
  */
226
- declare function healthCheck(runtime?: TaskerRuntime): boolean;
221
+ declare function healthCheck(module?: NapiModule): boolean;
227
222
 
228
223
  /**
229
224
  * High-level client wrapper for orchestration API operations.
230
225
  *
231
- * The raw FFI exposes `runtime.clientCreateTask(json)` and similar methods
232
- * that require callers to construct complete JSON request strings with all
233
- * required fields and return untyped `ClientResult` envelopes.
234
- *
235
- * This module provides a `TaskerClient` class with typed methods, sensible
236
- * defaults, and proper error handling.
226
+ * TAS-290: With napi-rs, requests are passed as typed objects directly —
227
+ * no JSON.stringify() at the boundary. This eliminates TAS-283 trailing
228
+ * input bugs.
237
229
  *
238
230
  * @example
239
231
  * ```typescript
@@ -244,7 +236,7 @@ declare function healthCheck(runtime?: TaskerRuntime): boolean;
244
236
  * const client = new TaskerClient(ffiLayer);
245
237
  *
246
238
  * const task = client.createTask({ name: 'process_order', namespace: 'ecommerce' });
247
- * console.log(task.task_uuid);
239
+ * console.log(task.taskUuid);
248
240
  * ```
249
241
  *
250
242
  * @packageDocumentation
@@ -273,13 +265,13 @@ interface CreateTaskOptions {
273
265
  /** Optional tags */
274
266
  tags?: string[];
275
267
  /** Optional priority */
276
- priority?: number | null;
268
+ priority?: number;
277
269
  /** Optional correlation ID (auto-generated if not provided) */
278
270
  correlationId?: string;
279
271
  /** Optional parent correlation ID */
280
- parentCorrelationId?: string | null;
272
+ parentCorrelationId?: string;
281
273
  /** Optional idempotency key */
282
- idempotencyKey?: string | null;
274
+ idempotencyKey?: string;
283
275
  }
284
276
  /**
285
277
  * Options for listing tasks.
@@ -315,26 +307,26 @@ declare class TaskerClient {
315
307
  * Create a task via the orchestration API.
316
308
  *
317
309
  * @param options - Task creation options (only `name` is required)
318
- * @returns Typed task response
310
+ * @returns Typed task response data
319
311
  * @throws TaskerClientError if the operation fails
320
312
  */
321
- createTask(options: CreateTaskOptions): ClientTaskResponse;
313
+ createTask(options: CreateTaskOptions): unknown;
322
314
  /**
323
315
  * Get a task by UUID.
324
316
  *
325
317
  * @param taskUuid - The task UUID
326
- * @returns Typed task response
318
+ * @returns Typed task response data
327
319
  * @throws TaskerClientError if the operation fails
328
320
  */
329
- getTask(taskUuid: string): ClientTaskResponse;
321
+ getTask(taskUuid: string): unknown;
330
322
  /**
331
323
  * List tasks with optional filtering and pagination.
332
324
  *
333
325
  * @param options - Filtering and pagination options
334
- * @returns Typed task list response with pagination
326
+ * @returns Typed task list response data
335
327
  * @throws TaskerClientError if the operation fails
336
328
  */
337
- listTasks(options?: ListTasksOptions): ClientTaskListResponse;
329
+ listTasks(options?: ListTasksOptions): unknown;
338
330
  /**
339
331
  * Cancel a task by UUID.
340
332
  *
@@ -346,43 +338,43 @@ declare class TaskerClient {
346
338
  * List workflow steps for a task.
347
339
  *
348
340
  * @param taskUuid - The task UUID
349
- * @returns Array of typed step responses
341
+ * @returns Array of step data
350
342
  * @throws TaskerClientError if the operation fails
351
343
  */
352
- listTaskSteps(taskUuid: string): ClientStepResponse[];
344
+ listTaskSteps(taskUuid: string): unknown;
353
345
  /**
354
346
  * Get a specific workflow step.
355
347
  *
356
348
  * @param taskUuid - The task UUID
357
349
  * @param stepUuid - The step UUID
358
- * @returns Typed step response
350
+ * @returns Typed step response data
359
351
  * @throws TaskerClientError if the operation fails
360
352
  */
361
- getStep(taskUuid: string, stepUuid: string): ClientStepResponse;
353
+ getStep(taskUuid: string, stepUuid: string): unknown;
362
354
  /**
363
355
  * Get audit history for a workflow step.
364
356
  *
365
357
  * @param taskUuid - The task UUID
366
358
  * @param stepUuid - The step UUID
367
- * @returns Array of typed audit history entries
359
+ * @returns Array of audit history entries
368
360
  * @throws TaskerClientError if the operation fails
369
361
  */
370
- getStepAuditHistory(taskUuid: string, stepUuid: string): ClientStepAuditResponse[];
362
+ getStepAuditHistory(taskUuid: string, stepUuid: string): unknown;
371
363
  /**
372
364
  * Check orchestration API health.
373
365
  *
374
- * @returns Typed health response
366
+ * @returns Typed health response data
375
367
  * @throws TaskerClientError if the operation fails
376
368
  */
377
- healthCheck(): ClientHealthResponse;
369
+ healthCheck(): unknown;
378
370
  /**
379
- * Unwrap a ClientResult envelope, throwing on error.
371
+ * Unwrap a NapiClientResult envelope, throwing on error.
380
372
  */
381
373
  private unwrap;
382
374
  /**
383
- * Get the FFI runtime from the layer.
375
+ * Get the napi-rs module from the layer.
384
376
  */
385
- private getRuntime;
377
+ private getModule;
386
378
  }
387
379
 
388
380
  /**
@@ -2635,7 +2627,258 @@ declare function ffiEventToDomainEvent(ffiEvent: FfiDomainEvent): DomainEvent;
2635
2627
  * poller.start();
2636
2628
  * ```
2637
2629
  */
2638
- declare function createFfiPollAdapter(runtime: TaskerRuntime): () => DomainEvent | null;
2630
+ declare function createFfiPollAdapter(module: NapiModule): () => DomainEvent | null;
2631
+
2632
+ /**
2633
+ * Functional/factory API for step handlers (TAS-294).
2634
+ *
2635
+ * This module provides factory-function alternatives to the class-based handler API.
2636
+ * It reduces boilerplate for common handler patterns while preserving full access
2637
+ * to the underlying StepContext for advanced use cases.
2638
+ *
2639
+ * Factory functions auto-wrap return values and classify exceptions:
2640
+ * - Record return → StepHandlerResult.success(record)
2641
+ * - StepHandlerResult return → pass through unchanged
2642
+ * - PermanentError thrown → StepHandlerResult.failure(retryable=false)
2643
+ * - RetryableError thrown → StepHandlerResult.failure(retryable=true)
2644
+ * - Other errors → StepHandlerResult.failure(retryable=true)
2645
+ *
2646
+ * @example
2647
+ * ```typescript
2648
+ * import { defineHandler, PermanentError } from 'tasker-core';
2649
+ *
2650
+ * const ProcessPayment = defineHandler('process_payment', {
2651
+ * depends: { cart: 'validate_cart' },
2652
+ * inputs: { paymentInfo: 'payment_info' },
2653
+ * }, async ({ cart, paymentInfo, context }) => {
2654
+ * if (!paymentInfo) throw new PermanentError('Payment info required');
2655
+ * const result = await chargeCard(paymentInfo, cart.total);
2656
+ * return { paymentId: result.id, amount: cart.total };
2657
+ * });
2658
+ * ```
2659
+ *
2660
+ * @module handler/functional
2661
+ */
2662
+
2663
+ /**
2664
+ * Base error for permanent, non-retryable failures.
2665
+ *
2666
+ * Throw this in functional handlers when the error will not succeed on retry.
2667
+ *
2668
+ * @example
2669
+ * ```typescript
2670
+ * throw new PermanentError('Invalid account number');
2671
+ * ```
2672
+ */
2673
+ declare class PermanentError extends Error {
2674
+ readonly retryable = false;
2675
+ readonly metadata: Record<string, unknown>;
2676
+ constructor(message: string, metadata?: Record<string, unknown>);
2677
+ }
2678
+ /**
2679
+ * Base error for transient, retryable failures.
2680
+ *
2681
+ * Throw this in functional handlers when a retry might succeed.
2682
+ *
2683
+ * @example
2684
+ * ```typescript
2685
+ * throw new RetryableError('Service temporarily unavailable');
2686
+ * ```
2687
+ */
2688
+ declare class RetryableError extends Error {
2689
+ readonly retryable = true;
2690
+ readonly metadata: Record<string, unknown>;
2691
+ constructor(message: string, metadata?: Record<string, unknown>);
2692
+ }
2693
+ /**
2694
+ * Options for defineHandler and related factory functions.
2695
+ */
2696
+ interface HandlerOptions {
2697
+ /** Mapping of parameter names to dependency step names */
2698
+ depends?: Record<string, string>;
2699
+ /** Mapping of parameter names to input data keys */
2700
+ inputs?: Record<string, string>;
2701
+ /** Handler version (default: "1.0.0") */
2702
+ version?: string;
2703
+ }
2704
+ /**
2705
+ * The injected arguments object passed to functional handlers.
2706
+ *
2707
+ * Contains declared dependencies, inputs, and always includes `context`.
2708
+ */
2709
+ type HandlerArgs = Record<string, unknown> & {
2710
+ context: StepContext;
2711
+ };
2712
+ /**
2713
+ * Handler function signature.
2714
+ */
2715
+ type HandlerFn = (args: HandlerArgs) => Promise<Record<string, unknown> | StepHandlerResult | undefined>;
2716
+ /**
2717
+ * Helper for decision handler return values.
2718
+ *
2719
+ * @example
2720
+ * ```typescript
2721
+ * const RouteOrder = defineDecisionHandler('route_order', {
2722
+ * depends: { order: 'validate_order' },
2723
+ * }, async ({ order }) => {
2724
+ * if (order.tier === 'premium') {
2725
+ * return Decision.route(['process_premium'], { tier: 'premium' });
2726
+ * }
2727
+ * return Decision.route(['process_standard']);
2728
+ * });
2729
+ * ```
2730
+ */
2731
+ declare class Decision {
2732
+ readonly type: 'create_steps' | 'no_branches';
2733
+ readonly steps: string[];
2734
+ readonly reason?: string | undefined;
2735
+ readonly routingContext: Record<string, unknown>;
2736
+ private constructor();
2737
+ /**
2738
+ * Route to the specified steps.
2739
+ */
2740
+ static route(steps: string[], routingContext?: Record<string, unknown>): Decision;
2741
+ /**
2742
+ * Skip all branches.
2743
+ */
2744
+ static skip(reason: string, routingContext?: Record<string, unknown>): Decision;
2745
+ }
2746
+ /**
2747
+ * Configuration returned by batch analyzer handlers.
2748
+ */
2749
+ interface BatchConfig {
2750
+ totalItems: number;
2751
+ batchSize: number;
2752
+ metadata?: Record<string, unknown>;
2753
+ }
2754
+ /**
2755
+ * Define a step handler from a function.
2756
+ *
2757
+ * Returns a StepHandler subclass that can be registered with HandlerRegistry.
2758
+ * The function receives injected dependencies, inputs, and context.
2759
+ * Return values are auto-wrapped as success results, and exceptions are
2760
+ * auto-classified as failure results.
2761
+ *
2762
+ * @param name - Handler name (must match step definition)
2763
+ * @param options - Dependencies, inputs, and version
2764
+ * @param fn - Handler function
2765
+ * @returns StepHandler subclass
2766
+ *
2767
+ * @example
2768
+ * ```typescript
2769
+ * const ProcessPayment = defineHandler('process_payment', {
2770
+ * depends: { cart: 'validate_cart' },
2771
+ * inputs: { paymentInfo: 'payment_info' },
2772
+ * }, async ({ cart, paymentInfo, context }) => {
2773
+ * if (!paymentInfo) throw new PermanentError('Payment info required');
2774
+ * const result = await chargeCard(paymentInfo, cart.total);
2775
+ * return { paymentId: result.id, amount: cart.total };
2776
+ * });
2777
+ *
2778
+ * // Register:
2779
+ * registry.register(ProcessPayment);
2780
+ * ```
2781
+ */
2782
+ declare function defineHandler(name: string, options: HandlerOptions, fn: HandlerFn): StepHandlerClass;
2783
+ /**
2784
+ * Define a decision handler from a function.
2785
+ *
2786
+ * The function should return a `Decision.route(...)` or `Decision.skip(...)`.
2787
+ *
2788
+ * @param name - Handler name
2789
+ * @param options - Dependencies, inputs, and version
2790
+ * @param fn - Handler function returning a Decision
2791
+ * @returns StepHandler subclass
2792
+ *
2793
+ * @example
2794
+ * ```typescript
2795
+ * const RouteOrder = defineDecisionHandler('route_order', {
2796
+ * depends: { order: 'validate_order' },
2797
+ * }, async ({ order }) => {
2798
+ * if (order.tier === 'premium') {
2799
+ * return Decision.route(['process_premium'], { tier: 'premium' });
2800
+ * }
2801
+ * return Decision.route(['process_standard']);
2802
+ * });
2803
+ * ```
2804
+ */
2805
+ declare function defineDecisionHandler(name: string, options: HandlerOptions, fn: (args: HandlerArgs) => Promise<Decision | StepHandlerResult>): StepHandlerClass;
2806
+ /**
2807
+ * Define a batch analyzer handler.
2808
+ *
2809
+ * The function should return a `BatchConfig` with `totalItems` and `batchSize`.
2810
+ * Cursor configs are generated automatically.
2811
+ *
2812
+ * @param name - Handler name
2813
+ * @param options - Handler options plus `workerTemplate`
2814
+ * @param fn - Handler function returning a BatchConfig
2815
+ * @returns StepHandler subclass
2816
+ */
2817
+ declare function defineBatchAnalyzer(name: string, options: HandlerOptions & {
2818
+ workerTemplate: string;
2819
+ }, fn: (args: HandlerArgs) => Promise<BatchConfig | StepHandlerResult>): StepHandlerClass;
2820
+ /**
2821
+ * Define a batch worker handler.
2822
+ *
2823
+ * The function receives a `batchContext` parameter extracted from the step
2824
+ * context, containing cursor configuration for this worker's partition.
2825
+ *
2826
+ * @param name - Handler name
2827
+ * @param options - Dependencies, inputs, and version
2828
+ * @param fn - Handler function receiving batch context
2829
+ * @returns StepHandler subclass
2830
+ */
2831
+ declare function defineBatchWorker(name: string, options: HandlerOptions, fn: (args: HandlerArgs & {
2832
+ batchContext: BatchWorkerContext | null;
2833
+ }) => Promise<Record<string, unknown> | StepHandlerResult | undefined>): StepHandlerClass;
2834
+ /**
2835
+ * Options for defineApiHandler.
2836
+ */
2837
+ interface ApiHandlerOptions extends HandlerOptions {
2838
+ /** Base URL for API calls */
2839
+ baseUrl: string;
2840
+ /** Default request timeout in milliseconds (default: 30000) */
2841
+ defaultTimeout?: number;
2842
+ /** Default headers to include in all requests */
2843
+ defaultHeaders?: Record<string, string>;
2844
+ }
2845
+ /**
2846
+ * The injected arguments for API handlers, including the `api` object
2847
+ * with pre-configured HTTP methods and result helpers.
2848
+ *
2849
+ * `api` is the handler instance itself with API methods applied (matching
2850
+ * the Python/Ruby pattern where `api=self`).
2851
+ */
2852
+ type ApiHandlerArgs = HandlerArgs & {
2853
+ api: APICapable;
2854
+ };
2855
+ /**
2856
+ * Define an API handler with HTTP client functionality.
2857
+ *
2858
+ * The function receives an `api` object providing pre-configured HTTP methods
2859
+ * (get, post, put, patch, delete, request) and result helpers (apiSuccess,
2860
+ * apiFailure, connectionError, timeoutError) from the APIMixin.
2861
+ *
2862
+ * @param name - Handler name (must match step definition)
2863
+ * @param options - Dependencies, inputs, version, and API configuration
2864
+ * @param fn - Handler function receiving api and other injected args
2865
+ * @returns StepHandler subclass
2866
+ *
2867
+ * @example
2868
+ * ```typescript
2869
+ * const FetchUser = defineApiHandler('fetch_user', {
2870
+ * baseUrl: 'https://api.example.com',
2871
+ * depends: { userId: 'validate_user' },
2872
+ * }, async ({ userId, api }) => {
2873
+ * const response = await api.get(`/users/${userId}`);
2874
+ * if (response.ok) {
2875
+ * return api.apiSuccess(response);
2876
+ * }
2877
+ * return api.apiFailure(response);
2878
+ * });
2879
+ * ```
2880
+ */
2881
+ declare function defineApiHandler(name: string, options: ApiHandlerOptions, fn: (args: ApiHandlerArgs) => Promise<Record<string, unknown> | StepHandlerResult | undefined>): StepHandlerClass;
2639
2882
 
2640
2883
  /**
2641
2884
  * TAS-93: Handler definition type for resolver chain.
@@ -2661,7 +2904,19 @@ declare function createFfiPollAdapter(runtime: TaskerRuntime): () => DomainEvent
2661
2904
  * }
2662
2905
  * ```
2663
2906
  */
2664
-
2907
+ /**
2908
+ * Handler definition DTO from napi-rs (flattened from step definition).
2909
+ *
2910
+ * TAS-290: With napi-rs, handler fields are flattened into NapiStepDefinition
2911
+ * (handlerCallable, handlerMethod, handlerResolver, handlerInitialization).
2912
+ * This interface provides a compatible shape for fromDto().
2913
+ */
2914
+ interface HandlerDefinitionDto {
2915
+ callable?: string;
2916
+ method?: string | null;
2917
+ resolver?: string | null;
2918
+ initialization?: Record<string, unknown>;
2919
+ }
2665
2920
  /**
2666
2921
  * Handler definition with resolution metadata.
2667
2922
  */
@@ -3687,12 +3942,18 @@ declare class HandlerSystem {
3687
3942
  * Try to import an index file from the handler path.
3688
3943
  */
3689
3944
  private tryImportIndexFile;
3945
+ /**
3946
+ * TAS-294: Try to import the dsl_examples index file.
3947
+ * This is separate from tryImportIndexFile because dsl_examples/ is a sibling
3948
+ * directory to examples/, and both need to be loaded.
3949
+ */
3950
+ private tryImportDslExamplesIndex;
3690
3951
  /**
3691
3952
  * Register handlers from a module's exports.
3692
3953
  */
3693
3954
  private registerHandlersFromModule;
3694
3955
  /**
3695
- * Register handlers from ALL_EXAMPLE_HANDLERS array.
3956
+ * Register handlers from a named handler array.
3696
3957
  */
3697
3958
  private registerFromHandlerArray;
3698
3959
  /**
@@ -3756,98 +4017,26 @@ interface LogFields {
3756
4017
  }
3757
4018
  /**
3758
4019
  * Log an ERROR level message with structured fields.
3759
- *
3760
- * Use this for unrecoverable failures that require intervention.
3761
- *
3762
- * @param message - The log message
3763
- * @param fields - Optional structured fields for context
3764
- *
3765
- * @example
3766
- * logError('Database connection failed', {
3767
- * component: 'database',
3768
- * operation: 'connect',
3769
- * error_message: 'Connection timeout',
3770
- * });
3771
4020
  */
3772
4021
  declare function logError(message: string, fields?: LogFields): void;
3773
4022
  /**
3774
4023
  * Log a WARN level message with structured fields.
3775
- *
3776
- * Use this for degraded operation or retryable failures.
3777
- *
3778
- * @param message - The log message
3779
- * @param fields - Optional structured fields for context
3780
- *
3781
- * @example
3782
- * logWarn('Retry attempt 3 of 5', {
3783
- * component: 'handler',
3784
- * operation: 'retry',
3785
- * attempt: 3,
3786
- * });
3787
4024
  */
3788
4025
  declare function logWarn(message: string, fields?: LogFields): void;
3789
4026
  /**
3790
4027
  * Log an INFO level message with structured fields.
3791
- *
3792
- * Use this for lifecycle events and state transitions.
3793
- *
3794
- * @param message - The log message
3795
- * @param fields - Optional structured fields for context
3796
- *
3797
- * @example
3798
- * logInfo('Task processing started', {
3799
- * component: 'handler',
3800
- * operation: 'process_payment',
3801
- * correlation_id: 'abc-123',
3802
- * task_uuid: 'task-456',
3803
- * });
3804
4028
  */
3805
4029
  declare function logInfo(message: string, fields?: LogFields): void;
3806
4030
  /**
3807
4031
  * Log a DEBUG level message with structured fields.
3808
- *
3809
- * Use this for detailed diagnostic information during development.
3810
- *
3811
- * @param message - The log message
3812
- * @param fields - Optional structured fields for context
3813
- *
3814
- * @example
3815
- * logDebug('Parsed request payload', {
3816
- * component: 'handler',
3817
- * payload_size: 1024,
3818
- * content_type: 'application/json',
3819
- * });
3820
4032
  */
3821
4033
  declare function logDebug(message: string, fields?: LogFields): void;
3822
4034
  /**
3823
4035
  * Log a TRACE level message with structured fields.
3824
- *
3825
- * Use this for very verbose logging, like function entry/exit.
3826
- * This level is typically disabled in production.
3827
- *
3828
- * @param message - The log message
3829
- * @param fields - Optional structured fields for context
3830
- *
3831
- * @example
3832
- * logTrace('Entering process_step', {
3833
- * component: 'handler',
3834
- * step_uuid: 'step-789',
3835
- * });
3836
4036
  */
3837
4037
  declare function logTrace(message: string, fields?: LogFields): void;
3838
4038
  /**
3839
4039
  * Create a logger with preset fields.
3840
- *
3841
- * Useful for creating component-specific loggers that automatically
3842
- * include common fields in every log message.
3843
- *
3844
- * @param defaultFields - Fields to include in every log message
3845
- * @returns Logger object with log methods
3846
- *
3847
- * @example
3848
- * const logger = createLogger({ component: 'payment_handler' });
3849
- * logger.info('Processing payment', { amount: 100 });
3850
- * // Logs: { component: 'payment_handler', amount: 100 }
3851
4040
  */
3852
4041
  declare function createLogger(defaultFields: LogFields): {
3853
4042
  error: (message: string, fields?: LogFields) => void;
@@ -4030,8 +4219,8 @@ interface ServerStatus {
4030
4219
  * Used by WorkerServer to manage lifecycle of all components.
4031
4220
  */
4032
4221
  interface ServerComponents {
4033
- /** FFI runtime instance */
4034
- runtime: TaskerRuntime;
4222
+ /** napi-rs FFI module instance */
4223
+ module: NapiModule;
4035
4224
  /** Event emitter for step events */
4036
4225
  emitter: TaskerEventEmitter;
4037
4226
  /** Handler registry */
@@ -4054,6 +4243,8 @@ interface ServerComponents {
4054
4243
  * - Event processing (via EventSystem)
4055
4244
  * - Graceful shutdown
4056
4245
  *
4246
+ * TAS-290: Uses NapiModule directly instead of TaskerRuntime.
4247
+ *
4057
4248
  * Design principles:
4058
4249
  * - Explicit construction: No singleton pattern - caller creates and manages
4059
4250
  * - Clear ownership: Owns FfiLayer, HandlerSystem, EventSystem
@@ -4170,4 +4361,4 @@ declare class WorkerServer {
4170
4361
  private cleanupOnError;
4171
4362
  }
4172
4363
 
4173
- export { type APICapable, APIMixin, ApiHandler, ApiResponse, BasePublisher, type BaseResolver, BaseSubscriber, type BatchAggregationResult, type BatchAnalyzerOutcome, type BatchMetadata, type BatchProcessingOutcome, type BatchWorkerContext, type BatchWorkerOutcome, type Batchable, BatchableMixin, type BootstrapConfig, type BootstrapResult, ClassLookupResolver, ClientHealthResponse, ClientStepAuditResponse, ClientStepResponse, ClientTaskListResponse, ClientTaskResponse, type CreateBatchesOutcome, type CreateTaskOptions, type CursorConfig, type DecisionCapable, DecisionHandler, DecisionMixin, type DecisionPointOutcome, DecisionType, DefaultPublisher, type DomainEvent, type DomainEventCallback, type DomainEventErrorCallback, type DomainEventMetadata, type DomainEventPollerConfig, DuplicatePublisherError, type EventDeclaration, EventPoller, EventSystem, ExecutableHandler, ExplicitMappingResolver, type FailureStrategy, FfiLayer, FfiLayerConfig, type HandlerEntry, type HandlerFactory, HandlerRegistry, type HandlerSpec, HandlerSystem, InProcessDomainEventPoller, type ListTasksOptions, type LogFields, MethodDispatchError, MethodDispatchWrapper, type NoBatchesOutcome, NoResolverMatchError, type PollerStats, type PublishContext, PublisherNotFoundError, PublisherRegistry, PublisherValidationError, RegistryFrozenError, RegistryResolver, type RegistryResolverStatic, ResolutionError, ResolverChain, type ResolverConfig, ResolverNotFoundError, type RustBatchWorkerInputs, type RustCursorConfig, type ServerComponents, type HealthCheckResult as ServerHealthCheckResult, type ServerState, type ServerStatus, ShutdownController, type ShutdownHandler, StepContext, type StepEventContext, StepExecutionSubscriber, StepHandler, StepHandlerClass, StepHandlerResult, type StepResult, type StopResult, type SubscriberClass, SubscriberRegistry, type SubscriberStats, TaskerClient, TaskerClientError, TaskerEventEmitter, TaskerRuntime, WorkerServer, type WorkerServerConfig, type WorkerStatus, aggregateBatchResults, applyAPI, applyBatchable, applyDecision, bootstrapWorker, createBatchWorkerContext, createBatches, createDomainEvent, createFfiPollAdapter, createLogger, createStepEventContext, effectiveMethod, ffiEventToDomainEvent, fromCallable, fromDto, getRustVersion, getVersion, getWorkerStatus, hasResolverHint, healthCheck, isCreateBatches, isNoBatches, isWorkerRunning, logDebug, logError, logInfo, logTrace, logWarn, noBatches, normalizeToDefinition, stopWorker, transitionToGracefulShutdown, usesMethodDispatch };
4364
+ export { type APICapable, APIMixin, ApiHandler, type ApiHandlerArgs, type ApiHandlerOptions, ApiResponse, BasePublisher, type BaseResolver, BaseSubscriber, type BatchAggregationResult, type BatchAnalyzerOutcome, type BatchConfig, type BatchMetadata, type BatchProcessingOutcome, type BatchWorkerContext, type BatchWorkerOutcome, type Batchable, BatchableMixin, type BootstrapConfig, type BootstrapResult, ClassLookupResolver, type CreateBatchesOutcome, type CreateTaskOptions, type CursorConfig, Decision, type DecisionCapable, DecisionHandler, DecisionMixin, type DecisionPointOutcome, DecisionType, DefaultPublisher, type DomainEvent, type DomainEventCallback, type DomainEventErrorCallback, type DomainEventMetadata, type DomainEventPollerConfig, DuplicatePublisherError, type EventDeclaration, EventPoller, EventSystem, ExecutableHandler, ExplicitMappingResolver, type FailureStrategy, FfiDomainEvent, FfiLayer, FfiLayerConfig, type HandlerArgs, type HandlerDefinition, type HandlerEntry, type HandlerFactory, type HandlerFn, type HandlerOptions, HandlerRegistry, type HandlerSpec, HandlerSystem, InProcessDomainEventPoller, type ListTasksOptions, type LogFields, MethodDispatchError, MethodDispatchWrapper, NapiModule, type NoBatchesOutcome, NoResolverMatchError, PermanentError, type PollerStats, type PublishContext, PublisherNotFoundError, PublisherRegistry, PublisherValidationError, RegistryFrozenError, RegistryResolver, type RegistryResolverStatic, ResolutionError, ResolverChain, type ResolverConfig, ResolverNotFoundError, RetryableError, type RustBatchWorkerInputs, type RustCursorConfig, type ServerComponents, type HealthCheckResult as ServerHealthCheckResult, type ServerState, type ServerStatus, ShutdownController, type ShutdownHandler, StepContext, type StepEventContext, StepExecutionSubscriber, StepHandler, StepHandlerClass, StepHandlerResult, type StepResult, type StopResult, type SubscriberClass, SubscriberRegistry, type SubscriberStats, TaskerClient, TaskerClientError, TaskerEventEmitter, WorkerServer, type WorkerServerConfig, type WorkerStatus, aggregateBatchResults, applyAPI, applyBatchable, applyDecision, bootstrapWorker, createBatchWorkerContext, createBatches, createDomainEvent, createFfiPollAdapter, createLogger, createStepEventContext, defineApiHandler, defineBatchAnalyzer, defineBatchWorker, defineDecisionHandler, defineHandler, effectiveMethod, ffiEventToDomainEvent, fromCallable, fromDto, getRustVersion, getVersion, getWorkerStatus, hasResolverHint, healthCheck, isCreateBatches, isNoBatches, isWorkerRunning, logDebug, logError, logInfo, logTrace, logWarn, noBatches, normalizeToDefinition, stopWorker, transitionToGracefulShutdown, usesMethodDispatch };