@upstash/qstash 2.7.1 → 2.7.3

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.
@@ -493,6 +493,9 @@ declare class DLQ {
493
493
  }>;
494
494
  }
495
495
 
496
+ type Unit = "s" | "m" | "h" | "d";
497
+ type Duration = `${bigint}${Unit}`;
498
+
496
499
  declare class Chat {
497
500
  private http;
498
501
  private token;
@@ -641,7 +644,7 @@ type CreateScheduleRequest = {
641
644
  *
642
645
  * @default undefined
643
646
  */
644
- delay?: number;
647
+ delay?: Duration | number;
645
648
  /**
646
649
  * In case your destination server is unavailable or returns a status code outside of the 200-299
647
650
  * range, we will retry the request after a certain amount of time.
@@ -687,7 +690,7 @@ type CreateScheduleRequest = {
687
690
  *
688
691
  * @default undefined
689
692
  */
690
- timeout?: number;
693
+ timeout?: Duration | number;
691
694
  /**
692
695
  * Schedule id to use.
693
696
  *
@@ -944,7 +947,7 @@ type PublishRequest<TBody = BodyInit> = {
944
947
  *
945
948
  * @default undefined
946
949
  */
947
- delay?: number;
950
+ delay?: Duration | number;
948
951
  /**
949
952
  * Optionally set the absolute delay of this message.
950
953
  * This will override the delay option.
@@ -1017,7 +1020,7 @@ type PublishRequest<TBody = BodyInit> = {
1017
1020
  *
1018
1021
  * @default undefined
1019
1022
  */
1020
- timeout?: number;
1023
+ timeout?: Duration | number;
1021
1024
  } & ({
1022
1025
  /**
1023
1026
  * The url where the message should be sent to.
@@ -1,2 +1,2 @@
1
1
  import*as j from"jose";import K from"crypto-js";var P=class extends Error{constructor(e){super(e),this.name="SignatureError"}},$=class{currentSigningKey;nextSigningKey;constructor(e){this.currentSigningKey=e.currentSigningKey,this.nextSigningKey=e.nextSigningKey}async verify(e){return await this.verifyWithKey(this.currentSigningKey,e)?!0:this.verifyWithKey(this.nextSigningKey,e)}async verifyWithKey(e,t){let n=(await j.jwtVerify(t.signature,new TextEncoder().encode(e),{issuer:"Upstash",clockTolerance:t.clockTolerance}).catch(a=>{throw new P(a.message)})).payload;if(t.url!==void 0&&n.sub!==t.url)throw new P(`invalid subject: ${n.sub}, want: ${t.url}`);let o=K.SHA256(t.body).toString(K.enc.Base64url),i=new RegExp(/=+$/);if(n.body.replace(i,"")!==o.replace(i,""))throw new P(`body hash does not match, want: ${n.body}, got: ${o}`);return!0}};var O=class{http;constructor(e){this.http=e}async listMessages(e){let t={...e?.filter,topicName:e?.filter?.urlGroup},s=await this.http.request({method:"GET",path:["v2","dlq"],query:{cursor:e?.cursor,count:e?.count,...t}});return{messages:s.messages.map(n=>({...n,urlGroup:n.topicName})),cursor:s.cursor}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","dlq",e],parseResponseAsJson:!1})}async deleteMany(e){return await this.http.request({method:"DELETE",path:["v2","dlq"],headers:{"Content-Type":"application/json"},body:JSON.stringify({dlqIds:e.dlqIds})})}};var w=class extends Error{constructor(e){super(e),this.name="QstashError"}},N=class extends w{limit;remaining;reset;constructor(e){super(`Exceeded burst rate limit. ${JSON.stringify(e)} `),this.name="QstashRatelimitError",this.limit=e.limit,this.remaining=e.remaining,this.reset=e.reset}},L=class extends w{limitRequests;limitTokens;remainingRequests;remainingTokens;resetRequests;resetTokens;constructor(e){super(`Exceeded chat rate limit. ${JSON.stringify(e)} `),this.limitRequests=e["limit-requests"],this.limitTokens=e["limit-tokens"],this.remainingRequests=e["remaining-requests"],this.remainingTokens=e["remaining-tokens"],this.resetRequests=e["reset-requests"],this.resetTokens=e["reset-tokens"]}},q=class extends w{limit;remaining;reset;constructor(e){super(`Exceeded daily rate limit. ${JSON.stringify(e)} `),this.limit=e.limit,this.remaining=e.remaining,this.reset=e.reset,this.name="QstashChatRatelimitError"}},v=class extends w{constructor(e){super(e),this.name="QStashWorkflowError"}},E=class extends Error{stepInfo;stepName;constructor(e,t){super(`This is an QStash Workflow error thrown after a step executes. It is expected to be raised. Make sure that you await for each step. Also, if you are using try/catch blocks, you should not wrap context.run/sleep/sleepUntil/call methods with try/catch. Aborting workflow after executing step '${e}'.`),this.name="QStashWorkflowAbort",this.stepName=e,this.stepInfo=t}},te=r=>r instanceof Error?{error:r.name,message:r.message}:{error:"Error",message:"An error occured while executing workflow."};var W=class{baseUrl;authorization;options;retry;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.authorization=e.authorization,this.retry=typeof e.retry=="boolean"&&!e.retry?{attempts:1,backoff:()=>0}:{attempts:e.retry?.retries?e.retry.retries+1:5,backoff:e.retry?.backoff??(t=>Math.exp(t)*50)}}async request(e){let{response:t}=await this.requestWithBackoff(e);if(e.parseResponseAsJson!==!1)return await t.json()}async*requestStream(e){let{response:t}=await this.requestWithBackoff(e);if(!t.body)throw new Error("No response body");let n=t.body.getReader(),o=new TextDecoder;try{for(;;){let{done:i,value:a}=await n.read();if(i)break;let c=o.decode(a,{stream:!0}).split(`
2
- `).filter(Boolean);for(let u of c)if(u.startsWith("data: ")){let f=u.slice(6);if(f==="[DONE]")break;yield JSON.parse(f)}}}finally{await n.cancel()}}requestWithBackoff=async e=>{let[t,s]=this.processRequest(e),n,o;for(let i=0;i<this.retry.attempts;i++)try{n=await fetch(t.toString(),s);break}catch(a){o=a,await new Promise(p=>setTimeout(p,this.retry.backoff(i)))}if(!n)throw o??new Error("Exhausted all retries");return await this.checkResponse(n),{response:n,error:o}};processRequest=e=>{let t=new Headers(e.headers);t.has("Authorization")||t.set("Authorization",this.authorization);let s={method:e.method,headers:t,body:e.body,keepalive:e.keepalive},n=new URL([e.baseUrl??this.baseUrl,...e.path].join("/"));if(e.query)for(let[o,i]of Object.entries(e.query))i!==void 0&&n.searchParams.set(o,i.toString());return[n.toString(),s]};async checkResponse(e){if(e.status===429)throw e.headers.get("x-ratelimit-limit-requests")?new L({"limit-requests":e.headers.get("x-ratelimit-limit-requests"),"limit-tokens":e.headers.get("x-ratelimit-limit-tokens"),"remaining-requests":e.headers.get("x-ratelimit-remaining-requests"),"remaining-tokens":e.headers.get("x-ratelimit-remaining-tokens"),"reset-requests":e.headers.get("x-ratelimit-reset-requests"),"reset-tokens":e.headers.get("x-ratelimit-reset-tokens")}):e.headers.get("RateLimit-Limit")?new q({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new N({limit:e.headers.get("Burst-RateLimit-Limit"),remaining:e.headers.get("Burst-RateLimit-Remaining"),reset:e.headers.get("Burst-RateLimit-Reset")});if(e.status<200||e.status>=300){let t=await e.text();throw new w(t.length>0?t:`Error: status=${e.status}`)}}};var S=(r,e,t,s)=>{if(!r)return{};switch(r.name){case"helicone":switch(s){case"upstash":return{baseURL:"https://qstash.helicone.ai/llm/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,Authorization:`Bearer ${e}`}};default:return{baseURL:"https://gateway.helicone.ai/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,"Helicone-Target-Url":t,Authorization:`Bearer ${e}`}}}default:throw new Error("Unknown analytics provider")}},Pe=()=>({owner:"upstash",baseUrl:"https://qstash.upstash.io/llm",token:""}),ve=({token:r})=>({token:r,owner:"openai",baseUrl:"https://api.openai.com"}),Ee=({baseUrl:r,token:e})=>{let t=r.replace(/\/(v1\/)?chat\/completions$/,"");return{token:e,owner:"custom",baseUrl:t}};var A=class r{http;token;constructor(e,t){this.http=e,this.token=t}static toChatRequest(e){let t=[];return t.push({role:"system",content:e.system},{role:"user",content:e.user}),{...e,messages:t}}create=async e=>{if(e.provider.owner!="upstash")return this.createThirdParty(e);let t=JSON.stringify(e),s,n={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,..."stream"in e&&e.stream?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{}};if(e.analytics){let{baseURL:i,defaultHeaders:a}=S({name:"helicone",token:e.analytics.token},this.getAuthorizationToken(),e.provider.baseUrl,"upstash");n={...n,...a},s=i}let o=e.analytics?[]:["llm","v1","chat","completions"];return"stream"in e&&e.stream?this.http.requestStream({path:o,method:"POST",headers:n,baseUrl:s,body:t}):this.http.request({path:o,method:"POST",headers:n,baseUrl:s,body:t})};createThirdParty=async e=>{let{baseUrl:t,token:s,owner:n}=e.provider;if(n==="upstash")throw new Error("Upstash is not 3rd party provider!");delete e.provider,delete e.system;let o=e.analytics;delete e.analytics;let i=JSON.stringify(e),a=o?.name&&o.token,p=o?.name&&o.token?S({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},c="stream"in e&&e.stream,u={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...c?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...p.defaultHeaders};return await this.http[c?"requestStream":"request"]({path:a?[]:["v1","chat","completions"],method:"POST",headers:u,body:i,baseUrl:p.baseURL})};getAuthorizationToken(){let t=String(this.http.authorization).match(/Bearer (.+)/);if(!t)throw new Error("Invalid authorization header format");return t[1]}prompt=async e=>{let t=r.toChatRequest(e);return this.create(t)}};function C(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){re(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=se(s),a=n?S({name:n.name,token:n.token},i,o,"custom"):void 0;a?(z(e,a),r.url=a.baseURL):(r.url=`${o}/v1/chat/completions`,e.set("Authorization",`Bearer ${i}`))}function re(r,e,t,s){if(s){let n=S({name:s.name,token:s.token},String(t.authorization).split("Bearer ")[1],r.api?.provider?.baseUrl,"upstash");z(e,n),r.url=n.baseURL}else r.api={name:"llm"}}function se(r){if(!r?.baseUrl)throw new Error("baseUrl cannot be empty or undefined!");if(!r.token)throw new Error("token cannot be empty or undefined!");return{baseUrl:r.baseUrl,token:r.token}}function z(r,e){r.set("Helicone-Auth",e.defaultHeaders?.["Helicone-Auth"]??""),r.set("Authorization",e.defaultHeaders?.Authorization??""),e.defaultHeaders?.["Helicone-Target-Url"]&&r.set("Helicone-Target-Url",e.defaultHeaders["Helicone-Target-Url"])}function I(r){if(r.api?.name==="llm"&&!r.callback)throw new TypeError("Callback cannot be undefined when using LLM")}var _=class{http;constructor(e){this.http=e}async get(e){let t=await this.http.request({method:"GET",path:["v2","messages",e]});return{...t,urlGroup:t.topicName}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","messages",e],parseResponseAsJson:!1})}async deleteMany(e){return(await this.http.request({method:"DELETE",path:["v2","messages"],headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:e})})).cancelled}async deleteAll(){return(await this.http.request({method:"DELETE",path:["v2","messages"]})).cancelled}};var ne=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function b(r){let e=[...r.keys()].filter(t=>!ne(t));for(let t of e){let s=r.get(t);s!==null&&r.set(`Upstash-Forward-${t}`,s),r.delete(t)}return r}function x(r){let e=b(new Headers(r.headers));return e.set("Upstash-Method",r.method??"POST"),r.delay!==void 0&&e.set("Upstash-Delay",`${r.delay.toFixed(0)}s`),r.notBefore!==void 0&&e.set("Upstash-Not-Before",r.notBefore.toFixed(0)),r.deduplicationId!==void 0&&e.set("Upstash-Deduplication-Id",r.deduplicationId),r.contentBasedDeduplication!==void 0&&e.set("Upstash-Content-Based-Deduplication","true"),r.retries!==void 0&&e.set("Upstash-Retries",r.retries.toFixed(0)),r.callback!==void 0&&e.set("Upstash-Callback",r.callback),r.failureCallback!==void 0&&e.set("Upstash-Failure-Callback",r.failureCallback),r.timeout!==void 0&&e.set("Upstash-Timeout",`${r.timeout}s`),e}function U(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var F=class{http;queueName;constructor(e,t){this.http=e,this.queueName=t}async upsert(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t={queueName:this.queueName,parallelism:e.parallelism??1,paused:e.paused??!1};await this.http.request({method:"POST",path:["v2","queues"],headers:{"Content-Type":"application/json"},body:JSON.stringify(t),parseResponseAsJson:!1})}async get(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");return await this.http.request({method:"GET",path:["v2","queues",this.queueName]})}async list(){return await this.http.request({method:"GET",path:["v2","queues"]})}async delete(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"DELETE",path:["v2","queues",this.queueName],parseResponseAsJson:!1})}async enqueue(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t=x(e),s=U(e);return await this.http.request({path:["v2","enqueue",this.queueName,s],body:e.body,headers:t,method:"POST"})}async enqueueJSON(e){let t=b(new Headers(e.headers));return t.set("Content-Type","application/json"),I(e),C(e,t,this.http),await this.enqueue({...e,body:JSON.stringify(e.body),headers:t})}async pause(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"pause"],parseResponseAsJson:!1})}async resume(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"resume"],parseResponseAsJson:!1})}};var H=class{http;constructor(e){this.http=e}async create(e){let t=b(new Headers(e.headers));return t.has("Content-Type")||t.set("Content-Type","application/json"),t.set("Upstash-Cron",e.cron),e.method!==void 0&&t.set("Upstash-Method",e.method),e.delay!==void 0&&t.set("Upstash-Delay",`${e.delay.toFixed(0)}s`),e.retries!==void 0&&t.set("Upstash-Retries",e.retries.toFixed(0)),e.callback!==void 0&&t.set("Upstash-Callback",e.callback),e.failureCallback!==void 0&&t.set("Upstash-Failure-Callback",e.failureCallback),e.timeout!==void 0&&t.set("Upstash-Timeout",`${e.timeout}s`),e.scheduleId!==void 0&&t.set("Upstash-Schedule-Id",e.scheduleId),await this.http.request({method:"POST",headers:t,path:["v2","schedules",e.destination],body:e.body})}async get(e){return await this.http.request({method:"GET",path:["v2","schedules",e]})}async list(){return await this.http.request({method:"GET",path:["v2","schedules"]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","schedules",e],parseResponseAsJson:!1})}async pause({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"pause"],parseResponseAsJson:!1})}async resume({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"resume"],parseResponseAsJson:!1})}};var B=class{http;constructor(e){this.http=e}async addEndpoints(e){await this.http.request({method:"POST",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async removeEndpoints(e){await this.http.request({method:"DELETE",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async list(){return await this.http.request({method:"GET",path:["v2","topics"]})}async get(e){return await this.http.request({method:"GET",path:["v2","topics",e]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","topics",e],parseResponseAsJson:!1})}};var oe={withStackTrace:!1},Y=(r,e,t=oe)=>{let s=e.isOk()?{type:"Ok",value:e.value}:{type:"Err",value:e.error},n=t.withStackTrace?new Error().stack:void 0;return{data:s,message:r,stack:n}};function k(r,e,t,s){function n(o){return o instanceof t?o:new t(function(i){i(o)})}return new(t||(t=Promise))(function(o,i){function a(u){try{c(s.next(u))}catch(f){i(f)}}function p(u){try{c(s.throw(u))}catch(f){i(f)}}function c(u){u.done?o(u.value):n(u.value).then(a,p)}c((s=s.apply(r,[])).next())})}function V(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function R(r){return this instanceof R?(this.v=r,this):new R(r)}function ie(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(r,e||[]),n,o=[];return n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n;function i(l){s[l]&&(n[l]=function(T){return new Promise(function(G,ee){o.push([l,T,G,ee])>1||a(l,T)})})}function a(l,T){try{p(s[l](T))}catch(G){f(o[0][3],G)}}function p(l){l.value instanceof R?Promise.resolve(l.value.v).then(c,u):f(o[0][2],l)}function c(l){a("next",l)}function u(l){a("throw",l)}function f(l,T){l(T),o.shift(),o.length&&a(o[0][0],o[0][1])}}function ae(r){var e,t;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,o){e[n]=r[n]?function(i){return(t=!t)?{value:R(r[n](i)),done:n==="return"}:o?o(i):i}:o}}function le(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof V=="function"?V(r):r[Symbol.iterator](),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(o){t[o]=r[o]&&function(i){return new Promise(function(a,p){i=r[o](i),n(a,p,i.done,i.value)})}}function n(o,i,a,p){Promise.resolve(p).then(function(c){o({value:c,done:a})},i)}}var g=class r{constructor(e){this._promise=e}static fromSafePromise(e){let t=e.then(s=>new m(s));return new r(t)}static fromPromise(e,t){let s=e.then(n=>new m(n)).catch(n=>new d(t(n)));return new r(s)}static fromThrowable(e,t){return(...s)=>new r(k(this,void 0,void 0,function*(){try{return new m(yield e(...s))}catch(n){return new d(t?t(n):n)}}))}static combine(e){return ue(e)}static combineWithAllErrors(e){return pe(e)}map(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){return t.isErr()?new d(t.error):new m(yield e(t.value))})))}andThrough(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){if(t.isErr())return new d(t.error);let s=yield e(t.value);return s.isErr()?new d(s.error):new m(t.value)})))}andTee(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){if(t.isErr())return new d(t.error);try{yield e(t.value)}catch{}return new m(t.value)})))}mapErr(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){return t.isOk()?new m(t.value):new d(yield e(t.error))})))}andThen(e){return new r(this._promise.then(t=>{if(t.isErr())return new d(t.error);let s=e(t.value);return s instanceof r?s._promise:s}))}orElse(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){return t.isErr()?e(t.error):new m(t.value)})))}match(e,t){return this._promise.then(s=>s.match(e,t))}unwrapOr(e){return this._promise.then(t=>t.unwrapOr(e))}safeUnwrap(){return ie(this,arguments,function*(){return yield R(yield R(yield*ae(le(yield R(this._promise.then(t=>t.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}};var J=r=>new g(Promise.resolve(new d(r))),Be=g.fromPromise,De=g.fromSafePromise,Me=g.fromThrowable,X=r=>{let e=y([]);for(let t of r)if(t.isErr()){e=h(t.error);break}else e.map(s=>s.push(t.value));return e},ue=r=>g.fromSafePromise(Promise.all(r)).andThen(X),Z=r=>{let e=y([]);for(let t of r)t.isErr()&&e.isErr()?e.error.push(t.error):t.isErr()&&e.isOk()?e=h([t.error]):t.isOk()&&e.isOk()&&e.value.push(t.value);return e},pe=r=>g.fromSafePromise(Promise.all(r)).andThen(Z),Q;(function(r){function e(n,o){return(...i)=>{try{let a=n(...i);return y(a)}catch(a){return h(o?o(a):a)}}}r.fromThrowable=e;function t(n){return X(n)}r.combine=t;function s(n){return Z(n)}r.combineWithAllErrors=s})(Q||(Q={}));var y=r=>new m(r);function h(r){return new d(r)}var m=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return y(e(this.value))}mapErr(e){return y(this.value)}andThen(e){return e(this.value)}andThrough(e){return e(this.value).map(t=>this.value)}andTee(e){try{e(this.value)}catch{}return y(this.value)}orElse(e){return y(this.value)}asyncAndThen(e){return e(this.value)}asyncAndThrough(e){return e(this.value).map(()=>this.value)}asyncMap(e){return g.fromSafePromise(e(this.value))}unwrapOr(e){return this.value}match(e,t){return e(this.value)}safeUnwrap(){let e=this.value;return function*(){return e}()}_unsafeUnwrap(e){return this.value}_unsafeUnwrapErr(e){throw Y("Called `_unsafeUnwrapErr` on an Ok",this,e)}},d=class{constructor(e){this.error=e}isOk(){return!1}isErr(){return!this.isOk()}map(e){return h(this.error)}mapErr(e){return h(e(this.error))}andThrough(e){return h(this.error)}andTee(e){return h(this.error)}andThen(e){return h(this.error)}orElse(e){return e(this.error)}asyncAndThen(e){return J(this.error)}asyncAndThrough(e){return J(this.error)}asyncMap(e){return J(this.error)}unwrapOr(e){return e}match(e,t){return t(this.error)}safeUnwrap(){let e=this.error;return function*(){throw yield h(e),new Error("Do not use this generator out of `safeTry`")}()}_unsafeUnwrap(e){throw Y("Called `_unsafeUnwrap` on an Err",this,e)}_unsafeUnwrapErr(e){return this.error}},Ge=Q.fromThrowable;var M=class{http;constructor(e){this.http=e}async cancel(e){return await this.http.request({path:["v2","workflows","runs",`${e}?cancel=true`],method:"DELETE",parseResponseAsJson:!1})??!0}};var D=class{http;token;constructor(e){this.http=new W({retry:e.retry,baseUrl:e.baseUrl?e.baseUrl.replace(/\/$/,""):"https://qstash.upstash.io",authorization:`Bearer ${e.token}`}),this.token=e.token}get urlGroups(){return new B(this.http)}get topics(){return this.urlGroups}get dlq(){return new O(this.http)}get messages(){return new _(this.http)}get schedules(){return new H(this.http)}get workflow(){return new M(this.http)}queue(e){return new F(this.http,e?.queueName)}chat(){return new A(this.http,this.token)}async publish(e){let t=x(e);return await this.http.request({path:["v2","publish",U(e)],body:e.body,headers:t,method:"POST"})}async publishJSON(e){let t=b(new Headers(e.headers));return t.set("Content-Type","application/json"),I(e),C(e,t,this.http),await this.publish({...e,headers:t,body:JSON.stringify(e.body)})}async batch(e){let t=[];for(let o of e){let i=x(o),a=Object.fromEntries(i.entries());t.push({destination:U(o),headers:a,body:o.body,...o.queueName&&{queue:o.queueName}})}let s=await this.http.request({path:["v2","batch"],body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST"});return Array.isArray(s)?s:[s]}async batchJSON(e){for(let s of e)"body"in s&&(s.body=JSON.stringify(s.body)),s.headers=new Headers(s.headers),I(s),C(s,s.headers,this.http),s.headers.set("Content-Type","application/json");return await this.batch(e)}async events(e){let t={};e?.cursor&&e.cursor>0&&(t.cursor=e.cursor.toString());for(let[n,o]of Object.entries(e?.filter??{}))typeof o=="number"&&o<0||(n==="urlGroup"?t.topicName=o.toString():typeof o<"u"&&(t[n]=o.toString()));let s=await this.http.request({path:["v2","events"],method:"GET",query:t});return{cursor:s.cursor,events:s.events.map(n=>({...n,urlGroup:n.topicName}))}}};export{A as Chat,D as Client,_ as Messages,E as QStashWorkflowAbort,v as QStashWorkflowError,L as QstashChatRatelimitError,q as QstashDailyRatelimitError,w as QstashError,N as QstashRatelimitError,$ as Receiver,H as Schedules,P as SignatureError,B as UrlGroups,Ee as custom,te as formatWorkflowError,ve as openai,S as setupAnalytics,Pe as upstash};
2
+ `).filter(Boolean);for(let u of c)if(u.startsWith("data: ")){let f=u.slice(6);if(f==="[DONE]")break;yield JSON.parse(f)}}}finally{await n.cancel()}}requestWithBackoff=async e=>{let[t,s]=this.processRequest(e),n,o;for(let i=0;i<this.retry.attempts;i++)try{n=await fetch(t.toString(),s);break}catch(a){o=a,await new Promise(p=>setTimeout(p,this.retry.backoff(i)))}if(!n)throw o??new Error("Exhausted all retries");return await this.checkResponse(n),{response:n,error:o}};processRequest=e=>{let t=new Headers(e.headers);t.has("Authorization")||t.set("Authorization",this.authorization);let s={method:e.method,headers:t,body:e.body,keepalive:e.keepalive},n=new URL([e.baseUrl??this.baseUrl,...e.path].join("/"));if(e.query)for(let[o,i]of Object.entries(e.query))i!==void 0&&n.searchParams.set(o,i.toString());return[n.toString(),s]};async checkResponse(e){if(e.status===429)throw e.headers.get("x-ratelimit-limit-requests")?new L({"limit-requests":e.headers.get("x-ratelimit-limit-requests"),"limit-tokens":e.headers.get("x-ratelimit-limit-tokens"),"remaining-requests":e.headers.get("x-ratelimit-remaining-requests"),"remaining-tokens":e.headers.get("x-ratelimit-remaining-tokens"),"reset-requests":e.headers.get("x-ratelimit-reset-requests"),"reset-tokens":e.headers.get("x-ratelimit-reset-tokens")}):e.headers.get("RateLimit-Limit")?new q({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new N({limit:e.headers.get("Burst-RateLimit-Limit"),remaining:e.headers.get("Burst-RateLimit-Remaining"),reset:e.headers.get("Burst-RateLimit-Reset")});if(e.status<200||e.status>=300){let t=await e.text();throw new w(t.length>0?t:`Error: status=${e.status}`)}}};var S=(r,e,t,s)=>{if(!r)return{};switch(r.name){case"helicone":switch(s){case"upstash":return{baseURL:"https://qstash.helicone.ai/llm/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,Authorization:`Bearer ${e}`}};default:return{baseURL:"https://gateway.helicone.ai/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,"Helicone-Target-Url":t,Authorization:`Bearer ${e}`}}}default:throw new Error("Unknown analytics provider")}},Pe=()=>({owner:"upstash",baseUrl:"https://qstash.upstash.io/llm",token:""}),ve=({token:r})=>({token:r,owner:"openai",baseUrl:"https://api.openai.com"}),Ee=({baseUrl:r,token:e})=>{let t=r.replace(/\/(v1\/)?chat\/completions$/,"");return{token:e,owner:"custom",baseUrl:t}};var A=class r{http;token;constructor(e,t){this.http=e,this.token=t}static toChatRequest(e){let t=[];return t.push({role:"system",content:e.system},{role:"user",content:e.user}),{...e,messages:t}}create=async e=>{if(e.provider.owner!="upstash")return this.createThirdParty(e);let t=JSON.stringify(e),s,n={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,..."stream"in e&&e.stream?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{}};if(e.analytics){let{baseURL:i,defaultHeaders:a}=S({name:"helicone",token:e.analytics.token},this.getAuthorizationToken(),e.provider.baseUrl,"upstash");n={...n,...a},s=i}let o=e.analytics?[]:["llm","v1","chat","completions"];return"stream"in e&&e.stream?this.http.requestStream({path:o,method:"POST",headers:n,baseUrl:s,body:t}):this.http.request({path:o,method:"POST",headers:n,baseUrl:s,body:t})};createThirdParty=async e=>{let{baseUrl:t,token:s,owner:n}=e.provider;if(n==="upstash")throw new Error("Upstash is not 3rd party provider!");delete e.provider,delete e.system;let o=e.analytics;delete e.analytics;let i=JSON.stringify(e),a=o?.name&&o.token,p=o?.name&&o.token?S({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},c="stream"in e&&e.stream,u={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...c?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...p.defaultHeaders};return await this.http[c?"requestStream":"request"]({path:a?[]:["v1","chat","completions"],method:"POST",headers:u,body:i,baseUrl:p.baseURL})};getAuthorizationToken(){let t=String(this.http.authorization).match(/Bearer (.+)/);if(!t)throw new Error("Invalid authorization header format");return t[1]}prompt=async e=>{let t=r.toChatRequest(e);return this.create(t)}};function C(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){re(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=se(s),a=n?S({name:n.name,token:n.token},i,o,"custom"):void 0;a?(z(e,a),r.url=a.baseURL):(r.url=`${o}/v1/chat/completions`,e.set("Authorization",`Bearer ${i}`))}function re(r,e,t,s){if(s){let n=S({name:s.name,token:s.token},String(t.authorization).split("Bearer ")[1],r.api?.provider?.baseUrl,"upstash");z(e,n),r.url=n.baseURL}else r.api={name:"llm"}}function se(r){if(!r?.baseUrl)throw new Error("baseUrl cannot be empty or undefined!");if(!r.token)throw new Error("token cannot be empty or undefined!");return{baseUrl:r.baseUrl,token:r.token}}function z(r,e){r.set("Helicone-Auth",e.defaultHeaders?.["Helicone-Auth"]??""),r.set("Authorization",e.defaultHeaders?.Authorization??""),e.defaultHeaders?.["Helicone-Target-Url"]&&r.set("Helicone-Target-Url",e.defaultHeaders["Helicone-Target-Url"])}function I(r){if(r.api?.name==="llm"&&!r.callback)throw new TypeError("Callback cannot be undefined when using LLM")}var _=class{http;constructor(e){this.http=e}async get(e){let t=await this.http.request({method:"GET",path:["v2","messages",e]});return{...t,urlGroup:t.topicName}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","messages",e],parseResponseAsJson:!1})}async deleteMany(e){return(await this.http.request({method:"DELETE",path:["v2","messages"],headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:e})})).cancelled}async deleteAll(){return(await this.http.request({method:"DELETE",path:["v2","messages"]})).cancelled}};var ne=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function b(r){let e=[...r.keys()].filter(t=>!ne(t));for(let t of e){let s=r.get(t);s!==null&&r.set(`Upstash-Forward-${t}`,s),r.delete(t)}return r}function x(r){let e=b(new Headers(r.headers));return e.set("Upstash-Method",r.method??"POST"),r.delay!==void 0&&(typeof r.delay=="string"?e.set("Upstash-Delay",r.delay):e.set("Upstash-Delay",`${r.delay.toFixed(0)}s`)),r.notBefore!==void 0&&e.set("Upstash-Not-Before",r.notBefore.toFixed(0)),r.deduplicationId!==void 0&&e.set("Upstash-Deduplication-Id",r.deduplicationId),r.contentBasedDeduplication!==void 0&&e.set("Upstash-Content-Based-Deduplication","true"),r.retries!==void 0&&e.set("Upstash-Retries",r.retries.toFixed(0)),r.callback!==void 0&&e.set("Upstash-Callback",r.callback),r.failureCallback!==void 0&&e.set("Upstash-Failure-Callback",r.failureCallback),r.timeout!==void 0&&(typeof r.timeout=="string"?e.set("Upstash-Timeout",r.timeout):e.set("Upstash-Timeout",`${r.timeout}s`)),e}function U(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var F=class{http;queueName;constructor(e,t){this.http=e,this.queueName=t}async upsert(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t={queueName:this.queueName,parallelism:e.parallelism??1,paused:e.paused??!1};await this.http.request({method:"POST",path:["v2","queues"],headers:{"Content-Type":"application/json"},body:JSON.stringify(t),parseResponseAsJson:!1})}async get(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");return await this.http.request({method:"GET",path:["v2","queues",this.queueName]})}async list(){return await this.http.request({method:"GET",path:["v2","queues"]})}async delete(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"DELETE",path:["v2","queues",this.queueName],parseResponseAsJson:!1})}async enqueue(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t=x(e),s=U(e);return await this.http.request({path:["v2","enqueue",this.queueName,s],body:e.body,headers:t,method:"POST"})}async enqueueJSON(e){let t=b(new Headers(e.headers));return t.set("Content-Type","application/json"),I(e),C(e,t,this.http),await this.enqueue({...e,body:JSON.stringify(e.body),headers:t})}async pause(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"pause"],parseResponseAsJson:!1})}async resume(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"resume"],parseResponseAsJson:!1})}};var H=class{http;constructor(e){this.http=e}async create(e){let t=b(new Headers(e.headers));return t.has("Content-Type")||t.set("Content-Type","application/json"),t.set("Upstash-Cron",e.cron),e.method!==void 0&&t.set("Upstash-Method",e.method),e.delay!==void 0&&(typeof e.delay=="string"?t.set("Upstash-Delay",e.delay):t.set("Upstash-Delay",`${e.delay.toFixed(0)}s`)),e.retries!==void 0&&t.set("Upstash-Retries",e.retries.toFixed(0)),e.callback!==void 0&&t.set("Upstash-Callback",e.callback),e.failureCallback!==void 0&&t.set("Upstash-Failure-Callback",e.failureCallback),e.timeout!==void 0&&(typeof e.timeout=="string"?t.set("Upstash-Timeout",e.timeout):t.set("Upstash-Timeout",`${e.timeout}s`)),e.scheduleId!==void 0&&t.set("Upstash-Schedule-Id",e.scheduleId),await this.http.request({method:"POST",headers:t,path:["v2","schedules",e.destination],body:e.body})}async get(e){return await this.http.request({method:"GET",path:["v2","schedules",e]})}async list(){return await this.http.request({method:"GET",path:["v2","schedules"]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","schedules",e],parseResponseAsJson:!1})}async pause({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"pause"],parseResponseAsJson:!1})}async resume({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"resume"],parseResponseAsJson:!1})}};var B=class{http;constructor(e){this.http=e}async addEndpoints(e){await this.http.request({method:"POST",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async removeEndpoints(e){await this.http.request({method:"DELETE",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async list(){return await this.http.request({method:"GET",path:["v2","topics"]})}async get(e){return await this.http.request({method:"GET",path:["v2","topics",e]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","topics",e],parseResponseAsJson:!1})}};var oe={withStackTrace:!1},Y=(r,e,t=oe)=>{let s=e.isOk()?{type:"Ok",value:e.value}:{type:"Err",value:e.error},n=t.withStackTrace?new Error().stack:void 0;return{data:s,message:r,stack:n}};function k(r,e,t,s){function n(o){return o instanceof t?o:new t(function(i){i(o)})}return new(t||(t=Promise))(function(o,i){function a(u){try{c(s.next(u))}catch(f){i(f)}}function p(u){try{c(s.throw(u))}catch(f){i(f)}}function c(u){u.done?o(u.value):n(u.value).then(a,p)}c((s=s.apply(r,[])).next())})}function V(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function R(r){return this instanceof R?(this.v=r,this):new R(r)}function ie(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(r,e||[]),n,o=[];return n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n;function i(l){s[l]&&(n[l]=function(T){return new Promise(function(G,ee){o.push([l,T,G,ee])>1||a(l,T)})})}function a(l,T){try{p(s[l](T))}catch(G){f(o[0][3],G)}}function p(l){l.value instanceof R?Promise.resolve(l.value.v).then(c,u):f(o[0][2],l)}function c(l){a("next",l)}function u(l){a("throw",l)}function f(l,T){l(T),o.shift(),o.length&&a(o[0][0],o[0][1])}}function ae(r){var e,t;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,o){e[n]=r[n]?function(i){return(t=!t)?{value:R(r[n](i)),done:n==="return"}:o?o(i):i}:o}}function le(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof V=="function"?V(r):r[Symbol.iterator](),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(o){t[o]=r[o]&&function(i){return new Promise(function(a,p){i=r[o](i),n(a,p,i.done,i.value)})}}function n(o,i,a,p){Promise.resolve(p).then(function(c){o({value:c,done:a})},i)}}var g=class r{constructor(e){this._promise=e}static fromSafePromise(e){let t=e.then(s=>new m(s));return new r(t)}static fromPromise(e,t){let s=e.then(n=>new m(n)).catch(n=>new d(t(n)));return new r(s)}static fromThrowable(e,t){return(...s)=>new r(k(this,void 0,void 0,function*(){try{return new m(yield e(...s))}catch(n){return new d(t?t(n):n)}}))}static combine(e){return ue(e)}static combineWithAllErrors(e){return pe(e)}map(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){return t.isErr()?new d(t.error):new m(yield e(t.value))})))}andThrough(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){if(t.isErr())return new d(t.error);let s=yield e(t.value);return s.isErr()?new d(s.error):new m(t.value)})))}andTee(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){if(t.isErr())return new d(t.error);try{yield e(t.value)}catch{}return new m(t.value)})))}mapErr(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){return t.isOk()?new m(t.value):new d(yield e(t.error))})))}andThen(e){return new r(this._promise.then(t=>{if(t.isErr())return new d(t.error);let s=e(t.value);return s instanceof r?s._promise:s}))}orElse(e){return new r(this._promise.then(t=>k(this,void 0,void 0,function*(){return t.isErr()?e(t.error):new m(t.value)})))}match(e,t){return this._promise.then(s=>s.match(e,t))}unwrapOr(e){return this._promise.then(t=>t.unwrapOr(e))}safeUnwrap(){return ie(this,arguments,function*(){return yield R(yield R(yield*ae(le(yield R(this._promise.then(t=>t.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}};var J=r=>new g(Promise.resolve(new d(r))),Be=g.fromPromise,De=g.fromSafePromise,Me=g.fromThrowable,X=r=>{let e=y([]);for(let t of r)if(t.isErr()){e=h(t.error);break}else e.map(s=>s.push(t.value));return e},ue=r=>g.fromSafePromise(Promise.all(r)).andThen(X),Z=r=>{let e=y([]);for(let t of r)t.isErr()&&e.isErr()?e.error.push(t.error):t.isErr()&&e.isOk()?e=h([t.error]):t.isOk()&&e.isOk()&&e.value.push(t.value);return e},pe=r=>g.fromSafePromise(Promise.all(r)).andThen(Z),Q;(function(r){function e(n,o){return(...i)=>{try{let a=n(...i);return y(a)}catch(a){return h(o?o(a):a)}}}r.fromThrowable=e;function t(n){return X(n)}r.combine=t;function s(n){return Z(n)}r.combineWithAllErrors=s})(Q||(Q={}));var y=r=>new m(r);function h(r){return new d(r)}var m=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return y(e(this.value))}mapErr(e){return y(this.value)}andThen(e){return e(this.value)}andThrough(e){return e(this.value).map(t=>this.value)}andTee(e){try{e(this.value)}catch{}return y(this.value)}orElse(e){return y(this.value)}asyncAndThen(e){return e(this.value)}asyncAndThrough(e){return e(this.value).map(()=>this.value)}asyncMap(e){return g.fromSafePromise(e(this.value))}unwrapOr(e){return this.value}match(e,t){return e(this.value)}safeUnwrap(){let e=this.value;return function*(){return e}()}_unsafeUnwrap(e){return this.value}_unsafeUnwrapErr(e){throw Y("Called `_unsafeUnwrapErr` on an Ok",this,e)}},d=class{constructor(e){this.error=e}isOk(){return!1}isErr(){return!this.isOk()}map(e){return h(this.error)}mapErr(e){return h(e(this.error))}andThrough(e){return h(this.error)}andTee(e){return h(this.error)}andThen(e){return h(this.error)}orElse(e){return e(this.error)}asyncAndThen(e){return J(this.error)}asyncAndThrough(e){return J(this.error)}asyncMap(e){return J(this.error)}unwrapOr(e){return e}match(e,t){return t(this.error)}safeUnwrap(){let e=this.error;return function*(){throw yield h(e),new Error("Do not use this generator out of `safeTry`")}()}_unsafeUnwrap(e){throw Y("Called `_unsafeUnwrap` on an Err",this,e)}_unsafeUnwrapErr(e){return this.error}},Ge=Q.fromThrowable;var M=class{http;constructor(e){this.http=e}async cancel(e){return await this.http.request({path:["v2","workflows","runs",`${e}?cancel=true`],method:"DELETE",parseResponseAsJson:!1})??!0}};var D=class{http;token;constructor(e){this.http=new W({retry:e.retry,baseUrl:e.baseUrl?e.baseUrl.replace(/\/$/,""):"https://qstash.upstash.io",authorization:`Bearer ${e.token}`}),this.token=e.token}get urlGroups(){return new B(this.http)}get topics(){return this.urlGroups}get dlq(){return new O(this.http)}get messages(){return new _(this.http)}get schedules(){return new H(this.http)}get workflow(){return new M(this.http)}queue(e){return new F(this.http,e?.queueName)}chat(){return new A(this.http,this.token)}async publish(e){let t=x(e);return await this.http.request({path:["v2","publish",U(e)],body:e.body,headers:t,method:"POST"})}async publishJSON(e){let t=b(new Headers(e.headers));return t.set("Content-Type","application/json"),I(e),C(e,t,this.http),await this.publish({...e,headers:t,body:JSON.stringify(e.body)})}async batch(e){let t=[];for(let o of e){let i=x(o),a=Object.fromEntries(i.entries());t.push({destination:U(o),headers:a,body:o.body,...o.queueName&&{queue:o.queueName}})}let s=await this.http.request({path:["v2","batch"],body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST"});return Array.isArray(s)?s:[s]}async batchJSON(e){for(let s of e)"body"in s&&(s.body=JSON.stringify(s.body)),s.headers=new Headers(s.headers),I(s),C(s,s.headers,this.http),s.headers.set("Content-Type","application/json");return await this.batch(e)}async events(e){let t={};e?.cursor&&e.cursor>0&&(t.cursor=e.cursor.toString());for(let[n,o]of Object.entries(e?.filter??{}))typeof o=="number"&&o<0||(n==="urlGroup"?t.topicName=o.toString():typeof o<"u"&&(t[n]=o.toString()));let s=await this.http.request({path:["v2","events"],method:"GET",query:t});return{cursor:s.cursor,events:s.events.map(n=>({...n,urlGroup:n.topicName}))}}};export{A as Chat,D as Client,_ as Messages,E as QStashWorkflowAbort,v as QStashWorkflowError,L as QstashChatRatelimitError,q as QstashDailyRatelimitError,w as QstashError,N as QstashRatelimitError,$ as Receiver,H as Schedules,P as SignatureError,B as UrlGroups,Ee as custom,te as formatWorkflowError,ve as openai,S as setupAnalytics,Pe as upstash};
@@ -432,6 +432,9 @@ declare class DLQ {
432
432
  }>;
433
433
  }
434
434
 
435
+ type Unit = "s" | "m" | "h" | "d";
436
+ type Duration = `${bigint}${Unit}`;
437
+
435
438
  declare class Chat {
436
439
  private http;
437
440
  private token;
@@ -580,7 +583,7 @@ type CreateScheduleRequest = {
580
583
  *
581
584
  * @default undefined
582
585
  */
583
- delay?: number;
586
+ delay?: Duration | number;
584
587
  /**
585
588
  * In case your destination server is unavailable or returns a status code outside of the 200-299
586
589
  * range, we will retry the request after a certain amount of time.
@@ -626,7 +629,7 @@ type CreateScheduleRequest = {
626
629
  *
627
630
  * @default undefined
628
631
  */
629
- timeout?: number;
632
+ timeout?: Duration | number;
630
633
  /**
631
634
  * Schedule id to use.
632
635
  *
@@ -794,7 +797,7 @@ type PublishRequest<TBody = BodyInit> = {
794
797
  *
795
798
  * @default undefined
796
799
  */
797
- delay?: number;
800
+ delay?: Duration | number;
798
801
  /**
799
802
  * Optionally set the absolute delay of this message.
800
803
  * This will override the delay option.
@@ -867,7 +870,7 @@ type PublishRequest<TBody = BodyInit> = {
867
870
  *
868
871
  * @default undefined
869
872
  */
870
- timeout?: number;
873
+ timeout?: Duration | number;
871
874
  } & ({
872
875
  /**
873
876
  * The url where the message should be sent to.
@@ -1,5 +1,5 @@
1
- import*as Pe from"jose";import ke from"crypto-js";var L=class extends Error{constructor(e){super(e),this.name="SignatureError"}},J=class{currentSigningKey;nextSigningKey;constructor(e){this.currentSigningKey=e.currentSigningKey,this.nextSigningKey=e.nextSigningKey}async verify(e){return await this.verifyWithKey(this.currentSigningKey,e)?!0:this.verifyWithKey(this.nextSigningKey,e)}async verifyWithKey(e,t){let n=(await Pe.jwtVerify(t.signature,new TextEncoder().encode(e),{issuer:"Upstash",clockTolerance:t.clockTolerance}).catch(a=>{throw new L(a.message)})).payload;if(t.url!==void 0&&n.sub!==t.url)throw new L(`invalid subject: ${n.sub}, want: ${t.url}`);let o=ke.SHA256(t.body).toString(ke.enc.Base64url),i=new RegExp(/=+$/);if(n.body.replace(i,"")!==o.replace(i,""))throw new L(`body hash does not match, want: ${n.body}, got: ${o}`);return!0}};var Q=class{http;constructor(e){this.http=e}async listMessages(e){let t={...e?.filter,topicName:e?.filter?.urlGroup},s=await this.http.request({method:"GET",path:["v2","dlq"],query:{cursor:e?.cursor,count:e?.count,...t}});return{messages:s.messages.map(n=>({...n,urlGroup:n.topicName})),cursor:s.cursor}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","dlq",e],parseResponseAsJson:!1})}async deleteMany(e){return await this.http.request({method:"DELETE",path:["v2","dlq"],headers:{"Content-Type":"application/json"},body:JSON.stringify({dlqIds:e.dlqIds})})}};var P=class extends Error{constructor(e){super(e),this.name="QstashError"}},K=class extends P{limit;remaining;reset;constructor(e){super(`Exceeded burst rate limit. ${JSON.stringify(e)} `),this.name="QstashRatelimitError",this.limit=e.limit,this.remaining=e.remaining,this.reset=e.reset}},j=class extends P{limitRequests;limitTokens;remainingRequests;remainingTokens;resetRequests;resetTokens;constructor(e){super(`Exceeded chat rate limit. ${JSON.stringify(e)} `),this.limitRequests=e["limit-requests"],this.limitTokens=e["limit-tokens"],this.remainingRequests=e["remaining-requests"],this.remainingTokens=e["remaining-tokens"],this.resetRequests=e["reset-requests"],this.resetTokens=e["reset-tokens"]}},z=class extends P{limit;remaining;reset;constructor(e){super(`Exceeded daily rate limit. ${JSON.stringify(e)} `),this.limit=e.limit,this.remaining=e.remaining,this.reset=e.reset,this.name="QstashChatRatelimitError"}},d=class extends P{constructor(e){super(e),this.name="QStashWorkflowError"}},R=class extends Error{stepInfo;stepName;constructor(e,t){super(`This is an QStash Workflow error thrown after a step executes. It is expected to be raised. Make sure that you await for each step. Also, if you are using try/catch blocks, you should not wrap context.run/sleep/sleepUntil/call methods with try/catch. Aborting workflow after executing step '${e}'.`),this.name="QStashWorkflowAbort",this.stepName=e,this.stepInfo=t}},ve=r=>r instanceof Error?{error:r.name,message:r.message}:{error:"Error",message:"An error occured while executing workflow."};var V=class{baseUrl;authorization;options;retry;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.authorization=e.authorization,this.retry=typeof e.retry=="boolean"&&!e.retry?{attempts:1,backoff:()=>0}:{attempts:e.retry?.retries?e.retry.retries+1:5,backoff:e.retry?.backoff??(t=>Math.exp(t)*50)}}async request(e){let{response:t}=await this.requestWithBackoff(e);if(e.parseResponseAsJson!==!1)return await t.json()}async*requestStream(e){let{response:t}=await this.requestWithBackoff(e);if(!t.body)throw new Error("No response body");let n=t.body.getReader(),o=new TextDecoder;try{for(;;){let{done:i,value:a}=await n.read();if(i)break;let p=o.decode(a,{stream:!0}).split(`
2
- `).filter(Boolean);for(let c of p)if(c.startsWith("data: ")){let m=c.slice(6);if(m==="[DONE]")break;yield JSON.parse(m)}}}finally{await n.cancel()}}requestWithBackoff=async e=>{let[t,s]=this.processRequest(e),n,o;for(let i=0;i<this.retry.attempts;i++)try{n=await fetch(t.toString(),s);break}catch(a){o=a,await new Promise(l=>setTimeout(l,this.retry.backoff(i)))}if(!n)throw o??new Error("Exhausted all retries");return await this.checkResponse(n),{response:n,error:o}};processRequest=e=>{let t=new Headers(e.headers);t.has("Authorization")||t.set("Authorization",this.authorization);let s={method:e.method,headers:t,body:e.body,keepalive:e.keepalive},n=new URL([e.baseUrl??this.baseUrl,...e.path].join("/"));if(e.query)for(let[o,i]of Object.entries(e.query))i!==void 0&&n.searchParams.set(o,i.toString());return[n.toString(),s]};async checkResponse(e){if(e.status===429)throw e.headers.get("x-ratelimit-limit-requests")?new j({"limit-requests":e.headers.get("x-ratelimit-limit-requests"),"limit-tokens":e.headers.get("x-ratelimit-limit-tokens"),"remaining-requests":e.headers.get("x-ratelimit-remaining-requests"),"remaining-tokens":e.headers.get("x-ratelimit-remaining-tokens"),"reset-requests":e.headers.get("x-ratelimit-reset-requests"),"reset-tokens":e.headers.get("x-ratelimit-reset-tokens")}):e.headers.get("RateLimit-Limit")?new z({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new K({limit:e.headers.get("Burst-RateLimit-Limit"),remaining:e.headers.get("Burst-RateLimit-Remaining"),reset:e.headers.get("Burst-RateLimit-Reset")});if(e.status<200||e.status>=300){let t=await e.text();throw new P(t.length>0?t:`Error: status=${e.status}`)}}};var I=(r,e,t,s)=>{if(!r)return{};switch(r.name){case"helicone":switch(s){case"upstash":return{baseURL:"https://qstash.helicone.ai/llm/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,Authorization:`Bearer ${e}`}};default:return{baseURL:"https://gateway.helicone.ai/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,"Helicone-Target-Url":t,Authorization:`Bearer ${e}`}}}default:throw new Error("Unknown analytics provider")}};var Y=class r{http;token;constructor(e,t){this.http=e,this.token=t}static toChatRequest(e){let t=[];return t.push({role:"system",content:e.system},{role:"user",content:e.user}),{...e,messages:t}}create=async e=>{if(e.provider.owner!="upstash")return this.createThirdParty(e);let t=JSON.stringify(e),s,n={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,..."stream"in e&&e.stream?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{}};if(e.analytics){let{baseURL:i,defaultHeaders:a}=I({name:"helicone",token:e.analytics.token},this.getAuthorizationToken(),e.provider.baseUrl,"upstash");n={...n,...a},s=i}let o=e.analytics?[]:["llm","v1","chat","completions"];return"stream"in e&&e.stream?this.http.requestStream({path:o,method:"POST",headers:n,baseUrl:s,body:t}):this.http.request({path:o,method:"POST",headers:n,baseUrl:s,body:t})};createThirdParty=async e=>{let{baseUrl:t,token:s,owner:n}=e.provider;if(n==="upstash")throw new Error("Upstash is not 3rd party provider!");delete e.provider,delete e.system;let o=e.analytics;delete e.analytics;let i=JSON.stringify(e),a=o?.name&&o.token,l=o?.name&&o.token?I({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},p="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...p?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[p?"requestStream":"request"]({path:a?[]:["v1","chat","completions"],method:"POST",headers:c,body:i,baseUrl:l.baseURL})};getAuthorizationToken(){let t=String(this.http.authorization).match(/Bearer (.+)/);if(!t)throw new Error("Invalid authorization header format");return t[1]}prompt=async e=>{let t=r.toChatRequest(e);return this.create(t)}};function A(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){Ve(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ye(s),a=n?I({name:n.name,token:n.token},i,o,"custom"):void 0;a?(Ee(e,a),r.url=a.baseURL):(r.url=`${o}/v1/chat/completions`,e.set("Authorization",`Bearer ${i}`))}function Ve(r,e,t,s){if(s){let n=I({name:s.name,token:s.token},String(t.authorization).split("Bearer ")[1],r.api?.provider?.baseUrl,"upstash");Ee(e,n),r.url=n.baseURL}else r.api={name:"llm"}}function Ye(r){if(!r?.baseUrl)throw new Error("baseUrl cannot be empty or undefined!");if(!r.token)throw new Error("token cannot be empty or undefined!");return{baseUrl:r.baseUrl,token:r.token}}function Ee(r,e){r.set("Helicone-Auth",e.defaultHeaders?.["Helicone-Auth"]??""),r.set("Authorization",e.defaultHeaders?.Authorization??""),e.defaultHeaders?.["Helicone-Target-Url"]&&r.set("Helicone-Target-Url",e.defaultHeaders["Helicone-Target-Url"])}function W(r){if(r.api?.name==="llm"&&!r.callback)throw new TypeError("Callback cannot be undefined when using LLM")}var X=class{http;constructor(e){this.http=e}async get(e){let t=await this.http.request({method:"GET",path:["v2","messages",e]});return{...t,urlGroup:t.topicName}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","messages",e],parseResponseAsJson:!1})}async deleteMany(e){return(await this.http.request({method:"DELETE",path:["v2","messages"],headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:e})})).cancelled}async deleteAll(){return(await this.http.request({method:"DELETE",path:["v2","messages"]})).cancelled}};var Xe=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function v(r){let e=[...r.keys()].filter(t=>!Xe(t));for(let t of e){let s=r.get(t);s!==null&&r.set(`Upstash-Forward-${t}`,s),r.delete(t)}return r}function _(r){let e=v(new Headers(r.headers));return e.set("Upstash-Method",r.method??"POST"),r.delay!==void 0&&e.set("Upstash-Delay",`${r.delay.toFixed(0)}s`),r.notBefore!==void 0&&e.set("Upstash-Not-Before",r.notBefore.toFixed(0)),r.deduplicationId!==void 0&&e.set("Upstash-Deduplication-Id",r.deduplicationId),r.contentBasedDeduplication!==void 0&&e.set("Upstash-Content-Based-Deduplication","true"),r.retries!==void 0&&e.set("Upstash-Retries",r.retries.toFixed(0)),r.callback!==void 0&&e.set("Upstash-Callback",r.callback),r.failureCallback!==void 0&&e.set("Upstash-Failure-Callback",r.failureCallback),r.timeout!==void 0&&e.set("Upstash-Timeout",`${r.timeout}s`),e}function H(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",Ze=21;function Ie(){return[...crypto.getRandomValues(new Uint8Array(Ze))].map(r=>Ce[r%Ce.length]).join("")}var Z=class{http;queueName;constructor(e,t){this.http=e,this.queueName=t}async upsert(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t={queueName:this.queueName,parallelism:e.parallelism??1,paused:e.paused??!1};await this.http.request({method:"POST",path:["v2","queues"],headers:{"Content-Type":"application/json"},body:JSON.stringify(t),parseResponseAsJson:!1})}async get(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");return await this.http.request({method:"GET",path:["v2","queues",this.queueName]})}async list(){return await this.http.request({method:"GET",path:["v2","queues"]})}async delete(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"DELETE",path:["v2","queues",this.queueName],parseResponseAsJson:!1})}async enqueue(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t=_(e),s=H(e);return await this.http.request({path:["v2","enqueue",this.queueName,s],body:e.body,headers:t,method:"POST"})}async enqueueJSON(e){let t=v(new Headers(e.headers));return t.set("Content-Type","application/json"),W(e),A(e,t,this.http),await this.enqueue({...e,body:JSON.stringify(e.body),headers:t})}async pause(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"pause"],parseResponseAsJson:!1})}async resume(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"resume"],parseResponseAsJson:!1})}};var ee=class{http;constructor(e){this.http=e}async create(e){let t=v(new Headers(e.headers));return t.has("Content-Type")||t.set("Content-Type","application/json"),t.set("Upstash-Cron",e.cron),e.method!==void 0&&t.set("Upstash-Method",e.method),e.delay!==void 0&&t.set("Upstash-Delay",`${e.delay.toFixed(0)}s`),e.retries!==void 0&&t.set("Upstash-Retries",e.retries.toFixed(0)),e.callback!==void 0&&t.set("Upstash-Callback",e.callback),e.failureCallback!==void 0&&t.set("Upstash-Failure-Callback",e.failureCallback),e.timeout!==void 0&&t.set("Upstash-Timeout",`${e.timeout}s`),e.scheduleId!==void 0&&t.set("Upstash-Schedule-Id",e.scheduleId),await this.http.request({method:"POST",headers:t,path:["v2","schedules",e.destination],body:e.body})}async get(e){return await this.http.request({method:"GET",path:["v2","schedules",e]})}async list(){return await this.http.request({method:"GET",path:["v2","schedules"]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","schedules",e],parseResponseAsJson:!1})}async pause({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"pause"],parseResponseAsJson:!1})}async resume({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"resume"],parseResponseAsJson:!1})}};var te=class{http;constructor(e){this.http=e}async addEndpoints(e){await this.http.request({method:"POST",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async removeEndpoints(e){await this.http.request({method:"DELETE",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async list(){return await this.http.request({method:"GET",path:["v2","topics"]})}async get(e){return await this.http.request({method:"GET",path:["v2","topics",e]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","topics",e],parseResponseAsJson:!1})}};var x=class{http;token;constructor(e){this.http=new V({retry:e.retry,baseUrl:e.baseUrl?e.baseUrl.replace(/\/$/,""):"https://qstash.upstash.io",authorization:`Bearer ${e.token}`}),this.token=e.token}get urlGroups(){return new te(this.http)}get topics(){return this.urlGroups}get dlq(){return new Q(this.http)}get messages(){return new X(this.http)}get schedules(){return new ee(this.http)}get workflow(){return new re(this.http)}queue(e){return new Z(this.http,e?.queueName)}chat(){return new Y(this.http,this.token)}async publish(e){let t=_(e);return await this.http.request({path:["v2","publish",H(e)],body:e.body,headers:t,method:"POST"})}async publishJSON(e){let t=v(new Headers(e.headers));return t.set("Content-Type","application/json"),W(e),A(e,t,this.http),await this.publish({...e,headers:t,body:JSON.stringify(e.body)})}async batch(e){let t=[];for(let o of e){let i=_(o),a=Object.fromEntries(i.entries());t.push({destination:H(o),headers:a,body:o.body,...o.queueName&&{queue:o.queueName}})}let s=await this.http.request({path:["v2","batch"],body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST"});return Array.isArray(s)?s:[s]}async batchJSON(e){for(let s of e)"body"in s&&(s.body=JSON.stringify(s.body)),s.headers=new Headers(s.headers),W(s),A(s,s.headers,this.http),s.headers.set("Content-Type","application/json");return await this.batch(e)}async events(e){let t={};e?.cursor&&e.cursor>0&&(t.cursor=e.cursor.toString());for(let[n,o]of Object.entries(e?.filter??{}))typeof o=="number"&&o<0||(n==="urlGroup"?t.topicName=o.toString():typeof o<"u"&&(t[n]=o.toString()));let s=await this.http.request({path:["v2","events"],method:"GET",query:t});return{cursor:s.cursor,events:s.events.map(n=>({...n,urlGroup:n.topicName}))}}};var et={withStackTrace:!1},Ue=(r,e,t=et)=>{let s=e.isOk()?{type:"Ok",value:e.value}:{type:"Err",value:e.error},n=t.withStackTrace?new Error().stack:void 0;return{data:s,message:r,stack:n}};function U(r,e,t,s){function n(o){return o instanceof t?o:new t(function(i){i(o)})}return new(t||(t=Promise))(function(o,i){function a(c){try{p(s.next(c))}catch(m){i(m)}}function l(c){try{p(s.throw(c))}catch(m){i(m)}}function p(c){c.done?o(c.value):n(c.value).then(a,l)}p((s=s.apply(r,[])).next())})}function xe(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function E(r){return this instanceof E?(this.v=r,this):new E(r)}function tt(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(r,e||[]),n,o=[];return n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n;function i(u){s[u]&&(n[u]=function(w){return new Promise(function(f,g){o.push([u,w,f,g])>1||a(u,w)})})}function a(u,w){try{l(s[u](w))}catch(f){m(o[0][3],f)}}function l(u){u.value instanceof E?Promise.resolve(u.value.v).then(p,c):m(o[0][2],u)}function p(u){a("next",u)}function c(u){a("throw",u)}function m(u,w){u(w),o.shift(),o.length&&a(o[0][0],o[0][1])}}function rt(r){var e,t;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,o){e[n]=r[n]?function(i){return(t=!t)?{value:E(r[n](i)),done:n==="return"}:o?o(i):i}:o}}function st(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof xe=="function"?xe(r):r[Symbol.iterator](),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(o){t[o]=r[o]&&function(i){return new Promise(function(a,l){i=r[o](i),n(a,l,i.done,i.value)})}}function n(o,i,a,l){Promise.resolve(l).then(function(p){o({value:p,done:a})},i)}}var k=class r{constructor(e){this._promise=e}static fromSafePromise(e){let t=e.then(s=>new T(s));return new r(t)}static fromPromise(e,t){let s=e.then(n=>new T(n)).catch(n=>new b(t(n)));return new r(s)}static fromThrowable(e,t){return(...s)=>new r(U(this,void 0,void 0,function*(){try{return new T(yield e(...s))}catch(n){return new b(t?t(n):n)}}))}static combine(e){return nt(e)}static combineWithAllErrors(e){return ot(e)}map(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?new b(t.error):new T(yield e(t.value))})))}andThrough(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){if(t.isErr())return new b(t.error);let s=yield e(t.value);return s.isErr()?new b(s.error):new T(t.value)})))}andTee(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){if(t.isErr())return new b(t.error);try{yield e(t.value)}catch{}return new T(t.value)})))}mapErr(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isOk()?new T(t.value):new b(yield e(t.error))})))}andThen(e){return new r(this._promise.then(t=>{if(t.isErr())return new b(t.error);let s=e(t.value);return s instanceof r?s._promise:s}))}orElse(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?e(t.error):new T(t.value)})))}match(e,t){return this._promise.then(s=>s.match(e,t))}unwrapOr(e){return this._promise.then(t=>t.unwrapOr(e))}safeUnwrap(){return tt(this,arguments,function*(){return yield E(yield E(yield*rt(st(yield E(this._promise.then(t=>t.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}};var ge=r=>new k(Promise.resolve(new b(r))),$t=k.fromPromise,Jt=k.fromSafePromise,Qt=k.fromThrowable,Oe=r=>{let e=h([]);for(let t of r)if(t.isErr()){e=y(t.error);break}else e.map(s=>s.push(t.value));return e},nt=r=>k.fromSafePromise(Promise.all(r)).andThen(Oe),Ne=r=>{let e=h([]);for(let t of r)t.isErr()&&e.isErr()?e.error.push(t.error):t.isErr()&&e.isOk()?e=y([t.error]):t.isOk()&&e.isOk()&&e.value.push(t.value);return e},ot=r=>k.fromSafePromise(Promise.all(r)).andThen(Ne),we;(function(r){function e(n,o){return(...i)=>{try{let a=n(...i);return h(a)}catch(a){return y(o?o(a):a)}}}r.fromThrowable=e;function t(n){return Oe(n)}r.combine=t;function s(n){return Ne(n)}r.combineWithAllErrors=s})(we||(we={}));var h=r=>new T(r);function y(r){return new b(r)}var T=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return h(e(this.value))}mapErr(e){return h(this.value)}andThen(e){return e(this.value)}andThrough(e){return e(this.value).map(t=>this.value)}andTee(e){try{e(this.value)}catch{}return h(this.value)}orElse(e){return h(this.value)}asyncAndThen(e){return e(this.value)}asyncAndThrough(e){return e(this.value).map(()=>this.value)}asyncMap(e){return k.fromSafePromise(e(this.value))}unwrapOr(e){return this.value}match(e,t){return e(this.value)}safeUnwrap(){let e=this.value;return function*(){return e}()}_unsafeUnwrap(e){return this.value}_unsafeUnwrapErr(e){throw Ue("Called `_unsafeUnwrapErr` on an Ok",this,e)}},b=class{constructor(e){this.error=e}isOk(){return!1}isErr(){return!this.isOk()}map(e){return y(this.error)}mapErr(e){return y(e(this.error))}andThrough(e){return y(this.error)}andTee(e){return y(this.error)}andThen(e){return y(this.error)}orElse(e){return e(this.error)}asyncAndThen(e){return ge(this.error)}asyncAndThrough(e){return ge(this.error)}asyncMap(e){return ge(this.error)}unwrapOr(e){return e}match(e,t){return t(this.error)}safeUnwrap(){let e=this.error;return function*(){throw yield y(e),new Error("Do not use this generator out of `safeTry`")}()}_unsafeUnwrap(e){throw Ue("Called `_unsafeUnwrap` on an Err",this,e)}_unsafeUnwrapErr(e){return this.error}},Kt=we.fromThrowable;var F="Upstash-Workflow-RunId",qe="Upstash-Workflow-Init",Le="Upstash-Workflow-Url",se="Upstash-Workflow-Is-Failure",B="1",ne="Upstash-Workflow-Sdk-Version",Ae="application/json";var We=["Initial","Run","SleepFor","SleepUntil","Call"];var _e=async(r,e)=>{let t=oe("true",r.workflowRunId,r.url,r.headers,void 0,r.failureUrl);await e?.log("SUBMIT","SUBMIT_FIRST_INVOCATION",{headers:t,requestPayload:r.requestPayload,url:r.url});try{return await r.qstashClient.publishJSON({headers:t,method:"POST",body:r.requestPayload,url:r.url}),h("success")}catch(s){return y(s)}},He=async({onCleanup:r,onStep:e})=>{try{return await e(),await r(),h("workflow-finished")}catch(t){let s=t;return s instanceof R?h("step-finished"):y(s)}},Fe=async(r,e,t=!1)=>{await e?.log("SUBMIT","SUBMIT_CLEANUP",{deletedWorkflowRunId:r.workflowRunId});let s=await r.qstashClient.http.request({path:["v2","workflows","runs",`${r.workflowRunId}?cancel=${t}`],method:"DELETE",parseResponseAsJson:!1});await e?.log("SUBMIT","SUBMIT_CLEANUP",s)},D=r=>{let e=new Headers,t=r.entries();for(let[s,n]of t){let o=s.toLowerCase();!o.startsWith("upstash-workflow-")&&!o.startsWith("x-vercel-")&&!o.startsWith("x-forwarded-")&&e.append(s,n)}return e},Be=async(r,e,t,s,n,o)=>{try{if(r.headers.get("Upstash-Workflow-Callback")){let i=JSON.parse(e);if(!(i.status>=200&&i.status<300))return await o?.log("WARN","SUBMIT_THIRD_PARTY_RESULT",i),h("call-will-retry");let a=r.headers.get(F),l=r.headers.get("Upstash-Workflow-StepId"),p=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),m=r.headers.get("Upstash-Workflow-Concurrent"),u=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&p&&We.includes(c)&&m&&u))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:p,stepType:c,concurrentString:m,contentType:u})}`);let w=D(r.headers),f=oe("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:p,stepType:c,out:Buffer.from(i.body,"base64").toString(),concurrent:Number(m)};await o?.log("SUBMIT","SUBMIT_THIRD_PARTY_RESULT",{step:g,headers:f,url:s});let S=await t.publishJSON({headers:f,method:"POST",body:g,url:s});return await o?.log("SUBMIT","SUBMIT_THIRD_PARTY_RESULT",{messageId:S.messageId}),h("is-call-return")}else return h("continue-workflow")}catch(i){let a=r.headers.get("Upstash-Workflow-Callback");return y(new d(`Error when handling call return (isCallReturn=${a}): ${i}`))}},oe=(r,e,t,s,n,o)=>{let i={[qe]:r,[F]:e,[Le]:t,[`Upstash-Forward-${ne}`]:B,...o?{[`Upstash-Failure-Callback-Forward-${se}`]:"true","Upstash-Failure-Callback":o}:{}};if(s)for(let a of s.keys())n?.callHeaders?i[`Upstash-Callback-Forward-${a}`]=s.get(a):i[`Upstash-Forward-${a}`]=s.get(a);if(n?.callHeaders){let a=Object.fromEntries(Object.entries(n.callHeaders).map(([p,c])=>[`Upstash-Forward-${p}`,c])),l=n.callHeaders["Content-Type"];return{...i,...a,"Upstash-Callback":t,"Upstash-Callback-Workflow-RunId":e,"Upstash-Callback-Workflow-CallType":"fromCallback","Upstash-Callback-Workflow-Init":"false","Upstash-Callback-Workflow-Url":t,"Upstash-Callback-Forward-Upstash-Workflow-Callback":"true","Upstash-Callback-Forward-Upstash-Workflow-StepId":n.stepId.toString(),"Upstash-Callback-Forward-Upstash-Workflow-StepName":n.stepName,"Upstash-Callback-Forward-Upstash-Workflow-StepType":n.stepType,"Upstash-Callback-Forward-Upstash-Workflow-Concurrent":n.concurrent.toString(),"Upstash-Callback-Forward-Upstash-Workflow-ContentType":l??Ae,"Upstash-Workflow-CallType":"toCallback"}}return i},De=async(r,e,t)=>{if(t)try{if(!e)throw new Error("`Upstash-Signature` header is not passed.");if(!await t.verify({body:r,signature:e}))throw new Error("Signature in `Upstash-Signature` header is not valid")}catch(s){throw new d(`Failed to verify that the Workflow request comes from QStash: ${s}
1
+ import*as Pe from"jose";import ke from"crypto-js";var q=class extends Error{constructor(e){super(e),this.name="SignatureError"}},J=class{currentSigningKey;nextSigningKey;constructor(e){this.currentSigningKey=e.currentSigningKey,this.nextSigningKey=e.nextSigningKey}async verify(e){return await this.verifyWithKey(this.currentSigningKey,e)?!0:this.verifyWithKey(this.nextSigningKey,e)}async verifyWithKey(e,t){let n=(await Pe.jwtVerify(t.signature,new TextEncoder().encode(e),{issuer:"Upstash",clockTolerance:t.clockTolerance}).catch(a=>{throw new q(a.message)})).payload;if(t.url!==void 0&&n.sub!==t.url)throw new q(`invalid subject: ${n.sub}, want: ${t.url}`);let o=ke.SHA256(t.body).toString(ke.enc.Base64url),i=new RegExp(/=+$/);if(n.body.replace(i,"")!==o.replace(i,""))throw new q(`body hash does not match, want: ${n.body}, got: ${o}`);return!0}};var Q=class{http;constructor(e){this.http=e}async listMessages(e){let t={...e?.filter,topicName:e?.filter?.urlGroup},s=await this.http.request({method:"GET",path:["v2","dlq"],query:{cursor:e?.cursor,count:e?.count,...t}});return{messages:s.messages.map(n=>({...n,urlGroup:n.topicName})),cursor:s.cursor}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","dlq",e],parseResponseAsJson:!1})}async deleteMany(e){return await this.http.request({method:"DELETE",path:["v2","dlq"],headers:{"Content-Type":"application/json"},body:JSON.stringify({dlqIds:e.dlqIds})})}};var P=class extends Error{constructor(e){super(e),this.name="QstashError"}},K=class extends P{limit;remaining;reset;constructor(e){super(`Exceeded burst rate limit. ${JSON.stringify(e)} `),this.name="QstashRatelimitError",this.limit=e.limit,this.remaining=e.remaining,this.reset=e.reset}},j=class extends P{limitRequests;limitTokens;remainingRequests;remainingTokens;resetRequests;resetTokens;constructor(e){super(`Exceeded chat rate limit. ${JSON.stringify(e)} `),this.limitRequests=e["limit-requests"],this.limitTokens=e["limit-tokens"],this.remainingRequests=e["remaining-requests"],this.remainingTokens=e["remaining-tokens"],this.resetRequests=e["reset-requests"],this.resetTokens=e["reset-tokens"]}},z=class extends P{limit;remaining;reset;constructor(e){super(`Exceeded daily rate limit. ${JSON.stringify(e)} `),this.limit=e.limit,this.remaining=e.remaining,this.reset=e.reset,this.name="QstashChatRatelimitError"}},d=class extends P{constructor(e){super(e),this.name="QStashWorkflowError"}},R=class extends Error{stepInfo;stepName;constructor(e,t){super(`This is an QStash Workflow error thrown after a step executes. It is expected to be raised. Make sure that you await for each step. Also, if you are using try/catch blocks, you should not wrap context.run/sleep/sleepUntil/call methods with try/catch. Aborting workflow after executing step '${e}'.`),this.name="QStashWorkflowAbort",this.stepName=e,this.stepInfo=t}},ve=r=>r instanceof Error?{error:r.name,message:r.message}:{error:"Error",message:"An error occured while executing workflow."};var V=class{baseUrl;authorization;options;retry;constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.authorization=e.authorization,this.retry=typeof e.retry=="boolean"&&!e.retry?{attempts:1,backoff:()=>0}:{attempts:e.retry?.retries?e.retry.retries+1:5,backoff:e.retry?.backoff??(t=>Math.exp(t)*50)}}async request(e){let{response:t}=await this.requestWithBackoff(e);if(e.parseResponseAsJson!==!1)return await t.json()}async*requestStream(e){let{response:t}=await this.requestWithBackoff(e);if(!t.body)throw new Error("No response body");let n=t.body.getReader(),o=new TextDecoder;try{for(;;){let{done:i,value:a}=await n.read();if(i)break;let p=o.decode(a,{stream:!0}).split(`
2
+ `).filter(Boolean);for(let c of p)if(c.startsWith("data: ")){let m=c.slice(6);if(m==="[DONE]")break;yield JSON.parse(m)}}}finally{await n.cancel()}}requestWithBackoff=async e=>{let[t,s]=this.processRequest(e),n,o;for(let i=0;i<this.retry.attempts;i++)try{n=await fetch(t.toString(),s);break}catch(a){o=a,await new Promise(l=>setTimeout(l,this.retry.backoff(i)))}if(!n)throw o??new Error("Exhausted all retries");return await this.checkResponse(n),{response:n,error:o}};processRequest=e=>{let t=new Headers(e.headers);t.has("Authorization")||t.set("Authorization",this.authorization);let s={method:e.method,headers:t,body:e.body,keepalive:e.keepalive},n=new URL([e.baseUrl??this.baseUrl,...e.path].join("/"));if(e.query)for(let[o,i]of Object.entries(e.query))i!==void 0&&n.searchParams.set(o,i.toString());return[n.toString(),s]};async checkResponse(e){if(e.status===429)throw e.headers.get("x-ratelimit-limit-requests")?new j({"limit-requests":e.headers.get("x-ratelimit-limit-requests"),"limit-tokens":e.headers.get("x-ratelimit-limit-tokens"),"remaining-requests":e.headers.get("x-ratelimit-remaining-requests"),"remaining-tokens":e.headers.get("x-ratelimit-remaining-tokens"),"reset-requests":e.headers.get("x-ratelimit-reset-requests"),"reset-tokens":e.headers.get("x-ratelimit-reset-tokens")}):e.headers.get("RateLimit-Limit")?new z({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new K({limit:e.headers.get("Burst-RateLimit-Limit"),remaining:e.headers.get("Burst-RateLimit-Remaining"),reset:e.headers.get("Burst-RateLimit-Reset")});if(e.status<200||e.status>=300){let t=await e.text();throw new P(t.length>0?t:`Error: status=${e.status}`)}}};var I=(r,e,t,s)=>{if(!r)return{};switch(r.name){case"helicone":switch(s){case"upstash":return{baseURL:"https://qstash.helicone.ai/llm/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,Authorization:`Bearer ${e}`}};default:return{baseURL:"https://gateway.helicone.ai/v1/chat/completions",defaultHeaders:{"Helicone-Auth":`Bearer ${r.token}`,"Helicone-Target-Url":t,Authorization:`Bearer ${e}`}}}default:throw new Error("Unknown analytics provider")}};var Y=class r{http;token;constructor(e,t){this.http=e,this.token=t}static toChatRequest(e){let t=[];return t.push({role:"system",content:e.system},{role:"user",content:e.user}),{...e,messages:t}}create=async e=>{if(e.provider.owner!="upstash")return this.createThirdParty(e);let t=JSON.stringify(e),s,n={"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,..."stream"in e&&e.stream?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{}};if(e.analytics){let{baseURL:i,defaultHeaders:a}=I({name:"helicone",token:e.analytics.token},this.getAuthorizationToken(),e.provider.baseUrl,"upstash");n={...n,...a},s=i}let o=e.analytics?[]:["llm","v1","chat","completions"];return"stream"in e&&e.stream?this.http.requestStream({path:o,method:"POST",headers:n,baseUrl:s,body:t}):this.http.request({path:o,method:"POST",headers:n,baseUrl:s,body:t})};createThirdParty=async e=>{let{baseUrl:t,token:s,owner:n}=e.provider;if(n==="upstash")throw new Error("Upstash is not 3rd party provider!");delete e.provider,delete e.system;let o=e.analytics;delete e.analytics;let i=JSON.stringify(e),a=o?.name&&o.token,l=o?.name&&o.token?I({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},p="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...p?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[p?"requestStream":"request"]({path:a?[]:["v1","chat","completions"],method:"POST",headers:c,body:i,baseUrl:l.baseURL})};getAuthorizationToken(){let t=String(this.http.authorization).match(/Bearer (.+)/);if(!t)throw new Error("Invalid authorization header format");return t[1]}prompt=async e=>{let t=r.toChatRequest(e);return this.create(t)}};function A(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){Ve(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ye(s),a=n?I({name:n.name,token:n.token},i,o,"custom"):void 0;a?(Ee(e,a),r.url=a.baseURL):(r.url=`${o}/v1/chat/completions`,e.set("Authorization",`Bearer ${i}`))}function Ve(r,e,t,s){if(s){let n=I({name:s.name,token:s.token},String(t.authorization).split("Bearer ")[1],r.api?.provider?.baseUrl,"upstash");Ee(e,n),r.url=n.baseURL}else r.api={name:"llm"}}function Ye(r){if(!r?.baseUrl)throw new Error("baseUrl cannot be empty or undefined!");if(!r.token)throw new Error("token cannot be empty or undefined!");return{baseUrl:r.baseUrl,token:r.token}}function Ee(r,e){r.set("Helicone-Auth",e.defaultHeaders?.["Helicone-Auth"]??""),r.set("Authorization",e.defaultHeaders?.Authorization??""),e.defaultHeaders?.["Helicone-Target-Url"]&&r.set("Helicone-Target-Url",e.defaultHeaders["Helicone-Target-Url"])}function W(r){if(r.api?.name==="llm"&&!r.callback)throw new TypeError("Callback cannot be undefined when using LLM")}var X=class{http;constructor(e){this.http=e}async get(e){let t=await this.http.request({method:"GET",path:["v2","messages",e]});return{...t,urlGroup:t.topicName}}async delete(e){return await this.http.request({method:"DELETE",path:["v2","messages",e],parseResponseAsJson:!1})}async deleteMany(e){return(await this.http.request({method:"DELETE",path:["v2","messages"],headers:{"Content-Type":"application/json"},body:JSON.stringify({messageIds:e})})).cancelled}async deleteAll(){return(await this.http.request({method:"DELETE",path:["v2","messages"]})).cancelled}};var Xe=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function v(r){let e=[...r.keys()].filter(t=>!Xe(t));for(let t of e){let s=r.get(t);s!==null&&r.set(`Upstash-Forward-${t}`,s),r.delete(t)}return r}function _(r){let e=v(new Headers(r.headers));return e.set("Upstash-Method",r.method??"POST"),r.delay!==void 0&&(typeof r.delay=="string"?e.set("Upstash-Delay",r.delay):e.set("Upstash-Delay",`${r.delay.toFixed(0)}s`)),r.notBefore!==void 0&&e.set("Upstash-Not-Before",r.notBefore.toFixed(0)),r.deduplicationId!==void 0&&e.set("Upstash-Deduplication-Id",r.deduplicationId),r.contentBasedDeduplication!==void 0&&e.set("Upstash-Content-Based-Deduplication","true"),r.retries!==void 0&&e.set("Upstash-Retries",r.retries.toFixed(0)),r.callback!==void 0&&e.set("Upstash-Callback",r.callback),r.failureCallback!==void 0&&e.set("Upstash-Failure-Callback",r.failureCallback),r.timeout!==void 0&&(typeof r.timeout=="string"?e.set("Upstash-Timeout",r.timeout):e.set("Upstash-Timeout",`${r.timeout}s`)),e}function H(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",Ze=21;function Ie(){return[...crypto.getRandomValues(new Uint8Array(Ze))].map(r=>Ce[r%Ce.length]).join("")}var Z=class{http;queueName;constructor(e,t){this.http=e,this.queueName=t}async upsert(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t={queueName:this.queueName,parallelism:e.parallelism??1,paused:e.paused??!1};await this.http.request({method:"POST",path:["v2","queues"],headers:{"Content-Type":"application/json"},body:JSON.stringify(t),parseResponseAsJson:!1})}async get(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");return await this.http.request({method:"GET",path:["v2","queues",this.queueName]})}async list(){return await this.http.request({method:"GET",path:["v2","queues"]})}async delete(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"DELETE",path:["v2","queues",this.queueName],parseResponseAsJson:!1})}async enqueue(e){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");let t=_(e),s=H(e);return await this.http.request({path:["v2","enqueue",this.queueName,s],body:e.body,headers:t,method:"POST"})}async enqueueJSON(e){let t=v(new Headers(e.headers));return t.set("Content-Type","application/json"),W(e),A(e,t,this.http),await this.enqueue({...e,body:JSON.stringify(e.body),headers:t})}async pause(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"pause"],parseResponseAsJson:!1})}async resume(){if(!this.queueName)throw new Error("Please provide a queue name to the Queue constructor");await this.http.request({method:"POST",path:["v2","queues",this.queueName,"resume"],parseResponseAsJson:!1})}};var ee=class{http;constructor(e){this.http=e}async create(e){let t=v(new Headers(e.headers));return t.has("Content-Type")||t.set("Content-Type","application/json"),t.set("Upstash-Cron",e.cron),e.method!==void 0&&t.set("Upstash-Method",e.method),e.delay!==void 0&&(typeof e.delay=="string"?t.set("Upstash-Delay",e.delay):t.set("Upstash-Delay",`${e.delay.toFixed(0)}s`)),e.retries!==void 0&&t.set("Upstash-Retries",e.retries.toFixed(0)),e.callback!==void 0&&t.set("Upstash-Callback",e.callback),e.failureCallback!==void 0&&t.set("Upstash-Failure-Callback",e.failureCallback),e.timeout!==void 0&&(typeof e.timeout=="string"?t.set("Upstash-Timeout",e.timeout):t.set("Upstash-Timeout",`${e.timeout}s`)),e.scheduleId!==void 0&&t.set("Upstash-Schedule-Id",e.scheduleId),await this.http.request({method:"POST",headers:t,path:["v2","schedules",e.destination],body:e.body})}async get(e){return await this.http.request({method:"GET",path:["v2","schedules",e]})}async list(){return await this.http.request({method:"GET",path:["v2","schedules"]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","schedules",e],parseResponseAsJson:!1})}async pause({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"pause"],parseResponseAsJson:!1})}async resume({schedule:e}){await this.http.request({method:"PATCH",path:["v2","schedules",e,"resume"],parseResponseAsJson:!1})}};var te=class{http;constructor(e){this.http=e}async addEndpoints(e){await this.http.request({method:"POST",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async removeEndpoints(e){await this.http.request({method:"DELETE",path:["v2","topics",e.name,"endpoints"],headers:{"Content-Type":"application/json"},body:JSON.stringify({endpoints:e.endpoints}),parseResponseAsJson:!1})}async list(){return await this.http.request({method:"GET",path:["v2","topics"]})}async get(e){return await this.http.request({method:"GET",path:["v2","topics",e]})}async delete(e){return await this.http.request({method:"DELETE",path:["v2","topics",e],parseResponseAsJson:!1})}};var x=class{http;token;constructor(e){this.http=new V({retry:e.retry,baseUrl:e.baseUrl?e.baseUrl.replace(/\/$/,""):"https://qstash.upstash.io",authorization:`Bearer ${e.token}`}),this.token=e.token}get urlGroups(){return new te(this.http)}get topics(){return this.urlGroups}get dlq(){return new Q(this.http)}get messages(){return new X(this.http)}get schedules(){return new ee(this.http)}get workflow(){return new re(this.http)}queue(e){return new Z(this.http,e?.queueName)}chat(){return new Y(this.http,this.token)}async publish(e){let t=_(e);return await this.http.request({path:["v2","publish",H(e)],body:e.body,headers:t,method:"POST"})}async publishJSON(e){let t=v(new Headers(e.headers));return t.set("Content-Type","application/json"),W(e),A(e,t,this.http),await this.publish({...e,headers:t,body:JSON.stringify(e.body)})}async batch(e){let t=[];for(let o of e){let i=_(o),a=Object.fromEntries(i.entries());t.push({destination:H(o),headers:a,body:o.body,...o.queueName&&{queue:o.queueName}})}let s=await this.http.request({path:["v2","batch"],body:JSON.stringify(t),headers:{"Content-Type":"application/json"},method:"POST"});return Array.isArray(s)?s:[s]}async batchJSON(e){for(let s of e)"body"in s&&(s.body=JSON.stringify(s.body)),s.headers=new Headers(s.headers),W(s),A(s,s.headers,this.http),s.headers.set("Content-Type","application/json");return await this.batch(e)}async events(e){let t={};e?.cursor&&e.cursor>0&&(t.cursor=e.cursor.toString());for(let[n,o]of Object.entries(e?.filter??{}))typeof o=="number"&&o<0||(n==="urlGroup"?t.topicName=o.toString():typeof o<"u"&&(t[n]=o.toString()));let s=await this.http.request({path:["v2","events"],method:"GET",query:t});return{cursor:s.cursor,events:s.events.map(n=>({...n,urlGroup:n.topicName}))}}};var et={withStackTrace:!1},Ue=(r,e,t=et)=>{let s=e.isOk()?{type:"Ok",value:e.value}:{type:"Err",value:e.error},n=t.withStackTrace?new Error().stack:void 0;return{data:s,message:r,stack:n}};function U(r,e,t,s){function n(o){return o instanceof t?o:new t(function(i){i(o)})}return new(t||(t=Promise))(function(o,i){function a(c){try{p(s.next(c))}catch(m){i(m)}}function l(c){try{p(s.throw(c))}catch(m){i(m)}}function p(c){c.done?o(c.value):n(c.value).then(a,l)}p((s=s.apply(r,[])).next())})}function xe(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],s=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&s>=r.length&&(r=void 0),{value:r&&r[s++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function E(r){return this instanceof E?(this.v=r,this):new E(r)}function tt(r,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(r,e||[]),n,o=[];return n={},i("next"),i("throw"),i("return"),n[Symbol.asyncIterator]=function(){return this},n;function i(u){s[u]&&(n[u]=function(w){return new Promise(function(f,g){o.push([u,w,f,g])>1||a(u,w)})})}function a(u,w){try{l(s[u](w))}catch(f){m(o[0][3],f)}}function l(u){u.value instanceof E?Promise.resolve(u.value.v).then(p,c):m(o[0][2],u)}function p(u){a("next",u)}function c(u){a("throw",u)}function m(u,w){u(w),o.shift(),o.length&&a(o[0][0],o[0][1])}}function rt(r){var e,t;return e={},s("next"),s("throw",function(n){throw n}),s("return"),e[Symbol.iterator]=function(){return this},e;function s(n,o){e[n]=r[n]?function(i){return(t=!t)?{value:E(r[n](i)),done:n==="return"}:o?o(i):i}:o}}function st(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof xe=="function"?xe(r):r[Symbol.iterator](),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(o){t[o]=r[o]&&function(i){return new Promise(function(a,l){i=r[o](i),n(a,l,i.done,i.value)})}}function n(o,i,a,l){Promise.resolve(l).then(function(p){o({value:p,done:a})},i)}}var k=class r{constructor(e){this._promise=e}static fromSafePromise(e){let t=e.then(s=>new T(s));return new r(t)}static fromPromise(e,t){let s=e.then(n=>new T(n)).catch(n=>new b(t(n)));return new r(s)}static fromThrowable(e,t){return(...s)=>new r(U(this,void 0,void 0,function*(){try{return new T(yield e(...s))}catch(n){return new b(t?t(n):n)}}))}static combine(e){return nt(e)}static combineWithAllErrors(e){return ot(e)}map(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?new b(t.error):new T(yield e(t.value))})))}andThrough(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){if(t.isErr())return new b(t.error);let s=yield e(t.value);return s.isErr()?new b(s.error):new T(t.value)})))}andTee(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){if(t.isErr())return new b(t.error);try{yield e(t.value)}catch{}return new T(t.value)})))}mapErr(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isOk()?new T(t.value):new b(yield e(t.error))})))}andThen(e){return new r(this._promise.then(t=>{if(t.isErr())return new b(t.error);let s=e(t.value);return s instanceof r?s._promise:s}))}orElse(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?e(t.error):new T(t.value)})))}match(e,t){return this._promise.then(s=>s.match(e,t))}unwrapOr(e){return this._promise.then(t=>t.unwrapOr(e))}safeUnwrap(){return tt(this,arguments,function*(){return yield E(yield E(yield*rt(st(yield E(this._promise.then(t=>t.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}};var ge=r=>new k(Promise.resolve(new b(r))),$t=k.fromPromise,Jt=k.fromSafePromise,Qt=k.fromThrowable,Oe=r=>{let e=h([]);for(let t of r)if(t.isErr()){e=y(t.error);break}else e.map(s=>s.push(t.value));return e},nt=r=>k.fromSafePromise(Promise.all(r)).andThen(Oe),Ne=r=>{let e=h([]);for(let t of r)t.isErr()&&e.isErr()?e.error.push(t.error):t.isErr()&&e.isOk()?e=y([t.error]):t.isOk()&&e.isOk()&&e.value.push(t.value);return e},ot=r=>k.fromSafePromise(Promise.all(r)).andThen(Ne),we;(function(r){function e(n,o){return(...i)=>{try{let a=n(...i);return h(a)}catch(a){return y(o?o(a):a)}}}r.fromThrowable=e;function t(n){return Oe(n)}r.combine=t;function s(n){return Ne(n)}r.combineWithAllErrors=s})(we||(we={}));var h=r=>new T(r);function y(r){return new b(r)}var T=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return h(e(this.value))}mapErr(e){return h(this.value)}andThen(e){return e(this.value)}andThrough(e){return e(this.value).map(t=>this.value)}andTee(e){try{e(this.value)}catch{}return h(this.value)}orElse(e){return h(this.value)}asyncAndThen(e){return e(this.value)}asyncAndThrough(e){return e(this.value).map(()=>this.value)}asyncMap(e){return k.fromSafePromise(e(this.value))}unwrapOr(e){return this.value}match(e,t){return e(this.value)}safeUnwrap(){let e=this.value;return function*(){return e}()}_unsafeUnwrap(e){return this.value}_unsafeUnwrapErr(e){throw Ue("Called `_unsafeUnwrapErr` on an Ok",this,e)}},b=class{constructor(e){this.error=e}isOk(){return!1}isErr(){return!this.isOk()}map(e){return y(this.error)}mapErr(e){return y(e(this.error))}andThrough(e){return y(this.error)}andTee(e){return y(this.error)}andThen(e){return y(this.error)}orElse(e){return e(this.error)}asyncAndThen(e){return ge(this.error)}asyncAndThrough(e){return ge(this.error)}asyncMap(e){return ge(this.error)}unwrapOr(e){return e}match(e,t){return t(this.error)}safeUnwrap(){let e=this.error;return function*(){throw yield y(e),new Error("Do not use this generator out of `safeTry`")}()}_unsafeUnwrap(e){throw Ue("Called `_unsafeUnwrap` on an Err",this,e)}_unsafeUnwrapErr(e){return this.error}},Kt=we.fromThrowable;var F="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",se="Upstash-Workflow-Is-Failure",B="1",ne="Upstash-Workflow-Sdk-Version",Ae="application/json";var We=["Initial","Run","SleepFor","SleepUntil","Call"];var _e=async(r,e)=>{let t=oe("true",r.workflowRunId,r.url,r.headers,void 0,r.failureUrl);await e?.log("SUBMIT","SUBMIT_FIRST_INVOCATION",{headers:t,requestPayload:r.requestPayload,url:r.url});try{return await r.qstashClient.publishJSON({headers:t,method:"POST",body:r.requestPayload,url:r.url}),h("success")}catch(s){return y(s)}},He=async({onCleanup:r,onStep:e})=>{try{return await e(),await r(),h("workflow-finished")}catch(t){let s=t;return s instanceof R?h("step-finished"):y(s)}},Fe=async(r,e,t=!1)=>{await e?.log("SUBMIT","SUBMIT_CLEANUP",{deletedWorkflowRunId:r.workflowRunId});let s=await r.qstashClient.http.request({path:["v2","workflows","runs",`${r.workflowRunId}?cancel=${t}`],method:"DELETE",parseResponseAsJson:!1});await e?.log("SUBMIT","SUBMIT_CLEANUP",s)},D=r=>{let e=new Headers,t=r.entries();for(let[s,n]of t){let o=s.toLowerCase();!o.startsWith("upstash-workflow-")&&!o.startsWith("x-vercel-")&&!o.startsWith("x-forwarded-")&&o!=="cf-connecting-ip"&&e.append(s,n)}return e},Be=async(r,e,t,s,n,o)=>{try{if(r.headers.get("Upstash-Workflow-Callback")){let i=JSON.parse(e);if(!(i.status>=200&&i.status<300))return await o?.log("WARN","SUBMIT_THIRD_PARTY_RESULT",i),h("call-will-retry");let a=r.headers.get(F),l=r.headers.get("Upstash-Workflow-StepId"),p=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),m=r.headers.get("Upstash-Workflow-Concurrent"),u=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&p&&We.includes(c)&&m&&u))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:p,stepType:c,concurrentString:m,contentType:u})}`);let w=D(r.headers),f=oe("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:p,stepType:c,out:Buffer.from(i.body,"base64").toString(),concurrent:Number(m)};await o?.log("SUBMIT","SUBMIT_THIRD_PARTY_RESULT",{step:g,headers:f,url:s});let S=await t.publishJSON({headers:f,method:"POST",body:g,url:s});return await o?.log("SUBMIT","SUBMIT_THIRD_PARTY_RESULT",{messageId:S.messageId}),h("is-call-return")}else return h("continue-workflow")}catch(i){let a=r.headers.get("Upstash-Workflow-Callback");return y(new d(`Error when handling call return (isCallReturn=${a}): ${i}`))}},oe=(r,e,t,s,n,o)=>{let i={[Le]:r,[F]:e,[qe]:t,[`Upstash-Forward-${ne}`]:B,...o?{[`Upstash-Failure-Callback-Forward-${se}`]:"true","Upstash-Failure-Callback":o}:{}};if(s)for(let a of s.keys())n?.callHeaders?i[`Upstash-Callback-Forward-${a}`]=s.get(a):i[`Upstash-Forward-${a}`]=s.get(a);if(n?.callHeaders){let a=Object.fromEntries(Object.entries(n.callHeaders).map(([p,c])=>[`Upstash-Forward-${p}`,c])),l=n.callHeaders["Content-Type"];return{...i,...a,"Upstash-Callback":t,"Upstash-Callback-Workflow-RunId":e,"Upstash-Callback-Workflow-CallType":"fromCallback","Upstash-Callback-Workflow-Init":"false","Upstash-Callback-Workflow-Url":t,"Upstash-Callback-Forward-Upstash-Workflow-Callback":"true","Upstash-Callback-Forward-Upstash-Workflow-StepId":n.stepId.toString(),"Upstash-Callback-Forward-Upstash-Workflow-StepName":n.stepName,"Upstash-Callback-Forward-Upstash-Workflow-StepType":n.stepType,"Upstash-Callback-Forward-Upstash-Workflow-Concurrent":n.concurrent.toString(),"Upstash-Callback-Forward-Upstash-Workflow-ContentType":l??Ae,"Upstash-Workflow-CallType":"toCallback"}}return i},De=async(r,e,t)=>{if(t)try{if(!e)throw new Error("`Upstash-Signature` header is not passed.");if(!await t.verify({body:r,signature:e}))throw new Error("Signature in `Upstash-Signature` header is not valid")}catch(s){throw new d(`Failed to verify that the Workflow request comes from QStash: ${s}
3
3
 
4
4
  If signature is missing, trigger the workflow endpoint by publishing your request to QStash instead of calling it directly.
5
5
 
@@ -7,4 +7,4 @@ If you want to disable QStash Verification, you should clear env variables QSTAS
7
7
  > Step Names from the request: ${JSON.stringify(o)}
8
8
  Step Types from the request: ${JSON.stringify(i)}
9
9
  > Step Names expected: ${JSON.stringify(s)}
10
- Step Types expected: ${JSON.stringify(n)}`)}throw t}},at=r=>{let e=t=>t.targetStep??t.stepId;return r.toSorted((t,s)=>e(t)-e(s))};var O=class{stepName;constructor(e){this.stepName=e}},le=class extends O{stepFunction;stepType="Run";constructor(e,t){super(e),this.stepFunction=t}getPlanStep(e,t){return{stepId:0,stepName:this.stepName,stepType:this.stepType,concurrent:e,targetStep:t}}async getResultStep(e,t){let s=this.stepFunction();return s instanceof Promise&&(s=await s),{stepId:t,stepName:this.stepName,stepType:this.stepType,out:s,concurrent:e}}},ue=class extends O{sleep;stepType="SleepFor";constructor(e,t){super(e),this.sleep=t}getPlanStep(e,t){return{stepId:0,stepName:this.stepName,stepType:this.stepType,sleepFor:this.sleep,concurrent:e,targetStep:t}}async getResultStep(e,t){return await Promise.resolve({stepId:t,stepName:this.stepName,stepType:this.stepType,sleepFor:this.sleep,concurrent:e})}},pe=class extends O{sleepUntil;stepType="SleepUntil";constructor(e,t){super(e),this.sleepUntil=t}getPlanStep(e,t){return{stepId:0,stepName:this.stepName,stepType:this.stepType,sleepUntil:this.sleepUntil,concurrent:e,targetStep:t}}async getResultStep(e,t){return await Promise.resolve({stepId:t,stepName:this.stepName,stepType:this.stepType,sleepUntil:this.sleepUntil,concurrent:e})}},ce=class extends O{url;method;body;headers;stepType="Call";constructor(e,t,s,n,o){super(e),this.url=t,this.method=s,this.body=n,this.headers=o}getPlanStep(e,t){return{stepId:0,stepName:this.stepName,stepType:this.stepType,concurrent:e,targetStep:t}}async getResultStep(e,t){return await Promise.resolve({stepId:t,stepName:this.stepName,stepType:this.stepType,concurrent:e,callUrl:this.url,callMethod:this.method,callBody:this.body,callHeaders:this.headers})}};var C=class{executor;steps;qstashClient;workflowRunId;url;failureUrl;requestPayload;headers;rawInitialPayload;env;constructor({qstashClient:e,workflowRunId:t,headers:s,steps:n,url:o,failureUrl:i,debug:a,initialPayload:l,rawInitialPayload:p,env:c}){this.qstashClient=e,this.workflowRunId=t,this.steps=n,this.url=o,this.failureUrl=i,this.headers=s,this.requestPayload=l,this.rawInitialPayload=p??JSON.stringify(this.requestPayload),this.env=c??{},this.executor=new ae(this,this.steps,a)}async run(e,t){let s=()=>this.executor.wrapStep(e,t);return this.addStep(new le(e,s))}async sleep(e,t){await this.addStep(new ue(e,t))}async sleepUntil(e,t){let s;typeof t=="number"?s=t:(t=typeof t=="string"?new Date(t):t,s=Math.round(t.getTime()/1e3)),await this.addStep(new pe(e,s))}async call(e,t,s,n,o){return await this.addStep(new ce(e,t,s,n,o??{}))}async addStep(e){return await this.executor.addStep(e)}},de=class r extends C{static disabledMessage="disabled-qstash-worklfow-run";async addStep(e){throw new R(r.disabledMessage)}static async tryAuthentication(e,t){let s=new r({qstashClient:new x({baseUrl:"disabled-client",token:"disabled-client"}),workflowRunId:t.workflowRunId,headers:t.headers,steps:[],url:t.url,failureUrl:t.failureUrl,initialPayload:t.requestPayload,rawInitialPayload:t.rawInitialPayload,env:t.env});try{await e(s)}catch(n){return n instanceof R&&n.stepName===this.disabledMessage?h("step-found"):y(n)}return h("run-ended")}};var Me=["DEBUG","INFO","SUBMIT","WARN","ERROR"],he=class r{logs=[];options;workflowRunId=void 0;constructor(e){this.options=e}async log(e,t,s){if(this.shouldLog(e)){let o={timestamp:Date.now(),workflowRunId:this.workflowRunId??"",logLevel:e,eventType:t,details:s};this.logs.push(o),this.options.logOutput==="console"&&this.writeToConsole(o),await new Promise(i=>setTimeout(i,100))}}setWorkflowRunId(e){this.workflowRunId=e}writeToConsole(e){console.log(JSON.stringify(e,void 0,2))}shouldLog(e){return Me.indexOf(e)>=Me.indexOf(this.options.logLevel)}static getLogger(e){return typeof e=="object"?e:e?new r({logLevel:"INFO",logOutput:"console"}):void 0}};var Ge=async r=>{try{return await r.text()}catch{return}},lt=r=>{let[e,...t]=JSON.parse(r),s=atob(e.body),n={stepId:0,stepName:"init",stepType:"Initial",out:s,concurrent:1},i=t.filter(l=>l.callType==="step").map(l=>JSON.parse(atob(l.body))),a=[n,...i];return{rawInitialPayload:s,steps:a}},ut=r=>{let e=[],t=[],s=[];for(let n of r)n.stepId===0?e.includes(n.targetStep??0)||(s.push(n),e.push(n.targetStep??0)):t.includes(n.stepId)||(s.push(n),t.push(n.stepId));return s},pt=async(r,e)=>{if(r.length<2)return!1;let t=r.at(-1),s=t.stepId,n=t.targetStep;for(let o=0;o<r.length-1;o++){let i=r[o];if(i.stepId===s&&i.targetStep===n){let a=`QStash Workflow: The step '${i.stepName}' with id '${i.stepId}' has run twice during workflow execution. Rest of the workflow will continue running as usual.`;return await e?.log("WARN","RESPONSE_DEFAULT",a),console.warn(a),!0}}return!1},$e=r=>{let e=r.headers.get(ne),t=!e;if(!t&&e!==B)throw new d(`Incompatible workflow sdk protocol version. Expected ${B}, got ${e} from the request.`);let s=t?`wfr_${Ie()}`:r.headers.get(F)??"";if(s.length===0)throw new d("Couldn't get workflow id from header");return{isFirstInvocation:t,workflowRunId:s}},Re=async(r,e,t)=>{if(e)return{rawInitialPayload:r??"",steps:[],isLastDuplicate:!1};{if(!r)throw new d("Only first call can have an empty body");let{rawInitialPayload:s,steps:n}=lt(r),o=await pt(n,t),i=ut(n);return{rawInitialPayload:s,steps:i,isLastDuplicate:o}}},Je=async(r,e,t,s,n,o)=>{if(r.headers.get(se)!=="true")return h("not-failure-callback");if(!n)return y(new d("Workflow endpoint is called to handle a failure, but a failureFunction is not provided in serve options. Either provide a failureUrl or a failureFunction."));try{let{status:i,header:a,body:l,url:p,sourceHeader:c,sourceBody:m,workflowRunId:u}=JSON.parse(e),w=l?atob(l):"{}",f=JSON.parse(w),{rawInitialPayload:g,steps:S,isLastDuplicate:me}=await Re(atob(m),!1,o),N=new C({qstashClient:t,workflowRunId:u,initialPayload:s(g),rawInitialPayload:g,headers:D(new Headers(c)),steps:S,url:p,failureUrl:p,debug:o});await n(N,i,f.message,a)}catch(i){return y(i)}return h("is-failure-callback")};var ct=r=>{let e=r?.env??(typeof process>"u"?{}:process.env),t=!!(e.QSTASH_CURRENT_SIGNING_KEY&&e.QSTASH_NEXT_SIGNING_KEY);return{qstashClient:new x({baseUrl:e.QSTASH_URL,token:e.QSTASH_TOKEN}),onStepFinish:(s,n)=>new Response(JSON.stringify({workflowRunId:s}),{status:200}),initialPayloadParser:s=>{if(s)try{return JSON.parse(s)}catch(n){if(n instanceof SyntaxError)return s;throw n}},receiver:t?new J({currentSigningKey:e.QSTASH_CURRENT_SIGNING_KEY,nextSigningKey:e.QSTASH_NEXT_SIGNING_KEY}):void 0,baseUrl:e.UPSTASH_WORKFLOW_URL,env:e,...r}},Qe=(r,e)=>{let{qstashClient:t,onStepFinish:s,initialPayloadParser:n,url:o,verbose:i,receiver:a,failureUrl:l,failureFunction:p,baseUrl:c,env:m}=ct(e),u=he.getLogger(i),w=async f=>{let g=o??f.url,S=c?g.replace(/^(https?:\/\/[^/]+)(\/.*)?$/,($,ht,ze)=>c+(ze||"")):g;S!==g&&await u?.log("WARN","ENDPOINT_START",{warning:`QStash Workflow: replacing the base of the url with "${c}" and using it as workflow endpoint.`,originalURL:g,updatedURL:S});let me=p?S:l,N=await Ge(f)??"";await De(N,f.headers.get("upstash-signature"),a),await u?.log("INFO","ENDPOINT_START");let fe=await Je(f,N,t,n,p);if(fe.isErr())throw fe.error;if(fe.value==="is-failure-callback")return await u?.log("WARN","RESPONSE_DEFAULT","failureFunction executed"),s("no-workflow-id","failure-callback");let{isFirstInvocation:Te,workflowRunId:Se}=$e(f);u?.setWorkflowRunId(Se);let{rawInitialPayload:ye,steps:Ke,isLastDuplicate:je}=await Re(N,Te,u);if(je)return s("no-workflow-id","duplicate-step");let q=new C({qstashClient:t,workflowRunId:Se,initialPayload:n(ye),rawInitialPayload:ye,headers:D(f.headers),steps:Ke,url:S,failureUrl:me,debug:u,env:m}),M=await de.tryAuthentication(r,q);if(M.isErr())throw await u?.log("ERROR","ERROR",{error:M.error.message}),M.error;if(M.value==="run-ended")return s("no-workflow-id","auth-fail");let G=await Be(f,ye,t,S,me,u);if(G.isErr())throw await u?.log("ERROR","SUBMIT_THIRD_PARTY_RESULT",{error:G.error.message}),G.error;if(G.value==="continue-workflow"){let $=Te?await _e(q,u):await He({onStep:async()=>r(q),onCleanup:async()=>{await Fe(q,u)}});if($.isErr())throw await u?.log("ERROR","ERROR",{error:$.error.message}),$.error;return await u?.log("INFO","RESPONSE_WORKFLOW"),s(q.workflowRunId,"success")}return await u?.log("INFO","RESPONSE_DEFAULT"),s("no-workflow-id","fromCallback")};return async f=>{try{return await w(f)}catch(g){return console.error(g),new Response(JSON.stringify(ve(g)),{status:500})}}};var re=class{http;constructor(e){this.http=e}async cancel(e){return await this.http.request({path:["v2","workflows","runs",`${e}?cancel=true`],method:"DELETE",parseResponseAsJson:!1})??!0}};var dt=r=>{if(!Array.isArray(r)||r.length===0)throw new Error("No arguments passed to serve handler");if(typeof r[0]=="object"&&"request"in r[0]&&"env"in r[0])return{request:r[0].request,env:r[0].env};if(r.length>1&&typeof r[1]=="object")return{request:r[0],env:r[1]};throw new Error("Could not derive handler arguments from input. Please check how serve is used.")},Ar=(r,e)=>async(...s)=>{let{request:n,env:o}=dt(s);return await Qe(r,{env:o,...e})(n)};export{Ar as serve};
10
+ Step Types expected: ${JSON.stringify(n)}`)}throw t}},at=r=>{let e=t=>t.targetStep??t.stepId;return r.toSorted((t,s)=>e(t)-e(s))};var O=class{stepName;constructor(e){this.stepName=e}},le=class extends O{stepFunction;stepType="Run";constructor(e,t){super(e),this.stepFunction=t}getPlanStep(e,t){return{stepId:0,stepName:this.stepName,stepType:this.stepType,concurrent:e,targetStep:t}}async getResultStep(e,t){let s=this.stepFunction();return s instanceof Promise&&(s=await s),{stepId:t,stepName:this.stepName,stepType:this.stepType,out:s,concurrent:e}}},ue=class extends O{sleep;stepType="SleepFor";constructor(e,t){super(e),this.sleep=t}getPlanStep(e,t){return{stepId:0,stepName:this.stepName,stepType:this.stepType,sleepFor:this.sleep,concurrent:e,targetStep:t}}async getResultStep(e,t){return await Promise.resolve({stepId:t,stepName:this.stepName,stepType:this.stepType,sleepFor:this.sleep,concurrent:e})}},pe=class extends O{sleepUntil;stepType="SleepUntil";constructor(e,t){super(e),this.sleepUntil=t}getPlanStep(e,t){return{stepId:0,stepName:this.stepName,stepType:this.stepType,sleepUntil:this.sleepUntil,concurrent:e,targetStep:t}}async getResultStep(e,t){return await Promise.resolve({stepId:t,stepName:this.stepName,stepType:this.stepType,sleepUntil:this.sleepUntil,concurrent:e})}},ce=class extends O{url;method;body;headers;stepType="Call";constructor(e,t,s,n,o){super(e),this.url=t,this.method=s,this.body=n,this.headers=o}getPlanStep(e,t){return{stepId:0,stepName:this.stepName,stepType:this.stepType,concurrent:e,targetStep:t}}async getResultStep(e,t){return await Promise.resolve({stepId:t,stepName:this.stepName,stepType:this.stepType,concurrent:e,callUrl:this.url,callMethod:this.method,callBody:this.body,callHeaders:this.headers})}};var C=class{executor;steps;qstashClient;workflowRunId;url;failureUrl;requestPayload;headers;rawInitialPayload;env;constructor({qstashClient:e,workflowRunId:t,headers:s,steps:n,url:o,failureUrl:i,debug:a,initialPayload:l,rawInitialPayload:p,env:c}){this.qstashClient=e,this.workflowRunId=t,this.steps=n,this.url=o,this.failureUrl=i,this.headers=s,this.requestPayload=l,this.rawInitialPayload=p??JSON.stringify(this.requestPayload),this.env=c??{},this.executor=new ae(this,this.steps,a)}async run(e,t){let s=()=>this.executor.wrapStep(e,t);return this.addStep(new le(e,s))}async sleep(e,t){await this.addStep(new ue(e,t))}async sleepUntil(e,t){let s;typeof t=="number"?s=t:(t=typeof t=="string"?new Date(t):t,s=Math.round(t.getTime()/1e3)),await this.addStep(new pe(e,s))}async call(e,t,s,n,o){return await this.addStep(new ce(e,t,s,n,o??{}))}async addStep(e){return await this.executor.addStep(e)}},de=class r extends C{static disabledMessage="disabled-qstash-worklfow-run";async addStep(e){throw new R(r.disabledMessage)}static async tryAuthentication(e,t){let s=new r({qstashClient:new x({baseUrl:"disabled-client",token:"disabled-client"}),workflowRunId:t.workflowRunId,headers:t.headers,steps:[],url:t.url,failureUrl:t.failureUrl,initialPayload:t.requestPayload,rawInitialPayload:t.rawInitialPayload,env:t.env});try{await e(s)}catch(n){return n instanceof R&&n.stepName===this.disabledMessage?h("step-found"):y(n)}return h("run-ended")}};var Me=["DEBUG","INFO","SUBMIT","WARN","ERROR"],he=class r{logs=[];options;workflowRunId=void 0;constructor(e){this.options=e}async log(e,t,s){if(this.shouldLog(e)){let o={timestamp:Date.now(),workflowRunId:this.workflowRunId??"",logLevel:e,eventType:t,details:s};this.logs.push(o),this.options.logOutput==="console"&&this.writeToConsole(o),await new Promise(i=>setTimeout(i,100))}}setWorkflowRunId(e){this.workflowRunId=e}writeToConsole(e){console.log(JSON.stringify(e,void 0,2))}shouldLog(e){return Me.indexOf(e)>=Me.indexOf(this.options.logLevel)}static getLogger(e){return typeof e=="object"?e:e?new r({logLevel:"INFO",logOutput:"console"}):void 0}};var Ge=async r=>{try{return await r.text()}catch{return}},lt=r=>{let[e,...t]=JSON.parse(r),s=atob(e.body),n={stepId:0,stepName:"init",stepType:"Initial",out:s,concurrent:1},i=t.filter(l=>l.callType==="step").map(l=>JSON.parse(atob(l.body))),a=[n,...i];return{rawInitialPayload:s,steps:a}},ut=r=>{let e=[],t=[],s=[];for(let n of r)n.stepId===0?e.includes(n.targetStep??0)||(s.push(n),e.push(n.targetStep??0)):t.includes(n.stepId)||(s.push(n),t.push(n.stepId));return s},pt=async(r,e)=>{if(r.length<2)return!1;let t=r.at(-1),s=t.stepId,n=t.targetStep;for(let o=0;o<r.length-1;o++){let i=r[o];if(i.stepId===s&&i.targetStep===n){let a=`QStash Workflow: The step '${i.stepName}' with id '${i.stepId}' has run twice during workflow execution. Rest of the workflow will continue running as usual.`;return await e?.log("WARN","RESPONSE_DEFAULT",a),console.warn(a),!0}}return!1},$e=r=>{let e=r.headers.get(ne),t=!e;if(!t&&e!==B)throw new d(`Incompatible workflow sdk protocol version. Expected ${B}, got ${e} from the request.`);let s=t?`wfr_${Ie()}`:r.headers.get(F)??"";if(s.length===0)throw new d("Couldn't get workflow id from header");return{isFirstInvocation:t,workflowRunId:s}},Re=async(r,e,t)=>{if(e)return{rawInitialPayload:r??"",steps:[],isLastDuplicate:!1};{if(!r)throw new d("Only first call can have an empty body");let{rawInitialPayload:s,steps:n}=lt(r),o=await pt(n,t),i=ut(n);return{rawInitialPayload:s,steps:i,isLastDuplicate:o}}},Je=async(r,e,t,s,n,o)=>{if(r.headers.get(se)!=="true")return h("not-failure-callback");if(!n)return y(new d("Workflow endpoint is called to handle a failure, but a failureFunction is not provided in serve options. Either provide a failureUrl or a failureFunction."));try{let{status:i,header:a,body:l,url:p,sourceHeader:c,sourceBody:m,workflowRunId:u}=JSON.parse(e),w=l?atob(l):"{}",f=JSON.parse(w),{rawInitialPayload:g,steps:S,isLastDuplicate:me}=await Re(atob(m),!1,o),N=new C({qstashClient:t,workflowRunId:u,initialPayload:s(g),rawInitialPayload:g,headers:D(new Headers(c)),steps:S,url:p,failureUrl:p,debug:o});await n(N,i,f.message,a)}catch(i){return y(i)}return h("is-failure-callback")};var ct=r=>{let e=r?.env??(typeof process>"u"?{}:process.env),t=!!(e.QSTASH_CURRENT_SIGNING_KEY&&e.QSTASH_NEXT_SIGNING_KEY);return{qstashClient:new x({baseUrl:e.QSTASH_URL,token:e.QSTASH_TOKEN}),onStepFinish:(s,n)=>new Response(JSON.stringify({workflowRunId:s}),{status:200}),initialPayloadParser:s=>{if(s)try{return JSON.parse(s)}catch(n){if(n instanceof SyntaxError)return s;throw n}},receiver:t?new J({currentSigningKey:e.QSTASH_CURRENT_SIGNING_KEY,nextSigningKey:e.QSTASH_NEXT_SIGNING_KEY}):void 0,baseUrl:e.UPSTASH_WORKFLOW_URL,env:e,...r}},Qe=(r,e)=>{let{qstashClient:t,onStepFinish:s,initialPayloadParser:n,url:o,verbose:i,receiver:a,failureUrl:l,failureFunction:p,baseUrl:c,env:m}=ct(e),u=he.getLogger(i),w=async f=>{let g=o??f.url,S=c?g.replace(/^(https?:\/\/[^/]+)(\/.*)?$/,($,ht,ze)=>c+(ze||"")):g;S!==g&&await u?.log("WARN","ENDPOINT_START",{warning:`QStash Workflow: replacing the base of the url with "${c}" and using it as workflow endpoint.`,originalURL:g,updatedURL:S});let me=p?S:l,N=await Ge(f)??"";await De(N,f.headers.get("upstash-signature"),a),await u?.log("INFO","ENDPOINT_START");let fe=await Je(f,N,t,n,p);if(fe.isErr())throw fe.error;if(fe.value==="is-failure-callback")return await u?.log("WARN","RESPONSE_DEFAULT","failureFunction executed"),s("no-workflow-id","failure-callback");let{isFirstInvocation:Te,workflowRunId:Se}=$e(f);u?.setWorkflowRunId(Se);let{rawInitialPayload:ye,steps:Ke,isLastDuplicate:je}=await Re(N,Te,u);if(je)return s("no-workflow-id","duplicate-step");let L=new C({qstashClient:t,workflowRunId:Se,initialPayload:n(ye),rawInitialPayload:ye,headers:D(f.headers),steps:Ke,url:S,failureUrl:me,debug:u,env:m}),M=await de.tryAuthentication(r,L);if(M.isErr())throw await u?.log("ERROR","ERROR",{error:M.error.message}),M.error;if(M.value==="run-ended")return s("no-workflow-id","auth-fail");let G=await Be(f,ye,t,S,me,u);if(G.isErr())throw await u?.log("ERROR","SUBMIT_THIRD_PARTY_RESULT",{error:G.error.message}),G.error;if(G.value==="continue-workflow"){let $=Te?await _e(L,u):await He({onStep:async()=>r(L),onCleanup:async()=>{await Fe(L,u)}});if($.isErr())throw await u?.log("ERROR","ERROR",{error:$.error.message}),$.error;return await u?.log("INFO","RESPONSE_WORKFLOW"),s(L.workflowRunId,"success")}return await u?.log("INFO","RESPONSE_DEFAULT"),s("no-workflow-id","fromCallback")};return async f=>{try{return await w(f)}catch(g){return console.error(g),new Response(JSON.stringify(ve(g)),{status:500})}}};var re=class{http;constructor(e){this.http=e}async cancel(e){return await this.http.request({path:["v2","workflows","runs",`${e}?cancel=true`],method:"DELETE",parseResponseAsJson:!1})??!0}};var dt=r=>{if(!Array.isArray(r)||r.length===0)throw new Error("No arguments passed to serve handler");if(typeof r[0]=="object"&&"request"in r[0]&&"env"in r[0])return{request:r[0].request,env:r[0].env};if(r.length>1&&typeof r[1]=="object")return{request:r[0],env:r[1]};throw new Error("Could not derive handler arguments from input. Please check how serve is used.")},Ar=(r,e)=>async(...s)=>{let{request:n,env:o}=dt(s);return await Qe(r,{env:o,...e})(n)};export{Ar as serve};
@@ -435,6 +435,9 @@ declare class DLQ {
435
435
  }>;
436
436
  }
437
437
 
438
+ type Unit = "s" | "m" | "h" | "d";
439
+ type Duration = `${bigint}${Unit}`;
440
+
438
441
  declare class Chat {
439
442
  private http;
440
443
  private token;
@@ -583,7 +586,7 @@ type CreateScheduleRequest = {
583
586
  *
584
587
  * @default undefined
585
588
  */
586
- delay?: number;
589
+ delay?: Duration | number;
587
590
  /**
588
591
  * In case your destination server is unavailable or returns a status code outside of the 200-299
589
592
  * range, we will retry the request after a certain amount of time.
@@ -629,7 +632,7 @@ type CreateScheduleRequest = {
629
632
  *
630
633
  * @default undefined
631
634
  */
632
- timeout?: number;
635
+ timeout?: Duration | number;
633
636
  /**
634
637
  * Schedule id to use.
635
638
  *
@@ -797,7 +800,7 @@ type PublishRequest<TBody = BodyInit> = {
797
800
  *
798
801
  * @default undefined
799
802
  */
800
- delay?: number;
803
+ delay?: Duration | number;
801
804
  /**
802
805
  * Optionally set the absolute delay of this message.
803
806
  * This will override the delay option.
@@ -870,7 +873,7 @@ type PublishRequest<TBody = BodyInit> = {
870
873
  *
871
874
  * @default undefined
872
875
  */
873
- timeout?: number;
876
+ timeout?: Duration | number;
874
877
  } & ({
875
878
  /**
876
879
  * The url where the message should be sent to.