@upstash/qstash 2.7.4 → 2.7.6-canary

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 (60) hide show
  1. package/README.md +10 -3
  2. package/chunk-B3NB4QLV.mjs +2920 -0
  3. package/chunk-IJ3475FO.mjs +403 -0
  4. package/chunk-IJ5AEYLN.js +1 -0
  5. package/chunk-NMSGEGBP.js +403 -0
  6. package/chunk-S7JMIMW4.mjs +0 -0
  7. package/chunk-WQZ4U6LJ.js +2920 -0
  8. package/{dist/workflow/index.d.mts → client-aUVEwn93.d.mts} +867 -795
  9. package/{dist/nextjs/index.d.mts → client-aUVEwn93.d.ts} +869 -737
  10. package/cloudflare.d.mts +33 -0
  11. package/cloudflare.d.ts +33 -0
  12. package/cloudflare.js +37 -0
  13. package/cloudflare.mjs +37 -0
  14. package/h3.d.mts +17 -0
  15. package/h3.d.ts +17 -0
  16. package/h3.js +10 -0
  17. package/h3.mjs +10 -0
  18. package/hono.d.mts +25 -0
  19. package/hono.d.ts +25 -0
  20. package/hono.js +22 -0
  21. package/hono.mjs +22 -0
  22. package/index.d.mts +54 -0
  23. package/index.d.ts +54 -0
  24. package/index.js +41 -0
  25. package/index.mjs +41 -0
  26. package/nextjs.d.mts +38 -0
  27. package/nextjs.d.ts +38 -0
  28. package/nextjs.js +178 -0
  29. package/nextjs.mjs +178 -0
  30. package/nuxt.d.mts +12 -0
  31. package/nuxt.d.ts +12 -0
  32. package/nuxt.js +11 -0
  33. package/nuxt.mjs +11 -0
  34. package/package.json +1 -1
  35. package/solidjs.d.mts +22 -0
  36. package/solidjs.d.ts +22 -0
  37. package/solidjs.js +56 -0
  38. package/solidjs.mjs +56 -0
  39. package/svelte.d.mts +24 -0
  40. package/svelte.d.ts +24 -0
  41. package/svelte.js +53 -0
  42. package/svelte.mjs +53 -0
  43. package/workflow.d.mts +2 -0
  44. package/workflow.d.ts +2 -0
  45. package/workflow.js +18 -0
  46. package/workflow.mjs +18 -0
  47. package/dist/base/index.d.mts +0 -1279
  48. package/dist/base/index.mjs +0 -2
  49. package/dist/cloudflare/index.d.mts +0 -1648
  50. package/dist/cloudflare/index.mjs +0 -10
  51. package/dist/h3/index.d.mts +0 -1633
  52. package/dist/h3/index.mjs +0 -10
  53. package/dist/hono/index.d.mts +0 -1641
  54. package/dist/hono/index.mjs +0 -10
  55. package/dist/nextjs/index.mjs +0 -10
  56. package/dist/solidjs/index.d.mts +0 -1638
  57. package/dist/solidjs/index.mjs +0 -10
  58. package/dist/svelte/index.d.mts +0 -1640
  59. package/dist/svelte/index.mjs +0 -10
  60. package/dist/workflow/index.mjs +0 -10
@@ -1,1633 +0,0 @@
1
- import * as h3 from 'h3';
2
- import { H3Event } from 'h3';
3
-
4
- type State = "CREATED" | "ACTIVE" | "DELIVERED" | "ERROR" | "RETRY" | "FAILED";
5
- type HTTPMethods = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
6
- type Event = {
7
- time: number;
8
- state: State;
9
- messageId: string;
10
- nextDeliveryTime?: number;
11
- error?: string;
12
- url: string;
13
- urlGroup?: string;
14
- topicName?: string;
15
- endpointName?: string;
16
- header?: Record<string, string>;
17
- body?: string;
18
- };
19
- type BodyInit = Blob | FormData | URLSearchParams | ReadableStream<Uint8Array> | string;
20
- type HeadersInit = Headers | Record<string, string> | [string, string][] | IterableIterator<[string, string]>;
21
-
22
- type ProviderReturnType = {
23
- owner: "upstash" | "openai" | "custom";
24
- baseUrl: string;
25
- token: string;
26
- };
27
-
28
- type ChatCompletionMessage = {
29
- role: "system" | "assistant" | "user";
30
- content: string;
31
- };
32
- type ChatModel = "meta-llama/Meta-Llama-3-8B-Instruct" | "mistralai/Mistral-7B-Instruct-v0.2";
33
- type ChatResponseFormat = {
34
- type: "text" | "json_object";
35
- };
36
- type TopLogprob = {
37
- token: string;
38
- bytes: number[];
39
- logprob: number;
40
- };
41
- type ChatCompletionTokenLogprob = {
42
- token: string;
43
- bytes: number[];
44
- logprob: number;
45
- top_logprobs: TopLogprob[];
46
- };
47
- type ChoiceLogprobs = {
48
- content: ChatCompletionTokenLogprob[];
49
- };
50
- type Choice = {
51
- finish_reason: "stop" | "length";
52
- index: number;
53
- logprobs: ChoiceLogprobs;
54
- message: ChatCompletionMessage;
55
- };
56
- type CompletionUsage = {
57
- completion_tokens: number;
58
- prompt_tokens: number;
59
- total_tokens: number;
60
- };
61
- type ChatCompletion = {
62
- id: string;
63
- choices: Choice[];
64
- created: number;
65
- model: string;
66
- object: "chat.completion";
67
- system_fingerprint: string;
68
- usage: CompletionUsage;
69
- };
70
- type ChunkChoice = {
71
- delta: ChatCompletionMessage;
72
- finish_reason: "stop" | "length";
73
- index: number;
74
- logprobs: ChoiceLogprobs;
75
- };
76
- type ChatCompletionChunk = {
77
- id: string;
78
- choices: ChunkChoice[];
79
- created: number;
80
- model: string;
81
- object: "chat.completion.chunk";
82
- system_fingerprint: string;
83
- usage: CompletionUsage;
84
- };
85
- type StreamEnabled = {
86
- stream: true;
87
- };
88
- type StreamDisabled = {
89
- stream: false;
90
- } | object;
91
- type StreamParameter = StreamEnabled | StreamDisabled;
92
- type OpenAIChatModel = "gpt-4-turbo" | "gpt-4-turbo-2024-04-09" | "gpt-4-0125-preview" | "gpt-4-turbo-preview" | "gpt-4-1106-preview" | "gpt-4-vision-preview" | "gpt-4" | "gpt-4-0314" | "gpt-4-0613" | "gpt-4-32k" | "gpt-4-32k-0314" | "gpt-4-32k-0613" | "gpt-3.5-turbo" | "gpt-3.5-turbo-16k" | "gpt-3.5-turbo-0301" | "gpt-3.5-turbo-0613" | "gpt-3.5-turbo-1106" | "gpt-3.5-turbo-0125" | "gpt-3.5-turbo-16k-0613";
93
- type ChatRequestCommonFields = {
94
- frequency_penalty?: number;
95
- logit_bias?: Record<string, number>;
96
- logprobs?: boolean;
97
- top_logprobs?: number;
98
- max_tokens?: number;
99
- n?: number;
100
- presence_penalty?: number;
101
- response_format?: ChatResponseFormat;
102
- seed?: number;
103
- stop?: string | string[];
104
- temperature?: number;
105
- top_p?: number;
106
- };
107
- type PromptChatRequestFields = ChatRequestCommonFields & {
108
- system: string;
109
- user: string;
110
- };
111
- type ChatRequestFields = ChatRequestCommonFields & {
112
- messages: ChatCompletionMessage[];
113
- };
114
- type ChatRequestProviders = {
115
- provider: ProviderReturnType;
116
- model: OpenAIChatModel;
117
- analytics?: {
118
- name: "helicone";
119
- token: string;
120
- };
121
- } | {
122
- provider: ProviderReturnType;
123
- model: string;
124
- analytics?: {
125
- name: "helicone";
126
- token: string;
127
- };
128
- } | {
129
- provider: ProviderReturnType;
130
- model: ChatModel;
131
- analytics?: {
132
- name: "helicone";
133
- token: string;
134
- };
135
- };
136
- type PromptChatRequest<TStream extends StreamParameter> = ChatRequestProviders & PromptChatRequestFields & TStream;
137
- type ChatRequest<TStream extends StreamParameter> = ChatRequestProviders & ChatRequestFields & TStream;
138
-
139
- type UpstashRequest = {
140
- /**
141
- * The path to the resource.
142
- */
143
- path: string[];
144
- /**
145
- * A BodyInit object or null to set request's body.
146
- */
147
- body?: BodyInit | null;
148
- /**
149
- * A Headers object, an object literal, or an array of two-item arrays to set
150
- * request's headers.
151
- */
152
- headers?: HeadersInit;
153
- /**
154
- * A boolean to set request's keepalive.
155
- */
156
- keepalive?: boolean;
157
- /**
158
- * A string to set request's method.
159
- */
160
- method?: HTTPMethods;
161
- query?: Record<string, string | number | boolean | undefined>;
162
- /**
163
- * if enabled, call `res.json()`
164
- *
165
- * @default true
166
- */
167
- parseResponseAsJson?: boolean;
168
- baseUrl?: string;
169
- };
170
- type UpstashResponse<TResult> = TResult & {
171
- error?: string;
172
- };
173
- type Requester = {
174
- request: <TResult = unknown>(request: UpstashRequest) => Promise<UpstashResponse<TResult>>;
175
- requestStream: (request: UpstashRequest) => AsyncIterable<ChatCompletionChunk>;
176
- };
177
- type RetryConfig = false | {
178
- /**
179
- * The number of retries to attempt before giving up.
180
- *
181
- * @default 5
182
- */
183
- retries?: number;
184
- /**
185
- * A backoff function receives the current retry cound and returns a number in milliseconds to wait before retrying.
186
- *
187
- * @default
188
- * ```ts
189
- * Math.exp(retryCount) * 50
190
- * ```
191
- */
192
- backoff?: (retryCount: number) => number;
193
- };
194
-
195
- /**
196
- * Necessary to verify the signature of a request.
197
- */
198
- type ReceiverConfig = {
199
- /**
200
- * The current signing key. Get it from `https://console.upstash.com/qstash
201
- */
202
- currentSigningKey: string;
203
- /**
204
- * The next signing key. Get it from `https://console.upstash.com/qstash
205
- */
206
- nextSigningKey: string;
207
- };
208
- type VerifyRequest = {
209
- /**
210
- * The signature from the `upstash-signature` header.
211
- */
212
- signature: string;
213
- /**
214
- * The raw request body.
215
- */
216
- body: string;
217
- /**
218
- * URL of the endpoint where the request was sent to.
219
- *
220
- * Omit empty to disable checking the url.
221
- */
222
- url?: string;
223
- /**
224
- * Number of seconds to tolerate when checking `nbf` and `exp` claims, to deal with small clock differences among different servers
225
- *
226
- * @default 0
227
- */
228
- clockTolerance?: number;
229
- };
230
- /**
231
- * Receiver offers a simple way to verify the signature of a request.
232
- */
233
- declare class Receiver {
234
- private readonly currentSigningKey;
235
- private readonly nextSigningKey;
236
- constructor(config: ReceiverConfig);
237
- /**
238
- * Verify the signature of a request.
239
- *
240
- * Tries to verify the signature with the current signing key.
241
- * If that fails, maybe because you have rotated the keys recently, it will
242
- * try to verify the signature with the next signing key.
243
- *
244
- * If that fails, the signature is invalid and a `SignatureError` is thrown.
245
- */
246
- verify(request: VerifyRequest): Promise<boolean>;
247
- /**
248
- * Verify signature with a specific signing key
249
- */
250
- private verifyWithKey;
251
- }
252
-
253
- type Message = {
254
- /**
255
- * A unique identifier for this message.
256
- */
257
- messageId: string;
258
- /**
259
- * The url group name if this message was sent to a urlGroup.
260
- */
261
- urlGroup?: string;
262
- /**
263
- * Deprecated. The topic name if this message was sent to a urlGroup. Use urlGroup instead
264
- */
265
- topicName?: string;
266
- /**
267
- * The url where this message is sent to.
268
- */
269
- url: string;
270
- /**
271
- * The endpoint name of the message if the endpoint is given a
272
- * name within the url group.
273
- */
274
- endpointName?: string;
275
- /**
276
- * The api name if this message was sent to an api
277
- */
278
- api?: string;
279
- /**
280
- * The http method used to deliver the message
281
- */
282
- method?: HTTPMethods;
283
- /**
284
- * The http headers sent along with the message to your API.
285
- */
286
- header?: Record<string, string[]>;
287
- /**
288
- * The http body sent to your API
289
- */
290
- body?: string;
291
- /**
292
- * The base64 encoded body if the body contains non-UTF-8 characters,
293
- * `None` otherwise.
294
- */
295
- bodyBase64?: string;
296
- /**
297
- * Maxmimum number of retries.
298
- */
299
- maxRetries?: number;
300
- /**
301
- * A unix timestamp (milliseconds) after which this message may get delivered.
302
- */
303
- notBefore?: number;
304
- /**
305
- * A unix timestamp (milliseconds) when this messages was created.
306
- */
307
- createdAt: number;
308
- /**
309
- * The callback url if configured.
310
- */
311
- callback?: string;
312
- /**
313
- * The failure callback url if configured.
314
- */
315
- failureCallback?: string;
316
- /**
317
- * The queue name if this message was sent to a queue.
318
- */
319
- queueName?: string;
320
- /**
321
- * The scheduleId of the message if the message is triggered by a schedule
322
- */
323
- scheduleId?: string;
324
- /**
325
- * IP address of the publisher of this message
326
- */
327
- callerIp?: string;
328
- };
329
- declare class Messages {
330
- private readonly http;
331
- constructor(http: Requester);
332
- /**
333
- * Get a message
334
- */
335
- get(messageId: string): Promise<Message>;
336
- /**
337
- * Cancel a message
338
- */
339
- delete(messageId: string): Promise<void>;
340
- deleteMany(messageIds: string[]): Promise<number>;
341
- deleteAll(): Promise<number>;
342
- }
343
-
344
- type DlqMessage = Message & {
345
- /**
346
- * The unique id within the DLQ
347
- */
348
- dlqId: string;
349
- /**
350
- * The HTTP status code of the last failed delivery attempt
351
- */
352
- responseStatus?: number;
353
- /**
354
- * The response headers of the last failed delivery attempt
355
- */
356
- responseHeader?: Record<string, string[]>;
357
- /**
358
- * The response body of the last failed delivery attempt if it is
359
- * composed of UTF-8 characters only, `None` otherwise.
360
- */
361
- responseBody?: string;
362
- /**
363
- * The base64 encoded response body of the last failed delivery attempt
364
- * if the response body contains non-UTF-8 characters, `None` otherwise.
365
- */
366
- responseBodyBase64?: string;
367
- };
368
- type DLQFilter = {
369
- /**
370
- * Filter DLQ entries by message id
371
- */
372
- messageId?: string;
373
- /**
374
- * Filter DLQ entries by url
375
- */
376
- url?: string;
377
- /**
378
- * Filter DLQ entries by url group name
379
- */
380
- urlGroup?: string;
381
- /**
382
- * Filter DLQ entries by api name
383
- */
384
- api?: string;
385
- /**
386
- * Filter DLQ entries by queue name
387
- */
388
- queueName?: string;
389
- /**
390
- * Filter DLQ entries by schedule id
391
- */
392
- scheduleId?: string;
393
- /**
394
- * Filter DLQ entries by starting time, in milliseconds
395
- */
396
- fromDate?: number;
397
- /**
398
- * Filter DLQ entries by ending time, in milliseconds
399
- */
400
- toDate?: number;
401
- /**
402
- * Filter DLQ entries by HTTP status of the response
403
- */
404
- responseStatus?: number;
405
- /**
406
- * Filter DLQ entries by IP address of the publisher of the message
407
- */
408
- callerIp?: string;
409
- };
410
- declare class DLQ {
411
- private readonly http;
412
- constructor(http: Requester);
413
- /**
414
- * List messages in the dlq
415
- */
416
- listMessages(options?: {
417
- cursor?: string;
418
- count?: number;
419
- filter?: DLQFilter;
420
- }): Promise<{
421
- messages: DlqMessage[];
422
- cursor?: string;
423
- }>;
424
- /**
425
- * Remove a message from the dlq using it's `dlqId`
426
- */
427
- delete(dlqMessageId: string): Promise<void>;
428
- /**
429
- * Remove multiple messages from the dlq using their `dlqId`s
430
- */
431
- deleteMany(request: {
432
- dlqIds: string[];
433
- }): Promise<{
434
- deleted: number;
435
- }>;
436
- }
437
-
438
- type Unit = "s" | "m" | "h" | "d";
439
- type Duration = `${bigint}${Unit}`;
440
-
441
- declare class Chat {
442
- private http;
443
- private token;
444
- constructor(http: Requester, token: string);
445
- private static toChatRequest;
446
- /**
447
- * Calls the Upstash completions api given a ChatRequest.
448
- *
449
- * Returns a ChatCompletion or a stream of ChatCompletionChunks
450
- * if stream is enabled.
451
- *
452
- * @param request ChatRequest with messages
453
- * @returns Chat completion or stream
454
- */
455
- create: <TStream extends StreamParameter>(request: ChatRequest<TStream>) => Promise<TStream extends StreamEnabled ? AsyncIterable<ChatCompletionChunk> : ChatCompletion>;
456
- /**
457
- * Calls the Upstash completions api given a ChatRequest.
458
- *
459
- * Returns a ChatCompletion or a stream of ChatCompletionChunks
460
- * if stream is enabled.
461
- *
462
- * @param request ChatRequest with messages
463
- * @returns Chat completion or stream
464
- */
465
- private createThirdParty;
466
- private getAuthorizationToken;
467
- /**
468
- * Calls the Upstash completions api given a PromptRequest.
469
- *
470
- * Returns a ChatCompletion or a stream of ChatCompletionChunks
471
- * if stream is enabled.
472
- *
473
- * @param request PromptRequest with system and user messages.
474
- * Note that system parameter shouldn't be passed in the case of
475
- * mistralai/Mistral-7B-Instruct-v0.2 model.
476
- * @returns Chat completion or stream
477
- */
478
- prompt: <TStream extends StreamParameter>(request: PromptChatRequest<TStream>) => Promise<TStream extends StreamEnabled ? AsyncIterable<ChatCompletionChunk> : ChatCompletion>;
479
- }
480
-
481
- type QueueResponse = {
482
- createdAt: number;
483
- updatedAt: number;
484
- name: string;
485
- parallelism: number;
486
- lag: number;
487
- paused: boolean;
488
- };
489
- type UpsertQueueRequest = {
490
- /**
491
- * The number of parallel consumers consuming from the queue.
492
- *
493
- * @default 1
494
- */
495
- parallelism?: number;
496
- /**
497
- * Whether to pause the queue or not. A paused queue will not
498
- * deliver new messages until it is resumed.
499
- *
500
- * @default false
501
- */
502
- paused?: boolean;
503
- };
504
- declare class Queue {
505
- private readonly http;
506
- private readonly queueName;
507
- constructor(http: Requester, queueName?: string);
508
- /**
509
- * Create or update the queue
510
- */
511
- upsert(request: UpsertQueueRequest): Promise<void>;
512
- /**
513
- * Get the queue details
514
- */
515
- get(): Promise<QueueResponse>;
516
- /**
517
- * List queues
518
- */
519
- list(): Promise<QueueResponse[]>;
520
- /**
521
- * Delete the queue
522
- */
523
- delete(): Promise<void>;
524
- /**
525
- * Enqueue a message to a queue.
526
- */
527
- enqueue<TRequest extends PublishRequest>(request: TRequest): Promise<PublishResponse<TRequest>>;
528
- /**
529
- * Enqueue a message to a queue, serializing the body to JSON.
530
- */
531
- enqueueJSON<TBody = unknown, TRequest extends PublishRequest<TBody> = PublishRequest<TBody>>(request: TRequest): Promise<PublishResponse<TRequest>>;
532
- /**
533
- * Pauses the queue.
534
- *
535
- * A paused queue will not deliver messages until
536
- * it is resumed.
537
- */
538
- pause(): Promise<void>;
539
- /**
540
- * Resumes the queue.
541
- */
542
- resume(): Promise<void>;
543
- }
544
-
545
- type Schedule = {
546
- scheduleId: string;
547
- cron: string;
548
- createdAt: number;
549
- destination: string;
550
- method: string;
551
- header?: Record<string, string[]>;
552
- body?: string;
553
- bodyBase64?: string;
554
- retries: number;
555
- delay?: number;
556
- callback?: string;
557
- failureCallback?: string;
558
- callerIp?: string;
559
- isPaused: boolean;
560
- };
561
- type CreateScheduleRequest = {
562
- /**
563
- * Either a URL or urlGroup name
564
- */
565
- destination: string;
566
- /**
567
- * The message to send.
568
- *
569
- * This can be anything, but please set the `Content-Type` header accordingly.
570
- *
571
- * You can leave this empty if you want to send a message with no body.
572
- */
573
- body?: BodyInit;
574
- /**
575
- * Optionally send along headers with the message.
576
- * These headers will be sent to your destination.
577
- *
578
- * We highly recommend sending a `Content-Type` header along, as this will help your destination
579
- * server to understand the content of the message.
580
- */
581
- headers?: HeadersInit;
582
- /**
583
- * Optionally delay the delivery of this message.
584
- *
585
- * In seconds.
586
- *
587
- * @default undefined
588
- */
589
- delay?: Duration | number;
590
- /**
591
- * In case your destination server is unavailable or returns a status code outside of the 200-299
592
- * range, we will retry the request after a certain amount of time.
593
- *
594
- * Configure how many times you would like the delivery to be retried
595
- *
596
- * @default The maximum retry quota associated with your account.
597
- */
598
- retries?: number;
599
- /**
600
- * Use a callback url to forward the response of your destination server to your callback url.
601
- *
602
- * The callback url must be publicly accessible
603
- *
604
- * @default undefined
605
- */
606
- callback?: string;
607
- /**
608
- * Use a failure callback url to handle messages that could not be delivered.
609
- *
610
- * The failure callback url must be publicly accessible
611
- *
612
- * @default undefined
613
- */
614
- failureCallback?: string;
615
- /**
616
- * The method to use when sending a request to your API
617
- *
618
- * @default `POST`
619
- */
620
- method?: HTTPMethods;
621
- /**
622
- * Specify a cron expression to repeatedly send this message to the destination.
623
- */
624
- cron: string;
625
- /**
626
- * The HTTP timeout value to use while calling the destination URL.
627
- * When a timeout is specified, it will be used instead of the maximum timeout
628
- * value permitted by the QStash plan. It is useful in scenarios, where a message
629
- * should be delivered with a shorter timeout.
630
- *
631
- * In seconds.
632
- *
633
- * @default undefined
634
- */
635
- timeout?: Duration | number;
636
- /**
637
- * Schedule id to use.
638
- *
639
- * Can be used to updatine the settings of an existing schedule.
640
- *
641
- * @default undefined
642
- */
643
- scheduleId?: string;
644
- };
645
- declare class Schedules {
646
- private readonly http;
647
- constructor(http: Requester);
648
- /**
649
- * Create a schedule
650
- */
651
- create(request: CreateScheduleRequest): Promise<{
652
- scheduleId: string;
653
- }>;
654
- /**
655
- * Get a schedule
656
- */
657
- get(scheduleId: string): Promise<Schedule>;
658
- /**
659
- * List your schedules
660
- */
661
- list(): Promise<Schedule[]>;
662
- /**
663
- * Delete a schedule
664
- */
665
- delete(scheduleId: string): Promise<void>;
666
- /**
667
- * Pauses the schedule.
668
- *
669
- * A paused schedule will not deliver messages until
670
- * it is resumed.
671
- */
672
- pause({ schedule }: {
673
- schedule: string;
674
- }): Promise<void>;
675
- /**
676
- * Resumes the schedule.
677
- */
678
- resume({ schedule }: {
679
- schedule: string;
680
- }): Promise<void>;
681
- }
682
-
683
- type Endpoint = {
684
- /**
685
- * The name of the endpoint (optional)
686
- */
687
- name?: string;
688
- /**
689
- * The url of the endpoint
690
- */
691
- url: string;
692
- };
693
- type AddEndpointsRequest = {
694
- /**
695
- * The name of the url group.
696
- * Must be unique and only contain alphanumeric, hyphen, underscore and periods.
697
- */
698
- name: string;
699
- endpoints: Endpoint[];
700
- };
701
- type RemoveEndpointsRequest = {
702
- /**
703
- * The name of the url group.
704
- * Must be unique and only contain alphanumeric, hyphen, underscore and periods.
705
- */
706
- name: string;
707
- endpoints: ({
708
- name: string;
709
- url?: string;
710
- } | {
711
- name?: string;
712
- url: string;
713
- })[];
714
- };
715
- type UrlGroup = {
716
- /**
717
- * A unix timestamp (milliseconds)
718
- */
719
- createdAt: number;
720
- /**
721
- * A unix timestamp (milliseconds)
722
- */
723
- updatedAt: number;
724
- /**
725
- * The name of this url group.
726
- */
727
- name: string;
728
- /**
729
- * A list of all subscribed endpoints
730
- */
731
- endpoints: Endpoint[];
732
- };
733
- declare class UrlGroups {
734
- private readonly http;
735
- constructor(http: Requester);
736
- /**
737
- * Create a new url group with the given name and endpoints
738
- */
739
- addEndpoints(request: AddEndpointsRequest): Promise<void>;
740
- /**
741
- * Remove endpoints from a url group.
742
- */
743
- removeEndpoints(request: RemoveEndpointsRequest): Promise<void>;
744
- /**
745
- * Get a list of all url groups.
746
- */
747
- list(): Promise<UrlGroup[]>;
748
- /**
749
- * Get a single url group
750
- */
751
- get(name: string): Promise<UrlGroup>;
752
- /**
753
- * Delete a url group
754
- */
755
- delete(name: string): Promise<void>;
756
- }
757
-
758
- type ClientConfig = {
759
- /**
760
- * Url of the QStash api server.
761
- *
762
- * This is only used for testing.
763
- *
764
- * @default "https://qstash.upstash.io"
765
- */
766
- baseUrl?: string;
767
- /**
768
- * The authorization token from the upstash console.
769
- */
770
- token: string;
771
- /**
772
- * Configure how the client should retry requests.
773
- */
774
- retry?: RetryConfig;
775
- };
776
- type PublishBatchRequest<TBody = BodyInit> = PublishRequest<TBody> & {
777
- queueName?: string;
778
- };
779
- type PublishRequest<TBody = BodyInit> = {
780
- /**
781
- * The message to send.
782
- *
783
- * This can be anything, but please set the `Content-Type` header accordingly.
784
- *
785
- * You can leave this empty if you want to send a message with no body.
786
- */
787
- body?: TBody;
788
- /**
789
- * Optionally send along headers with the message.
790
- * These headers will be sent to your destination.
791
- *
792
- * We highly recommend sending a `Content-Type` header along, as this will help your destination
793
- * server to understand the content of the message.
794
- */
795
- headers?: HeadersInit;
796
- /**
797
- * Optionally delay the delivery of this message.
798
- *
799
- * In seconds.
800
- *
801
- * @default undefined
802
- */
803
- delay?: Duration | number;
804
- /**
805
- * Optionally set the absolute delay of this message.
806
- * This will override the delay option.
807
- * The message will not delivered until the specified time.
808
- *
809
- * Unix timestamp in seconds.
810
- *
811
- * @default undefined
812
- */
813
- notBefore?: number;
814
- /**
815
- * Provide a unique id for deduplication. This id will be used to detect duplicate messages.
816
- * If a duplicate message is detected, the request will be accepted but not enqueued.
817
- *
818
- * We store deduplication ids for 90 days. Afterwards it is possible that the message with the
819
- * same deduplication id is delivered again.
820
- *
821
- * When scheduling a message, the deduplication happens before the schedule is created.
822
- *
823
- * @default undefined
824
- */
825
- deduplicationId?: string;
826
- /**
827
- * If true, the message content will get hashed and used as deduplication id.
828
- * If a duplicate message is detected, the request will be accepted but not enqueued.
829
- *
830
- * The content based hash includes the following values:
831
- * - All headers, except Upstash-Authorization, this includes all headers you are sending.
832
- * - The entire raw request body The destination from the url path
833
- *
834
- * We store deduplication ids for 90 days. Afterwards it is possible that the message with the
835
- * same deduplication id is delivered again.
836
- *
837
- * When scheduling a message, the deduplication happens before the schedule is created.
838
- *
839
- * @default false
840
- */
841
- contentBasedDeduplication?: boolean;
842
- /**
843
- * In case your destination server is unavaialble or returns a status code outside of the 200-299
844
- * range, we will retry the request after a certain amount of time.
845
- *
846
- * Configure how many times you would like the delivery to be retried up to the maxRetries limit
847
- * defined in your plan.
848
- *
849
- * @default 3
850
- */
851
- retries?: number;
852
- /**
853
- * Use a failure callback url to handle messages that could not be delivered.
854
- *
855
- * The failure callback url must be publicly accessible
856
- *
857
- * @default undefined
858
- */
859
- failureCallback?: string;
860
- /**
861
- * The method to use when sending a request to your API
862
- *
863
- * @default `POST`
864
- */
865
- method?: HTTPMethods;
866
- /**
867
- * The HTTP timeout value to use while calling the destination URL.
868
- * When a timeout is specified, it will be used instead of the maximum timeout
869
- * value permitted by the QStash plan. It is useful in scenarios, where a message
870
- * should be delivered with a shorter timeout.
871
- *
872
- * In seconds.
873
- *
874
- * @default undefined
875
- */
876
- timeout?: Duration | number;
877
- } & ({
878
- /**
879
- * The url where the message should be sent to.
880
- */
881
- url: string;
882
- urlGroup?: never;
883
- api?: never;
884
- topic?: never;
885
- /**
886
- * Use a callback url to forward the response of your destination server to your callback url.
887
- *
888
- * The callback url must be publicly accessible
889
- *
890
- * @default undefined
891
- */
892
- callback?: string;
893
- } | {
894
- url?: never;
895
- /**
896
- * The url group the message should be sent to.
897
- */
898
- urlGroup: string;
899
- api?: never;
900
- topic?: never;
901
- /**
902
- * Use a callback url to forward the response of your destination server to your callback url.
903
- *
904
- * The callback url must be publicly accessible
905
- *
906
- * @default undefined
907
- */
908
- callback?: string;
909
- } | {
910
- url?: string;
911
- urlGroup?: never;
912
- /**
913
- * The api endpoint the request should be sent to.
914
- */
915
- api: {
916
- name: "llm";
917
- provider?: ProviderReturnType;
918
- analytics?: {
919
- name: "helicone";
920
- token: string;
921
- };
922
- };
923
- /**
924
- * Use a callback url to forward the response of your destination server to your callback url.
925
- *
926
- * The callback url must be publicly accessible
927
- *
928
- * @default undefined
929
- */
930
- callback: string;
931
- topic?: never;
932
- } | {
933
- url?: never;
934
- urlGroup?: never;
935
- api: never;
936
- /**
937
- * Deprecated. The topic the message should be sent to. Same as urlGroup
938
- */
939
- topic?: string;
940
- /**
941
- * Use a callback url to forward the response of your destination server to your callback url.
942
- *
943
- * The callback url must be publicly accessible
944
- *
945
- * @default undefined
946
- */
947
- callback?: string;
948
- });
949
- type EventsRequest = {
950
- cursor?: number;
951
- filter?: EventsRequestFilter;
952
- };
953
- type EventsRequestFilter = {
954
- messageId?: string;
955
- state?: State;
956
- url?: string;
957
- urlGroup?: string;
958
- topicName?: string;
959
- api?: string;
960
- scheduleId?: string;
961
- queueName?: string;
962
- fromDate?: number;
963
- toDate?: number;
964
- count?: number;
965
- };
966
- type GetEventsResponse = {
967
- cursor?: number;
968
- events: Event[];
969
- };
970
- type QueueRequest = {
971
- queueName?: string;
972
- };
973
- declare class Client {
974
- http: Requester;
975
- private token;
976
- constructor(config: ClientConfig);
977
- /**
978
- * Access the urlGroup API.
979
- *
980
- * Create, read, update or delete urlGroups.
981
- */
982
- get urlGroups(): UrlGroups;
983
- /**
984
- * Deprecated. Use urlGroups instead.
985
- *
986
- * Access the topic API.
987
- *
988
- * Create, read, update or delete topics.
989
- */
990
- get topics(): UrlGroups;
991
- /**
992
- * Access the dlq API.
993
- *
994
- * List or remove messages from the DLQ.
995
- */
996
- get dlq(): DLQ;
997
- /**
998
- * Access the message API.
999
- *
1000
- * Read or cancel messages.
1001
- */
1002
- get messages(): Messages;
1003
- /**
1004
- * Access the schedule API.
1005
- *
1006
- * Create, read or delete schedules.
1007
- */
1008
- get schedules(): Schedules;
1009
- /**
1010
- * Access the workflow API.
1011
- *
1012
- * cancel workflows.
1013
- */
1014
- get workflow(): Workflow;
1015
- /**
1016
- * Access the queue API.
1017
- *
1018
- * Create, read, update or delete queues.
1019
- */
1020
- queue(request?: QueueRequest): Queue;
1021
- /**
1022
- * Access the Chat API
1023
- *
1024
- * Call the create or prompt methods
1025
- */
1026
- chat(): Chat;
1027
- publish<TRequest extends PublishRequest>(request: TRequest): Promise<PublishResponse<TRequest>>;
1028
- /**
1029
- * publishJSON is a utility wrapper around `publish` that automatically serializes the body
1030
- * and sets the `Content-Type` header to `application/json`.
1031
- */
1032
- publishJSON<TBody = unknown, TRequest extends PublishRequest<TBody> = PublishRequest<TBody>>(request: TRequest): Promise<PublishResponse<TRequest>>;
1033
- /**
1034
- * Batch publish messages to QStash.
1035
- */
1036
- batch(request: PublishBatchRequest[]): Promise<PublishResponse<PublishRequest>[]>;
1037
- /**
1038
- * Batch publish messages to QStash, serializing each body to JSON.
1039
- */
1040
- batchJSON<TBody = unknown, TRequest extends PublishBatchRequest<TBody> = PublishBatchRequest<TBody>>(request: TRequest[]): Promise<PublishResponse<TRequest>[]>;
1041
- /**
1042
- * Retrieve your logs.
1043
- *
1044
- * The logs endpoint is paginated and returns only 100 logs at a time.
1045
- * If you want to receive more logs, you can use the cursor to paginate.
1046
- *
1047
- * The cursor is a unix timestamp with millisecond precision
1048
- *
1049
- * @example
1050
- * ```ts
1051
- * let cursor = Date.now()
1052
- * const logs: Log[] = []
1053
- * while (cursor > 0) {
1054
- * const res = await qstash.logs({ cursor })
1055
- * logs.push(...res.logs)
1056
- * cursor = res.cursor ?? 0
1057
- * }
1058
- * ```
1059
- */
1060
- events(request?: EventsRequest): Promise<GetEventsResponse>;
1061
- }
1062
- type PublishToApiResponse = {
1063
- messageId: string;
1064
- };
1065
- type PublishToUrlResponse = PublishToApiResponse & {
1066
- url: string;
1067
- deduplicated?: boolean;
1068
- };
1069
- type PublishToUrlGroupsResponse = PublishToUrlResponse[];
1070
- type PublishResponse<TRequest> = TRequest extends {
1071
- url: string;
1072
- } ? PublishToUrlResponse : TRequest extends {
1073
- urlGroup: string;
1074
- } ? PublishToUrlGroupsResponse : PublishToApiResponse;
1075
-
1076
- /**
1077
- * Base class outlining steps. Basically, each step kind (run/sleep/sleepUntil)
1078
- * should have two methods: getPlanStep & getResultStep.
1079
- *
1080
- * getPlanStep works the same way for all so it's implemented here.
1081
- * The different step types will implement their own getResultStep method.
1082
- */
1083
- declare abstract class BaseLazyStep<TResult = unknown> {
1084
- readonly stepName: string;
1085
- abstract readonly stepType: StepType;
1086
- constructor(stepName: string);
1087
- /**
1088
- * plan step to submit when step will run parallel with other
1089
- * steps (parallel call state `first`)
1090
- *
1091
- * @param concurrent number of steps running parallel
1092
- * @param targetStep target step id corresponding to this step
1093
- * @returns
1094
- */
1095
- abstract getPlanStep(concurrent: number, targetStep: number): Step<undefined>;
1096
- /**
1097
- * result step to submit after the step executes. Used in single step executions
1098
- * and when a plan step executes in parallel executions (parallel call state `partial`).
1099
- *
1100
- * @param concurrent
1101
- * @param stepId
1102
- */
1103
- abstract getResultStep(concurrent: number, stepId: number): Promise<Step<TResult>>;
1104
- }
1105
-
1106
- declare const LOG_LEVELS: readonly ["DEBUG", "INFO", "SUBMIT", "WARN", "ERROR"];
1107
- type LogLevel = (typeof LOG_LEVELS)[number];
1108
- type ChatLogEntry = {
1109
- timestamp: number;
1110
- workflowRunId: string;
1111
- logLevel: LogLevel;
1112
- eventType: "ENDPOINT_START" | "SUBMIT_THIRD_PARTY_RESULT" | "CREATE_CONTEXT" | "SUBMIT_FIRST_INVOCATION" | "RUN_SINGLE" | "RUN_PARALLEL" | "SUBMIT_STEP" | "SUBMIT_CLEANUP" | "RESPONSE_WORKFLOW" | "RESPONSE_DEFAULT" | "ERROR";
1113
- details: unknown;
1114
- };
1115
- type WorkflowLoggerOptions = {
1116
- logLevel: LogLevel;
1117
- logOutput: "console";
1118
- };
1119
- declare class WorkflowLogger {
1120
- private logs;
1121
- private options;
1122
- private workflowRunId?;
1123
- constructor(options: WorkflowLoggerOptions);
1124
- log(level: LogLevel, eventType: ChatLogEntry["eventType"], details?: unknown): Promise<void>;
1125
- setWorkflowRunId(workflowRunId: string): void;
1126
- private writeToConsole;
1127
- private shouldLog;
1128
- static getLogger(verbose?: boolean | WorkflowLogger): WorkflowLogger | undefined;
1129
- }
1130
-
1131
- declare class AutoExecutor {
1132
- private context;
1133
- private promises;
1134
- private activeLazyStepList?;
1135
- private debug?;
1136
- private readonly nonPlanStepCount;
1137
- private readonly steps;
1138
- private indexInCurrentList;
1139
- stepCount: number;
1140
- planStepCount: number;
1141
- protected executingStep: string | false;
1142
- constructor(context: WorkflowContext, steps: Step[], debug?: WorkflowLogger);
1143
- /**
1144
- * Adds the step function to the list of step functions to run in
1145
- * parallel. After adding the function, defers the execution, so
1146
- * that if there is another step function to be added, it's also
1147
- * added.
1148
- *
1149
- * After all functions are added, list of functions are executed.
1150
- * If there is a single function, it's executed by itself. If there
1151
- * are multiple, they are run in parallel.
1152
- *
1153
- * If a function is already executing (this.executingStep), this
1154
- * means that there is a nested step which is not allowed. In this
1155
- * case, addStep throws QStashWorkflowError.
1156
- *
1157
- * @param stepInfo step plan to add
1158
- * @returns result of the step function
1159
- */
1160
- addStep<TResult>(stepInfo: BaseLazyStep<TResult>): Promise<TResult>;
1161
- /**
1162
- * Wraps a step function to set this.executingStep to step name
1163
- * before running and set this.executingStep to False after execution
1164
- * ends.
1165
- *
1166
- * this.executingStep allows us to detect nested steps which are not
1167
- * allowed.
1168
- *
1169
- * @param stepName name of the step being wrapped
1170
- * @param stepFunction step function to wrap
1171
- * @returns wrapped step function
1172
- */
1173
- wrapStep<TResult = unknown>(stepName: string, stepFunction: StepFunction<TResult>): TResult | Promise<TResult>;
1174
- /**
1175
- * Executes a step:
1176
- * - If the step result is available in the steps, returns the result
1177
- * - If the result is not avaiable, runs the function
1178
- * - Sends the result to QStash
1179
- *
1180
- * @param lazyStep lazy step to execute
1181
- * @returns step result
1182
- */
1183
- protected runSingle<TResult>(lazyStep: BaseLazyStep<TResult>): Promise<TResult>;
1184
- /**
1185
- * Runs steps in parallel.
1186
- *
1187
- * @param stepName parallel step name
1188
- * @param stepFunctions list of async functions to run in parallel
1189
- * @returns results of the functions run in parallel
1190
- */
1191
- protected runParallel<TResults extends unknown[]>(parallelSteps: {
1192
- [K in keyof TResults]: BaseLazyStep<TResults[K]>;
1193
- }): Promise<TResults>;
1194
- /**
1195
- * Determines the parallel call state
1196
- *
1197
- * First filters the steps to get the steps which are after `initialStepCount` parameter.
1198
- *
1199
- * Depending on the remaining steps, decides the parallel state:
1200
- * - "first": If there are no steps
1201
- * - "last" If there are equal to or more than `2 * parallelStepCount`. We multiply by two
1202
- * because each step in a parallel execution will have 2 steps: a plan step and a result
1203
- * step.
1204
- * - "partial": If the last step is a plan step
1205
- * - "discard": If the last step is not a plan step. This means that the parallel execution
1206
- * is in progress (there are still steps to run) and one step has finished and submitted
1207
- * its result to QStash
1208
- *
1209
- * @param parallelStepCount number of steps to run in parallel
1210
- * @param initialStepCount steps after the parallel invocation
1211
- * @returns parallel call state
1212
- */
1213
- protected getParallelCallState(parallelStepCount: number, initialStepCount: number): ParallelCallState;
1214
- /**
1215
- * sends the steps to QStash as batch
1216
- *
1217
- * @param steps steps to send
1218
- */
1219
- private submitStepsToQStash;
1220
- /**
1221
- * Get the promise by executing the lazt steps list. If there is a single
1222
- * step, we call `runSingle`. Otherwise `runParallel` is called.
1223
- *
1224
- * @param lazyStepList steps list to execute
1225
- * @returns promise corresponding to the execution
1226
- */
1227
- private getExecutionPromise;
1228
- /**
1229
- * @param lazyStepList steps we executed
1230
- * @param result result of the promise from `getExecutionPromise`
1231
- * @param index index of the current step
1232
- * @returns result[index] if lazyStepList > 1, otherwise result
1233
- */
1234
- private static getResult;
1235
- private deferExecution;
1236
- }
1237
-
1238
- /**
1239
- * QStash workflow context
1240
- *
1241
- * See the docs for fields and methods https://upstash.com/docs/qstash/workflows/basics/context
1242
- */
1243
- declare class WorkflowContext<TInitialPayload = unknown> {
1244
- protected readonly executor: AutoExecutor;
1245
- protected readonly steps: Step[];
1246
- /**
1247
- * QStash client of the workflow
1248
- *
1249
- * Can be overwritten by passing `qstashClient` parameter in `serve`:
1250
- *
1251
- * ```ts
1252
- * import { Client } from "@upstash/qstash"
1253
- *
1254
- * export const POST = serve(
1255
- * async (context) => {
1256
- * ...
1257
- * },
1258
- * {
1259
- * qstashClient: new Client({...})
1260
- * }
1261
- * )
1262
- * ```
1263
- */
1264
- readonly qstashClient: WorkflowClient;
1265
- /**
1266
- * Run id of the workflow
1267
- */
1268
- readonly workflowRunId: string;
1269
- /**
1270
- * URL of the workflow
1271
- *
1272
- * Can be overwritten by passing a `url` parameter in `serve`:
1273
- *
1274
- * ```ts
1275
- * export const POST = serve(
1276
- * async (context) => {
1277
- * ...
1278
- * },
1279
- * {
1280
- * url: "new-url-value"
1281
- * }
1282
- * )
1283
- * ```
1284
- */
1285
- readonly url: string;
1286
- /**
1287
- * URL to call in case of workflow failure with QStash failure callback
1288
- *
1289
- * https://upstash.com/docs/qstash/features/callbacks#what-is-a-failure-callback
1290
- *
1291
- * Can be overwritten by passing a `failureUrl` parameter in `serve`:
1292
- *
1293
- * ```ts
1294
- * export const POST = serve(
1295
- * async (context) => {
1296
- * ...
1297
- * },
1298
- * {
1299
- * failureUrl: "new-url-value"
1300
- * }
1301
- * )
1302
- * ```
1303
- */
1304
- readonly failureUrl?: string;
1305
- /**
1306
- * Payload of the request which started the workflow.
1307
- *
1308
- * To specify its type, you can define `serve` as follows:
1309
- *
1310
- * ```ts
1311
- * // set requestPayload type to MyPayload:
1312
- * export const POST = serve<MyPayload>(
1313
- * async (context) => {
1314
- * ...
1315
- * }
1316
- * )
1317
- * ```
1318
- *
1319
- * By default, `serve` tries to apply `JSON.parse` to the request payload.
1320
- * If your payload is encoded in a format other than JSON, you can utilize
1321
- * the `initialPayloadParser` parameter:
1322
- *
1323
- * ```ts
1324
- * export const POST = serve<MyPayload>(
1325
- * async (context) => {
1326
- * ...
1327
- * },
1328
- * {
1329
- * initialPayloadParser: (initialPayload) => {return doSomething(initialPayload)}
1330
- * }
1331
- * )
1332
- * ```
1333
- */
1334
- readonly requestPayload: TInitialPayload;
1335
- /**
1336
- * headers of the initial request
1337
- */
1338
- readonly headers: Headers;
1339
- /**
1340
- * initial payload as a raw string
1341
- */
1342
- readonly rawInitialPayload: string;
1343
- /**
1344
- * Map of environment variables and their values.
1345
- *
1346
- * Can be set using the `env` option of serve:
1347
- *
1348
- * ```ts
1349
- * export const POST = serve<MyPayload>(
1350
- * async (context) => {
1351
- * const key = context.env["API_KEY"];
1352
- * },
1353
- * {
1354
- * env: {
1355
- * "API_KEY": "*****";
1356
- * }
1357
- * }
1358
- * )
1359
- * ```
1360
- *
1361
- * Default value is set to `process.env`.
1362
- */
1363
- readonly env: Record<string, string | undefined>;
1364
- constructor({ qstashClient, workflowRunId, headers, steps, url, failureUrl, debug, initialPayload, rawInitialPayload, env, }: {
1365
- qstashClient: WorkflowClient;
1366
- workflowRunId: string;
1367
- headers: Headers;
1368
- steps: Step[];
1369
- url: string;
1370
- failureUrl?: string;
1371
- debug?: WorkflowLogger;
1372
- initialPayload: TInitialPayload;
1373
- rawInitialPayload?: string;
1374
- env?: Record<string, string | undefined>;
1375
- });
1376
- /**
1377
- * Executes a workflow step
1378
- *
1379
- * ```typescript
1380
- * const result = await context.run("step 1", () => {
1381
- * return "result"
1382
- * })
1383
- * ```
1384
- *
1385
- * Can also be called in parallel and the steps will be executed
1386
- * simulatenously:
1387
- *
1388
- * ```typescript
1389
- * const [result1, result2] = await Promise.all([
1390
- * context.run("step 1", () => {
1391
- * return "result1"
1392
- * })
1393
- * context.run("step 2", async () => {
1394
- * return await fetchResults()
1395
- * })
1396
- * ])
1397
- * ```
1398
- *
1399
- * @param stepName name of the step
1400
- * @param stepFunction step function to be executed
1401
- * @returns result of the step function
1402
- */
1403
- run<TResult>(stepName: string, stepFunction: StepFunction<TResult>): Promise<TResult>;
1404
- /**
1405
- * Stops the execution for the duration provided.
1406
- *
1407
- * @param stepName
1408
- * @param duration sleep duration in seconds
1409
- * @returns undefined
1410
- */
1411
- sleep(stepName: string, duration: number): Promise<void>;
1412
- /**
1413
- * Stops the execution until the date time provided.
1414
- *
1415
- * @param stepName
1416
- * @param datetime time to sleep until. Can be provided as a number (in unix seconds),
1417
- * as a Date object or a string (passed to `new Date(datetimeString)`)
1418
- * @returns undefined
1419
- */
1420
- sleepUntil(stepName: string, datetime: Date | string | number): Promise<void>;
1421
- /**
1422
- * Makes a third party call through QStash in order to make a
1423
- * network call without consuming any runtime.
1424
- *
1425
- * ```ts
1426
- * const postResult = await context.call<string>(
1427
- * "post call step",
1428
- * `https://www.some-endpoint.com/api`,
1429
- * "POST",
1430
- * "my-payload"
1431
- * );
1432
- * ```
1433
- *
1434
- * @param stepName
1435
- * @param url url to call
1436
- * @param method call method
1437
- * @param body call body
1438
- * @param headers call headers
1439
- * @returns call result
1440
- */
1441
- call<TResult = unknown, TBody = unknown>(stepName: string, url: string, method: HTTPMethods, body?: TBody, headers?: Record<string, string>): Promise<TResult>;
1442
- /**
1443
- * Adds steps to the executor. Needed so that it can be overwritten in
1444
- * DisabledWorkflowContext.
1445
- */
1446
- protected addStep<TResult = unknown>(step: BaseLazyStep<TResult>): Promise<TResult>;
1447
- }
1448
-
1449
- /**
1450
- * Interface for Client with required methods
1451
- *
1452
- * Neeeded to resolve import issues
1453
- */
1454
- type WorkflowClient = {
1455
- batchJSON: InstanceType<typeof Client>["batchJSON"];
1456
- publishJSON: InstanceType<typeof Client>["publishJSON"];
1457
- http: InstanceType<typeof Client>["http"];
1458
- };
1459
- /**
1460
- * Interface for Receiver with required methods
1461
- *
1462
- * Neeeded to resolve import issues
1463
- */
1464
- type WorkflowReceiver = {
1465
- verify: InstanceType<typeof Receiver>["verify"];
1466
- };
1467
- declare const StepTypes: readonly ["Initial", "Run", "SleepFor", "SleepUntil", "Call"];
1468
- type StepType = (typeof StepTypes)[number];
1469
- type ThirdPartyCallFields<TBody = unknown> = {
1470
- /**
1471
- * Third party call URL. Set when context.call is used.
1472
- */
1473
- callUrl: string;
1474
- /**
1475
- * Third party call method. Set when context.call is used.
1476
- */
1477
- callMethod: HTTPMethods;
1478
- /**
1479
- * Third party call body. Set when context.call is used.
1480
- */
1481
- callBody: TBody;
1482
- /**
1483
- * Third party call headers. Set when context.call is used.
1484
- */
1485
- callHeaders: Record<string, string>;
1486
- };
1487
- type Step<TResult = unknown, TBody = unknown> = {
1488
- /**
1489
- * index of the step
1490
- */
1491
- stepId: number;
1492
- /**
1493
- * name of the step
1494
- */
1495
- stepName: string;
1496
- /**
1497
- * type of the step (Initial/Run/SleepFor/SleepUntil/Call)
1498
- */
1499
- stepType: StepType;
1500
- /**
1501
- * step result. Set if context.run or context.call are used.
1502
- */
1503
- out?: TResult;
1504
- /**
1505
- * sleep duration in seconds. Set when context.sleep is used.
1506
- */
1507
- sleepFor?: number;
1508
- /**
1509
- * unix timestamp (in seconds) to wait until. Set when context.sleepUntil is used.
1510
- */
1511
- sleepUntil?: number;
1512
- /**
1513
- * number of steps running concurrently if the step is in a parallel run.
1514
- * Set to 1 if step is not parallel.
1515
- */
1516
- concurrent: number;
1517
- /**
1518
- * target step of a plan step. In other words, the step to assign the
1519
- * result of a plan step.
1520
- *
1521
- * undefined if the step is not a plan step (of a parallel run). Otherwise,
1522
- * set to the target step.
1523
- */
1524
- targetStep?: number;
1525
- } & (ThirdPartyCallFields<TBody> | {
1526
- [P in keyof ThirdPartyCallFields]?: never;
1527
- });
1528
- type SyncStepFunction<TResult> = () => TResult;
1529
- type AsyncStepFunction<TResult> = () => Promise<TResult>;
1530
- type StepFunction<TResult> = AsyncStepFunction<TResult> | SyncStepFunction<TResult>;
1531
- type ParallelCallState = "first" | "partial" | "discard" | "last";
1532
- type RouteFunction<TInitialPayload> = (context: WorkflowContext<TInitialPayload>) => Promise<void>;
1533
- type FinishCondition = "success" | "duplicate-step" | "fromCallback" | "auth-fail" | "failure-callback";
1534
- type WorkflowServeOptions<TResponse extends Response = Response, TInitialPayload = unknown> = {
1535
- /**
1536
- * QStash client
1537
- */
1538
- qstashClient?: WorkflowClient;
1539
- /**
1540
- * Function called to return a response after each step execution
1541
- *
1542
- * @param workflowRunId
1543
- * @returns response
1544
- */
1545
- onStepFinish?: (workflowRunId: string, finishCondition: FinishCondition) => TResponse;
1546
- /**
1547
- * Function to parse the initial payload passed by the user
1548
- */
1549
- initialPayloadParser?: (initialPayload: string) => TInitialPayload;
1550
- /**
1551
- * Url of the endpoint where the workflow is set up.
1552
- *
1553
- * If not set, url will be inferred from the request.
1554
- */
1555
- url?: string;
1556
- /**
1557
- * Verbose mode
1558
- *
1559
- * Disabled if not set. If set to true, a logger is created automatically.
1560
- *
1561
- * Alternatively, a WorkflowLogger can be passed.
1562
- */
1563
- verbose?: WorkflowLogger | true;
1564
- /**
1565
- * Receiver to verify *all* requests by checking if they come from QStash
1566
- *
1567
- * By default, a receiver is created from the env variables
1568
- * QSTASH_CURRENT_SIGNING_KEY and QSTASH_NEXT_SIGNING_KEY if they are set.
1569
- */
1570
- receiver?: WorkflowReceiver;
1571
- /**
1572
- * Url to call if QStash retries are exhausted while executing the workflow
1573
- */
1574
- failureUrl?: string;
1575
- /**
1576
- * Failure function called when QStash retries are exhausted while executing
1577
- * the workflow. Will overwrite `failureUrl` parameter with the workflow
1578
- * endpoint if passed.
1579
- *
1580
- * @param context workflow context at the moment of error
1581
- * @param failStatus error status
1582
- * @param failResponse error message
1583
- * @returns void
1584
- */
1585
- failureFunction?: (context: Omit<WorkflowContext, "run" | "sleepUntil" | "sleep" | "call">, failStatus: number, failResponse: string, failHeader: Record<string, string[]>) => Promise<void> | void;
1586
- /**
1587
- * Base Url of the workflow endpoint
1588
- *
1589
- * Can be used to set if there is a local tunnel or a proxy between
1590
- * QStash and the workflow endpoint.
1591
- *
1592
- * Will be set to the env variable UPSTASH_WORKFLOW_URL if not passed.
1593
- * If the env variable is not set, the url will be infered as usual from
1594
- * the `request.url` or the `url` parameter in `serve` options.
1595
- *
1596
- * @default undefined
1597
- */
1598
- baseUrl?: string;
1599
- /**
1600
- * Optionally, one can pass an env object mapping environment
1601
- * variables to their keys.
1602
- *
1603
- * Useful in cases like cloudflare with hono.
1604
- */
1605
- env?: Record<string, string | undefined>;
1606
- };
1607
-
1608
- declare class Workflow {
1609
- private readonly http;
1610
- constructor(http: Requester);
1611
- /**
1612
- * Cancel an ongoing workflow
1613
- *
1614
- * @param workflowRunId run id of the workflow to delete
1615
- * @returns true if workflow is succesfully deleted. Otherwise throws QStashError
1616
- */
1617
- cancel(workflowRunId: string): Promise<true | {
1618
- error: string;
1619
- }>;
1620
- }
1621
-
1622
- type VerifySignatureConfig = {
1623
- currentSigningKey?: string;
1624
- nextSigningKey?: string;
1625
- clockTolerance?: number;
1626
- };
1627
- declare const verifySignatureH3: (handler: (event: H3Event) => Promise<unknown>, config?: VerifySignatureConfig) => h3.EventHandler<h3.EventHandlerRequest, Promise<unknown>>;
1628
- declare const serve: <TInitialPayload = unknown>(routeFunction: RouteFunction<TInitialPayload>, options?: Omit<WorkflowServeOptions<Response, TInitialPayload>, "onStepFinish">) => h3.EventHandler<h3.EventHandlerRequest, Promise<Response | {
1629
- status: number;
1630
- body: string;
1631
- }>>;
1632
-
1633
- export { serve, verifySignatureH3 };