@aniket-lodh/veyra-sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +209 -120
  2. package/dist/cjs/client.d.ts +204 -0
  3. package/dist/cjs/client.js +647 -0
  4. package/dist/cjs/errors.d.ts +147 -0
  5. package/dist/cjs/errors.js +262 -0
  6. package/dist/cjs/handlers.d.ts +165 -0
  7. package/dist/cjs/handlers.js +46 -0
  8. package/dist/cjs/index.d.ts +15 -0
  9. package/dist/cjs/index.js +37 -0
  10. package/dist/cjs/package.json +3 -0
  11. package/dist/cjs/standard-schema.d.ts +86 -0
  12. package/dist/cjs/standard-schema.js +49 -0
  13. package/dist/cjs/types.d.ts +430 -0
  14. package/dist/cjs/types.js +6 -0
  15. package/dist/cjs/webhook.d.ts +98 -0
  16. package/dist/cjs/webhook.js +165 -0
  17. package/dist/cjs/worker.d.ts +101 -0
  18. package/dist/cjs/worker.js +497 -0
  19. package/dist/client.d.ts +159 -25
  20. package/dist/client.js +501 -122
  21. package/dist/errors.d.ts +123 -10
  22. package/dist/errors.js +192 -19
  23. package/dist/handlers.d.ts +165 -0
  24. package/dist/handlers.js +42 -0
  25. package/dist/index.d.ts +13 -6
  26. package/dist/index.js +12 -6
  27. package/dist/standard-schema.d.ts +86 -0
  28. package/dist/standard-schema.js +45 -0
  29. package/dist/types.d.ts +281 -36
  30. package/dist/types.js +2 -2
  31. package/dist/webhook.d.ts +98 -0
  32. package/dist/webhook.js +128 -0
  33. package/dist/worker.d.ts +80 -55
  34. package/dist/worker.js +308 -195
  35. package/package.json +27 -13
  36. package/dist/client.d.ts.map +0 -1
  37. package/dist/client.js.map +0 -1
  38. package/dist/errors.d.ts.map +0 -1
  39. package/dist/errors.js.map +0 -1
  40. package/dist/index.d.ts.map +0 -1
  41. package/dist/index.js.map +0 -1
  42. package/dist/types.d.ts.map +0 -1
  43. package/dist/types.js.map +0 -1
  44. package/dist/worker.d.ts.map +0 -1
  45. package/dist/worker.js.map +0 -1
  46. package/src/client.ts +0 -389
  47. package/src/errors.ts +0 -82
  48. package/src/index.ts +0 -8
  49. package/src/types.ts +0 -217
  50. package/src/worker.ts +0 -472
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Minimal, dependency-free subset of the [Standard Schema v1](https://standardschema.dev)
3
+ * interfaces plus a compile-time-only schema helper.
4
+ */
5
+ /**
6
+ * A Standard Schema v1 compatible schema (Zod, Valibot, ArkType, ...).
7
+ *
8
+ * @typeParam Input - Value accepted by the schema.
9
+ * @typeParam Output - Value produced after validation.
10
+ */
11
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
12
+ readonly '~standard': StandardSchemaV1.Props<Input, Output>;
13
+ }
14
+ export declare namespace StandardSchemaV1 {
15
+ /** Schema metadata and validation entry point. */
16
+ interface Props<Input = unknown, Output = Input> {
17
+ readonly version: 1;
18
+ readonly vendor: string;
19
+ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
20
+ readonly types?: Types<Input, Output> | undefined;
21
+ }
22
+ /** Validation result: exactly one of `value` or `issues` is populated. */
23
+ interface Result<Output> {
24
+ readonly value?: Output | undefined;
25
+ readonly issues?: ReadonlyArray<Issue> | undefined;
26
+ }
27
+ /** A single validation failure. */
28
+ interface Issue {
29
+ readonly message: string;
30
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
31
+ }
32
+ /** Object key in an issue path. */
33
+ interface PathSegment {
34
+ readonly key: PropertyKey;
35
+ }
36
+ /** Compile-time input/output pair exposed by a schema. */
37
+ interface Types<Input = unknown, Output = Input> {
38
+ readonly input: Input;
39
+ readonly output: Output;
40
+ }
41
+ /** Extracts the schema input type. */
42
+ type InferInput<Schema extends StandardSchemaV1> = Schema['~standard']['types'] extends Types<infer Input, any> ? Input : unknown;
43
+ /** Extracts the schema output type. */
44
+ type InferOutput<Schema extends StandardSchemaV1> = Schema['~standard']['types'] extends Types<any, infer Output> ? Output : unknown;
45
+ }
46
+ /**
47
+ * A zero-runtime schema used purely to carry `TPayload`/`TResult` types.
48
+ * Created with {@link staticSchema}; no validation runs.
49
+ */
50
+ export interface StaticSchema<T> {
51
+ readonly '~standard': {
52
+ readonly version: 1;
53
+ readonly vendor: 'veyra';
54
+ readonly types: StandardSchemaV1.Types<T, T>;
55
+ };
56
+ }
57
+ /** A runtime Standard Schema or a compile-time-only {@link StaticSchema}. */
58
+ export type SchemaLike<T> = StandardSchemaV1<unknown, T> | StaticSchema<T>;
59
+ /** Extracts the output type of a {@link SchemaLike}. */
60
+ export type InferSchemaOutput<S> = S extends StandardSchemaV1<any, infer Output> ? Output : S extends StaticSchema<infer T> ? T : unknown;
61
+ /**
62
+ * Declares payload/result types without runtime validation or dependencies.
63
+ *
64
+ * The returned value is `undefined` at runtime; only the type is meaningful.
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * const sendEmail = defineHandler({
69
+ * name: 'send_email',
70
+ * payload: staticSchema<{ to: string }>(),
71
+ * result: staticSchema<{ messageId: string }>(),
72
+ * });
73
+ * ```
74
+ */
75
+ export declare function staticSchema<T>(): StaticSchema<T>;
76
+ /**
77
+ * Validates `value` with a runtime Standard Schema, or returns it unchanged for
78
+ * {@link StaticSchema} values.
79
+ *
80
+ * @param schema - Schema to validate with, or `undefined` to skip validation.
81
+ * @param value - Candidate value.
82
+ * @param label - Human-readable context included in the thrown error.
83
+ * @returns The schema output, or `value` when no runtime schema is present.
84
+ * @throws {VeyraValidationError} When validation produces issues.
85
+ */
86
+ export declare function validateWithSchema<T>(schema: SchemaLike<T> | undefined, value: unknown, label: string): Promise<T>;
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ /**
3
+ * Minimal, dependency-free subset of the [Standard Schema v1](https://standardschema.dev)
4
+ * interfaces plus a compile-time-only schema helper.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.staticSchema = staticSchema;
8
+ exports.validateWithSchema = validateWithSchema;
9
+ const errors_js_1 = require("./errors.js");
10
+ /**
11
+ * Declares payload/result types without runtime validation or dependencies.
12
+ *
13
+ * The returned value is `undefined` at runtime; only the type is meaningful.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * const sendEmail = defineHandler({
18
+ * name: 'send_email',
19
+ * payload: staticSchema<{ to: string }>(),
20
+ * result: staticSchema<{ messageId: string }>(),
21
+ * });
22
+ * ```
23
+ */
24
+ function staticSchema() {
25
+ return undefined;
26
+ }
27
+ function isRuntimeSchema(schema) {
28
+ return typeof schema['~standard']?.validate === 'function';
29
+ }
30
+ /**
31
+ * Validates `value` with a runtime Standard Schema, or returns it unchanged for
32
+ * {@link StaticSchema} values.
33
+ *
34
+ * @param schema - Schema to validate with, or `undefined` to skip validation.
35
+ * @param value - Candidate value.
36
+ * @param label - Human-readable context included in the thrown error.
37
+ * @returns The schema output, or `value` when no runtime schema is present.
38
+ * @throws {VeyraValidationError} When validation produces issues.
39
+ */
40
+ async function validateWithSchema(schema, value, label) {
41
+ if (!schema || !isRuntimeSchema(schema)) {
42
+ return value;
43
+ }
44
+ const result = await schema['~standard'].validate(value);
45
+ if (result.issues && result.issues.length > 0) {
46
+ throw new errors_js_1.VeyraValidationError(label, result.issues);
47
+ }
48
+ return result.value;
49
+ }
@@ -0,0 +1,430 @@
1
+ /**
2
+ * Wire types for the Veyra REST API and HTTP worker protocol.
3
+ * Every shape here mirrors `apps/api` and `apps/worker` exactly.
4
+ */
5
+ import type { DefinitionPayload, HandlerDefinition, HandlerName, HandlerPayload, HandlerResult } from './handlers.js';
6
+ /** JSON value accepted anywhere the API stores opaque JSON. */
7
+ export type JsonValue = string | number | boolean | null | JsonValue[] | {
8
+ [key: string]: JsonValue;
9
+ };
10
+ /**
11
+ * The seven-value status vocabulary returned by `GET /jobs` and `GET /jobs/:id`.
12
+ * `scheduled` is derived from `queued` plus a future `scheduledFor`;
13
+ * `dead-lettered` is the storage value `dead_lettered` renamed for display.
14
+ */
15
+ export type JobStatus = 'queued' | 'scheduled' | 'running' | 'succeeded' | 'failed' | 'dead-lettered' | 'cancelled';
16
+ /**
17
+ * The six-value status vocabulary used by queue storage and by worker
18
+ * protocol responses (`claim`, `complete`, `fail`, webhooks).
19
+ */
20
+ export type StorageJobStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'dead_lettered' | 'cancelled';
21
+ /** Retry strategy attached to a job. */
22
+ export type BackoffStrategy = {
23
+ /** Exponential backoff. */
24
+ kind: 'exponential';
25
+ /** Initial delay in seconds. */
26
+ baseSeconds: number;
27
+ /** Maximum delay in seconds. */
28
+ capSeconds: number;
29
+ } | {
30
+ /** Constant delay between attempts. */
31
+ kind: 'fixed';
32
+ /** Delay in seconds. */
33
+ seconds: number;
34
+ };
35
+ /** Structured error persisted on a failed job. */
36
+ export interface JobError {
37
+ /** Failure class, e.g. `timeout`, `http_5xx`, `HandlerError`. */
38
+ class: string;
39
+ /** Human-readable failure message. */
40
+ message: string;
41
+ /** Stack trace captured by the worker, or an empty string. */
42
+ stackTrace: string;
43
+ /** RFC 3339 timestamp of the failure. */
44
+ occurredAt: string;
45
+ }
46
+ /** One execution attempt in a job's history. */
47
+ export interface JobAttempt {
48
+ /** 1-based attempt number. */
49
+ attemptNumber: number;
50
+ /** Worker that executed the attempt. */
51
+ workerId: string;
52
+ /** RFC 3339 start timestamp. */
53
+ startedAt: string;
54
+ /** RFC 3339 end timestamp, or `null` while running. */
55
+ endedAt: string | null;
56
+ /** Duration in milliseconds, or `null` while running. */
57
+ durationMs: number | null;
58
+ /** `succeeded`, `failed`, `timeout`, `cancelled`, `lease-lost`, or `null`. */
59
+ outcome: string | null;
60
+ /** Failure class, or `null`. */
61
+ errorClass: string | null;
62
+ /** Failure message, or `null`. */
63
+ errorMessage: string | null;
64
+ }
65
+ /** Delivery state of a completion webhook. */
66
+ export type CallbackStatus = 'pending' | 'running' | 'delivered' | 'failed';
67
+ /**
68
+ * Full job representation returned by `POST /jobs`, `GET /jobs/:id`,
69
+ * `POST /jobs/:id/cancel`, and `POST /jobs/:id/retry`.
70
+ *
71
+ * @typeParam TPayload - Shape of `payload`.
72
+ * @typeParam TResult - Shape of `result` once the job succeeds.
73
+ */
74
+ export interface Job<TPayload = unknown, TResult = unknown> {
75
+ /** ULID, 26 characters. */
76
+ id: string;
77
+ /** Handler name matched by workers. */
78
+ handler: string;
79
+ /** Queue the job belongs to. */
80
+ queue: string;
81
+ /** API status vocabulary. */
82
+ status: JobStatus;
83
+ /** `0` (lowest) to `9` (highest). */
84
+ priority: number;
85
+ /** Idempotency key supplied at enqueue, or `null`. */
86
+ idempotencyKey: string | null;
87
+ /** Opaque payload supplied at enqueue. */
88
+ payload: TPayload;
89
+ /** Handler result after success, or `null`. */
90
+ result: TResult | null;
91
+ /** Last failure, or `null`. */
92
+ error: JobError | null;
93
+ /** Attempts made so far. */
94
+ attempt: number;
95
+ /** Per-job retry ceiling. */
96
+ maxAttempts: number;
97
+ /** Retry strategy. */
98
+ backoff: BackoffStrategy;
99
+ /** RFC 3339 enqueue timestamp. */
100
+ enqueuedAt: string;
101
+ /** Earliest runnable time, or `null`. */
102
+ scheduledFor: string | null;
103
+ /** RFC 3339 timestamp of the current/last attempt start, or `null`. */
104
+ startedAt: string | null;
105
+ /** RFC 3339 success timestamp, or `null`. */
106
+ completedAt: string | null;
107
+ /** RFC 3339 cancellation timestamp, or `null`. */
108
+ cancelledAt: string | null;
109
+ /** RFC 3339 dead-letter timestamp, or `null`. */
110
+ deadLetteredAt: string | null;
111
+ /** Worker currently holding the lease, or `null`. */
112
+ currentWorkerId: string | null;
113
+ /** RFC 3339 lease expiry, or `null`. */
114
+ leaseExpiresAt: string | null;
115
+ /** RFC 3339 next retry time, or `null`. */
116
+ nextRetryAt: string | null;
117
+ /** Completion webhook URL; omitted when not configured. */
118
+ callbackUrl?: string;
119
+ /** Webhook delivery state; omitted when not configured. */
120
+ callbackStatus?: CallbackStatus;
121
+ /** Number of webhook delivery attempts. */
122
+ callbackAttempts: number;
123
+ /** Last webhook delivery error; omitted when unset. */
124
+ callbackLastError?: string;
125
+ /** RFC 3339 webhook delivery timestamp; omitted when undelivered. */
126
+ callbackDeliveredAt?: string;
127
+ /** Per-attempt history, oldest first. */
128
+ attempts: JobAttempt[];
129
+ /** `true` when the job was returned from an idempotent replay. */
130
+ isReplay: boolean;
131
+ }
132
+ /** Optional knobs shared by every enqueue call. */
133
+ export interface EnqueueOptions {
134
+ /** Queue name. Defaults to the handler definition's queue or the client's `defaultQueue`. */
135
+ queue?: string;
136
+ /** `0` (lowest) to `9` (highest). Defaults to `5`. */
137
+ priority?: number;
138
+ /** Per-job retry ceiling. Defaults to `3`. */
139
+ maxAttempts?: number;
140
+ /** Retry strategy. Defaults to exponential (30s base, 1h cap). */
141
+ backoff?: BackoffStrategy;
142
+ /** Earliest runnable time as an ISO string or `Date`. */
143
+ scheduledFor?: string | Date;
144
+ /** Dedupe key scoped to the queue. Replays return the existing job. */
145
+ idempotencyKey?: string;
146
+ /** Completion webhook URL (absolute `http`/`https`, max 2048 chars). */
147
+ callbackUrl?: string;
148
+ /** Optional cancellation signal to abort the in-flight enqueue request. */
149
+ signal?: AbortSignal;
150
+ /** Override retry attempts for this request. Only retried if `idempotencyKey` is set. */
151
+ retries?: number;
152
+ }
153
+ /** Optional parameters accepted by retrieval, cancel, and retry requests. */
154
+ export interface RequestOptions {
155
+ /** Optional cancellation signal to abort the in-flight HTTP request. */
156
+ signal?: AbortSignal;
157
+ /** Override retry attempts for this request. */
158
+ retries?: number;
159
+ }
160
+ /**
161
+ * Body accepted by `POST /jobs`.
162
+ *
163
+ * @typeParam TPayload - Shape of `payload`.
164
+ */
165
+ export interface EnqueueJobInput<TPayload = unknown> extends EnqueueOptions {
166
+ /** Handler name matched by workers. */
167
+ handler: string;
168
+ /** Opaque JSON payload passed to the handler. */
169
+ payload: TPayload;
170
+ }
171
+ /**
172
+ * Object form of an enqueue call using a {@link HandlerDefinition}.
173
+ *
174
+ * @typeParam TDefinition - Definition created with `defineHandler`.
175
+ */
176
+ export interface DefinitionEnqueueInput<TDefinition extends HandlerDefinition<any, any, any, any> = HandlerDefinition<any, any, any, any>> extends EnqueueOptions {
177
+ /** Reusable handler definition. */
178
+ handler: TDefinition;
179
+ /** Payload satisfying the definition. */
180
+ payload: DefinitionPayload<TDefinition>;
181
+ }
182
+ /**
183
+ * Object form of a typed enqueue call. Known handler names constrain
184
+ * `payload`; unknown names fall back to `TFallbackPayload`.
185
+ */
186
+ export type TypedEnqueueInput<THandlers extends object, TName extends string, TFallbackPayload> = EnqueueOptions & {
187
+ handler: TName;
188
+ payload: TName extends HandlerName<THandlers> ? HandlerPayload<THandlers, TName> : TFallbackPayload;
189
+ };
190
+ /** Payload type of a typed enqueue, with a fallback for unknown handlers. */
191
+ export type TypedEnqueuePayload<THandlers extends object, TName extends string, TFallbackPayload> = TName extends HandlerName<THandlers> ? HandlerPayload<THandlers, TName> : TFallbackPayload;
192
+ /** Result type of a typed enqueue, with a fallback for unknown handlers. */
193
+ export type TypedEnqueueResult<THandlers extends object, TName extends string, TFallbackResult> = TName extends HandlerName<THandlers> ? HandlerResult<THandlers, TName> : TFallbackResult;
194
+ /** Job returned by `POST /workers/:id/claim`. */
195
+ export interface JobClaim<TPayload = unknown> {
196
+ /** Job ULID. */
197
+ id: string;
198
+ /** Queue the job belongs to. */
199
+ queue: string;
200
+ /** Handler name to execute. */
201
+ handler: string;
202
+ /** Storage status, normally `running`. */
203
+ status: StorageJobStatus;
204
+ /** 1-based attempt number. */
205
+ attempt: number;
206
+ /** Per-job retry ceiling. */
207
+ maxAttempts: number;
208
+ /** `0` to `9`. */
209
+ priority: number;
210
+ /** Job payload. */
211
+ payload: TPayload;
212
+ /** RFC 3339 lease expiry, or `null`. */
213
+ leaseExpiresAt: string | null;
214
+ /** RFC 3339 attempt start, or `null`. */
215
+ startedAt: string | null;
216
+ /** RFC 3339 enqueue timestamp. */
217
+ enqueuedAt: string;
218
+ }
219
+ /** An in-flight lease shown on a worker record. */
220
+ export interface WorkerLease {
221
+ /** Job ULID. */
222
+ jobId: string;
223
+ /** Handler name. */
224
+ handler: string;
225
+ /** Queue name. */
226
+ queue: string;
227
+ /** Attempt number. */
228
+ attempt: number;
229
+ /** RFC 3339 lease start, or an empty string. */
230
+ leasedAt: string;
231
+ /** RFC 3339 lease expiry, or an empty string. */
232
+ leaseExpiresAt: string;
233
+ }
234
+ /** Worker lifecycle state stored in Postgres. */
235
+ export type WorkerState = 'active' | 'idle' | 'cordoned' | 'draining' | 'disconnected';
236
+ /** Worker representation returned by the `/workers` endpoints. */
237
+ export interface WorkerRecord {
238
+ /** Ephemeral runtime id. */
239
+ id: string;
240
+ /** Hostname reported at registration. */
241
+ hostname: string;
242
+ /** OS process id. */
243
+ pid: number;
244
+ /** Worker version string. */
245
+ version: string;
246
+ /** Current lifecycle state. */
247
+ state: WorkerState;
248
+ /** RFC 3339 registration timestamp. */
249
+ startedAt: string;
250
+ /** RFC 3339 last heartbeat timestamp. */
251
+ lastHeartbeatAt: string;
252
+ /** Heartbeat cadence in seconds. */
253
+ heartbeatIntervalSeconds: number;
254
+ /** Queues this worker polls. */
255
+ queues: string[];
256
+ /** Handlers this worker advertises. */
257
+ handlers: string[];
258
+ /** Advertised concurrency limit. */
259
+ maxConcurrency: number;
260
+ /** Number of leases currently held. */
261
+ inFlight: number;
262
+ /** Lifetime completed attempts reported by this worker. */
263
+ totalProcessed: number;
264
+ /** Active leases. */
265
+ leases: WorkerLease[];
266
+ }
267
+ /** Body accepted by `POST /workers/register`. */
268
+ export interface WorkerRegisterParams {
269
+ /** Worker id. The API generates a ULID when omitted. */
270
+ id?: string;
271
+ /** Hostname. The API stores `external` when omitted. */
272
+ hostname?: string;
273
+ /** OS process id. */
274
+ pid?: number;
275
+ /** Worker version. The API stores `1.0.0` when omitted. */
276
+ version?: string;
277
+ /** Non-empty list of queues to poll. */
278
+ queues: string[];
279
+ /** Non-empty list of handler names this worker can run. */
280
+ handlers: string[];
281
+ /** Maximum concurrent jobs. Must be at least `1`. */
282
+ maxConcurrency: number;
283
+ /** Heartbeat cadence in seconds. Defaults to `10`. */
284
+ heartbeatIntervalSeconds?: number;
285
+ }
286
+ /** Response from `POST /workers/:id/heartbeat`. */
287
+ export interface HeartbeatResponse {
288
+ /** Worker id. */
289
+ id: string;
290
+ /** Current lifecycle state. */
291
+ state: WorkerState;
292
+ /** RFC 3339 heartbeat timestamp. */
293
+ lastHeartbeatAt: string;
294
+ }
295
+ /** Body accepted by `POST /workers/:id/claim`. */
296
+ export interface ClaimParams {
297
+ /** Queues to poll. Defaults to the worker's registered queues. */
298
+ queues?: string[];
299
+ /** Handlers to accept. Defaults to the worker's registered handlers. */
300
+ handlers?: string[];
301
+ }
302
+ /** Body accepted by `POST /workers/:id/jobs/:jobId/fail`. */
303
+ export interface FailJobParams {
304
+ /** Failure class. Defaults to `HandlerError`. */
305
+ errorClass?: string;
306
+ /** Failure message. Required by the API. */
307
+ message: string;
308
+ /** Stack trace captured by the handler. */
309
+ stackTrace?: string;
310
+ /** Skip remaining retries and dead-letter immediately. */
311
+ permanent?: boolean;
312
+ }
313
+ /** Response from `POST /workers/:id/jobs/:jobId/complete`. */
314
+ export interface CompleteJobResponse {
315
+ /** Always `true` on success. */
316
+ completed: boolean;
317
+ /** Job ULID. */
318
+ jobId: string;
319
+ /** Worker id. */
320
+ workerId: string;
321
+ /** Storage status after completion. */
322
+ status: StorageJobStatus;
323
+ }
324
+ /** Response from `POST /workers/:id/jobs/:jobId/fail`. */
325
+ export interface FailJobResponse {
326
+ /** Always `true` on success. */
327
+ failed: boolean;
328
+ /** Job ULID. */
329
+ jobId: string;
330
+ /** Worker id. */
331
+ workerId: string;
332
+ /** Storage status after the failure. */
333
+ status: StorageJobStatus;
334
+ /** Whether the failure was permanent. */
335
+ permanent: boolean;
336
+ /** `true` when the job was dead-lettered. */
337
+ terminal: boolean;
338
+ }
339
+ /** Response from `POST /workers/:id/jobs/:jobId/heartbeat`. */
340
+ export interface RenewLeaseResponse {
341
+ /** Always `true` on success. */
342
+ renewed: boolean;
343
+ /** Job ULID. */
344
+ jobId: string;
345
+ /** Worker id. */
346
+ workerId: string;
347
+ /** RFC 3339 new lease expiry. */
348
+ leaseExpiresAt: string;
349
+ }
350
+ /** Response from `POST /workers/:id/deregister` and `DELETE /workers/:id`. */
351
+ export interface DeregisterWorkerResponse {
352
+ /** Always `true` on success. */
353
+ deregistered: boolean;
354
+ /** Worker id. */
355
+ workerId: string;
356
+ }
357
+ /** Execution context passed to every registered handler. */
358
+ export interface JobContext {
359
+ /** Job ULID. */
360
+ readonly jobId: string;
361
+ /** 1-based attempt number. */
362
+ readonly attempt: number;
363
+ /** Queue name. */
364
+ readonly queue: string;
365
+ /** Handler name. */
366
+ readonly handler: string;
367
+ /** Aborted when the lease is lost, the worker drains, or the job is cancelled. */
368
+ readonly signal: AbortSignal;
369
+ /** Renews the job lease immediately. */
370
+ extendLease(): Promise<RenewLeaseResponse>;
371
+ }
372
+ /** A job handler callback. */
373
+ export type HandlerFn<TPayload = unknown, TResult = unknown> = (job: JobClaim<TPayload>, ctx: JobContext) => Promise<TResult> | TResult;
374
+ /** Structured logger interface. Compatible with `console`, `pino`, `winston`, etc. */
375
+ export interface VeyraLogger {
376
+ debug?(message: string, meta?: Record<string, unknown>): void;
377
+ info?(message: string, meta?: Record<string, unknown>): void;
378
+ warn?(message: string, meta?: Record<string, unknown>): void;
379
+ error?(message: string, meta?: Record<string, unknown>): void;
380
+ }
381
+ /** Configuration for {@link VeyraClient}. */
382
+ export interface VeyraClientConfig {
383
+ /** API origin, e.g. `https://veyra.example.com`. Must be a valid http: or https: URL. */
384
+ baseUrl: string;
385
+ /** Bearer API key with the scopes the calls require. Must not contain whitespace or control characters. */
386
+ apiKey: string;
387
+ /** Queue used when `enqueue` omits `queue`. Defaults to `default`. */
388
+ defaultQueue?: string;
389
+ /** Custom `fetch` implementation (tests, proxies, instrumented clients). */
390
+ fetch?: typeof fetch;
391
+ /** Per-request timeout in milliseconds. Defaults to `30000`. */
392
+ timeoutMs?: number;
393
+ /** Maximum automatic retry attempts for idempotent requests (GET, heartbeats, POST with idempotencyKey). Defaults to `2`. */
394
+ maxRetries?: number;
395
+ /** Optional structured logger for transport debugging. */
396
+ logger?: VeyraLogger;
397
+ }
398
+ /** Options for {@link VeyraWorker}. */
399
+ export interface VeyraWorkerOptions {
400
+ /** Queues to poll. At least one is required. */
401
+ queues: string[];
402
+ /** Handler names to advertise. Defaults to every registered handler. */
403
+ handlers?: string[];
404
+ /** Maximum concurrent jobs. Defaults to `5`. */
405
+ concurrency?: number;
406
+ /** Delay between empty polls in milliseconds. Defaults to `1000`. */
407
+ pollIntervalMs?: number;
408
+ /** Worker heartbeat cadence in milliseconds. Defaults to `10000`. */
409
+ heartbeatIntervalMs?: number;
410
+ /** In-flight lease renewal cadence in milliseconds. Defaults to `10000`. */
411
+ leaseHeartbeatIntervalMs?: number;
412
+ /** Hostname reported at registration. */
413
+ hostname?: string;
414
+ /** OS process id reported at registration. */
415
+ pid?: number;
416
+ /** Version reported at registration. Defaults to `0.1.0`. */
417
+ version?: string;
418
+ /** Explicit worker id. Defaults to a random `worker-*` id. */
419
+ workerId?: string;
420
+ /** Optional structured logger for worker event debugging. */
421
+ logger?: VeyraLogger;
422
+ /** Called when a job is claimed, before execution. */
423
+ onJobStart?: (job: JobClaim) => void;
424
+ /** Called after the API acknowledges completion. */
425
+ onJobComplete?: (job: JobClaim, result: unknown) => void;
426
+ /** Called after a handler throws or result validation fails. */
427
+ onJobError?: (job: JobClaim, error: unknown) => void;
428
+ /** Called for background errors (heartbeats, re-registration, reporting). */
429
+ onError?: (error: unknown) => void;
430
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /**
3
+ * Wire types for the Veyra REST API and HTTP worker protocol.
4
+ * Every shape here mirrors `apps/api` and `apps/worker` exactly.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Typed completion webhooks: signature verification and payload parsing.
3
+ */
4
+ import type { HandlerDefinition } from './handlers.js';
5
+ import type { JobError } from './types.js';
6
+ /** Terminal statuses that trigger a webhook delivery. */
7
+ export type WebhookJobStatus = 'succeeded' | 'dead_lettered' | 'cancelled';
8
+ /**
9
+ * Body delivered to `callbackUrl` when a job reaches a terminal state.
10
+ *
11
+ * @typeParam TResult - Shape of `result`.
12
+ */
13
+ export interface WebhookEvent<TResult = unknown> {
14
+ /** Always `job.completed`. */
15
+ event: 'job.completed';
16
+ /** Job ULID. */
17
+ jobId: string;
18
+ /** Queue name. */
19
+ queue: string;
20
+ /** Handler name. */
21
+ handler: string;
22
+ /** Terminal storage status. */
23
+ status: WebhookJobStatus;
24
+ /** Attempts made. */
25
+ attempt: number;
26
+ /** Per-job retry ceiling. */
27
+ maxAttempts: number;
28
+ /** Payload supplied at enqueue. */
29
+ payload: unknown;
30
+ /** Handler result, or `null` for failures and cancellations. */
31
+ result: TResult | null;
32
+ /** Structured failure, or `null`. */
33
+ error: JobError | null;
34
+ /** RFC 3339 enqueue timestamp. */
35
+ enqueuedAt: string;
36
+ /** RFC 3339 attempt start, or `null`. */
37
+ startedAt: string | null;
38
+ /** RFC 3339 success timestamp, or `null`. */
39
+ completedAt: string | null;
40
+ /** RFC 3339 cancellation timestamp, or `null`. */
41
+ cancelledAt: string | null;
42
+ /** RFC 3339 dead-letter timestamp, or `null`. */
43
+ deadLetteredAt: string | null;
44
+ /** 1-based webhook delivery attempt. */
45
+ callbackAttempts: number;
46
+ }
47
+ /** Signature options for {@link parseWebhook}. */
48
+ export interface WebhookVerificationOptions {
49
+ /** Shared secret configured as `VEYRA_CALLBACK_SECRET` on the API. */
50
+ secret?: string;
51
+ /** Raw `X-Veyra-Signature` header value, e.g. `sha256=ab12...`. */
52
+ signature?: string | null;
53
+ }
54
+ /**
55
+ * Verifies the `X-Veyra-Signature` header: `sha256=<hex HMAC-SHA256(rawBody)>`.
56
+ * Comparison is strictly constant-time and lengths are guarded to prevent `RangeError`.
57
+ *
58
+ * @param rawBody - Exact request body bytes (do not re-serialize JSON).
59
+ * @param signature - `X-Veyra-Signature` header value.
60
+ * @param secret - Shared secret configured as `VEYRA_CALLBACK_SECRET` on the API.
61
+ * @returns `true` when the signature matches.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * const ok = await verifyWebhookSignature(rawBody, req.headers['x-veyra-signature'], secret);
66
+ * ```
67
+ */
68
+ export declare function verifyWebhookSignature(rawBody: string | ArrayBuffer | ArrayBufferView, signature: string | null | undefined, secret: string): Promise<boolean>;
69
+ /**
70
+ * Verifies (when a secret is supplied), parses, and optionally validates a
71
+ * completion webhook.
72
+ *
73
+ * @param rawBody - Exact request body bytes.
74
+ * @param handler - Optional definition whose result schema validates `event.result`.
75
+ * @param options - HMAC secret and signature header.
76
+ * @returns The typed webhook event.
77
+ * @throws {VeyraWebhookError} When the signature is missing/invalid or the body is not JSON.
78
+ * @throws {VeyraValidationError} When `event.result` fails the definition's result schema.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * const event = await parseWebhook(rawBody, sendEmail, {
83
+ * secret: process.env.VEYRA_CALLBACK_SECRET,
84
+ * signature: req.headers['x-veyra-signature'],
85
+ * });
86
+ * event.result?.messageId; // string | null
87
+ * ```
88
+ */
89
+ export declare function parseWebhook<TName extends string, TPayload, TResult, TQueue extends string | undefined>(rawBody: string | ArrayBuffer | ArrayBufferView, handler: HandlerDefinition<TName, TPayload, TResult, TQueue>, options?: WebhookVerificationOptions): Promise<WebhookEvent<TResult>>;
90
+ /**
91
+ * Verifies (when a secret is supplied), parses, and returns a webhook event.
92
+ *
93
+ * @param rawBody - Exact request body bytes.
94
+ * @param options - HMAC secret, signature header, and optional result type.
95
+ * @returns The typed webhook event.
96
+ * @throws {VeyraWebhookError} When the signature is missing/invalid or the body is not JSON.
97
+ */
98
+ export declare function parseWebhook<TResult = unknown>(rawBody: string | ArrayBuffer | ArrayBufferView, options?: WebhookVerificationOptions): Promise<WebhookEvent<TResult>>;