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