@upstash/qstash 2.7.3 → 2.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloudflare/index.mjs +1 -1
- package/dist/h3/index.mjs +1 -1
- package/dist/hono/index.mjs +1 -1
- package/dist/nextjs/index.d.mts +3 -2
- package/dist/nextjs/index.mjs +3 -3
- package/dist/solidjs/index.mjs +1 -1
- package/dist/svelte/index.mjs +1 -1
- package/dist/workflow/index.mjs +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
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}
|
|
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:atob(i.body),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
|
|
package/dist/h3/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import{defineEventHandler as Qe,getHeader as mt,readRawBody as je}from"h3";import*as Pe from"jose";import ke from"crypto-js";var _=class extends Error{constructor(e){super(e),this.name="SignatureError"}},I=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 _(a.message)})).payload;if(t.url!==void 0&&n.sub!==t.url)throw new _(`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 _(`body hash does not match, want: ${n.body}, got: ${o}`);return!0}};var K=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"}},Q=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"]}},V=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 z=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 u=o.decode(a,{stream:!0}).split(`
|
|
2
|
-
`).filter(Boolean);for(let c of u)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 V({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new Q({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 x=(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}=x({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?x({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},u="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...u?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[u?"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"){Xe(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ze(s),a=n?x({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 Xe(r,e,t,s){if(s){let n=x({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 Ze(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 et=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function v(r){let e=[...r.keys()].filter(t=>!et(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 H(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 F(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",tt=21;function Ie(){return[...crypto.getRandomValues(new Uint8Array(tt))].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=H(e),s=F(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 rt={withStackTrace:!1},Ue=(r,e,t=rt)=>{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{u(s.next(c))}catch(m){i(m)}}function l(c){try{u(s.throw(c))}catch(m){i(m)}}function u(c){c.done?o(c.value):n(c.value).then(a,l)}u((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 st(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(p){s[p]&&(n[p]=function(w){return new Promise(function(f,g){o.push([p,w,f,g])>1||a(p,w)})})}function a(p,w){try{l(s[p](w))}catch(f){m(o[0][3],f)}}function l(p){p.value instanceof E?Promise.resolve(p.value.v).then(u,c):m(o[0][2],p)}function u(p){a("next",p)}function c(p){a("throw",p)}function m(p,w){p(w),o.shift(),o.length&&a(o[0][0],o[0][1])}}function nt(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 ot(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(u){o({value:u,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 it(e)}static combineWithAllErrors(e){return at(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 st(this,arguments,function*(){return yield E(yield E(yield*nt(ot(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))),At=k.fromPromise,Wt=k.fromSafePromise,Ht=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},it=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},at=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}},Ft=we.fromThrowable;var B="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",re="Upstash-Workflow-Is-Failure",D="1",se="Upstash-Workflow-Sdk-Version",_e="application/json";var Ae=["Initial","Run","SleepFor","SleepUntil","Call"];var We=async(r,e)=>{let t=ne("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)},G=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(B),l=r.headers.get("Upstash-Workflow-StepId"),u=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),m=r.headers.get("Upstash-Workflow-Concurrent"),p=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&u&&Ae.includes(c)&&m&&p))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:u,stepType:c,concurrentString:m,contentType:p})}`);let w=G(r.headers),f=ne("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:u,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}`))}},ne=(r,e,t,s,n,o)=>{let i={[Le]:r,[B]:e,[qe]:t,[`Upstash-Forward-${se}`]:D,...o?{[`Upstash-Failure-Callback-Forward-${re}`]:"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(([u,c])=>[`Upstash-Forward-${u}`,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??_e,"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}
|
|
2
|
+
`).filter(Boolean);for(let c of u)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 V({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new Q({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 x=(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}=x({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?x({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},u="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...u?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[u?"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"){Xe(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ze(s),a=n?x({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 Xe(r,e,t,s){if(s){let n=x({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 Ze(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 et=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function v(r){let e=[...r.keys()].filter(t=>!et(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 H(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 F(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",tt=21;function Ie(){return[...crypto.getRandomValues(new Uint8Array(tt))].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=H(e),s=F(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 rt={withStackTrace:!1},Ue=(r,e,t=rt)=>{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{u(s.next(c))}catch(m){i(m)}}function l(c){try{u(s.throw(c))}catch(m){i(m)}}function u(c){c.done?o(c.value):n(c.value).then(a,l)}u((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 st(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(p){s[p]&&(n[p]=function(w){return new Promise(function(f,g){o.push([p,w,f,g])>1||a(p,w)})})}function a(p,w){try{l(s[p](w))}catch(f){m(o[0][3],f)}}function l(p){p.value instanceof E?Promise.resolve(p.value.v).then(u,c):m(o[0][2],p)}function u(p){a("next",p)}function c(p){a("throw",p)}function m(p,w){p(w),o.shift(),o.length&&a(o[0][0],o[0][1])}}function nt(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 ot(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(u){o({value:u,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 it(e)}static combineWithAllErrors(e){return at(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 st(this,arguments,function*(){return yield E(yield E(yield*nt(ot(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))),At=k.fromPromise,Wt=k.fromSafePromise,Ht=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},it=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},at=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}},Ft=we.fromThrowable;var B="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",re="Upstash-Workflow-Is-Failure",D="1",se="Upstash-Workflow-Sdk-Version",_e="application/json";var Ae=["Initial","Run","SleepFor","SleepUntil","Call"];var We=async(r,e)=>{let t=ne("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)},G=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(B),l=r.headers.get("Upstash-Workflow-StepId"),u=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),m=r.headers.get("Upstash-Workflow-Concurrent"),p=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&u&&Ae.includes(c)&&m&&p))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:u,stepType:c,concurrentString:m,contentType:p})}`);let w=G(r.headers),f=ne("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:u,stepType:c,out:atob(i.body),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}`))}},ne=(r,e,t,s,n,o)=>{let i={[Le]:r,[B]:e,[qe]:t,[`Upstash-Forward-${se}`]:D,...o?{[`Upstash-Failure-Callback-Forward-${re}`]:"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(([u,c])=>[`Upstash-Forward-${u}`,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??_e,"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
|
|
package/dist/hono/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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 W(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 A(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"),A(e),W(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"),A(e),W(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),A(s),W(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))),Gt=k.fromPromise,$t=k.fromSafePromise,Jt=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}},Qt=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",We="application/json";var Ae=["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&&Ae.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??We,"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}
|
|
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 W(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 A(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"),A(e),W(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"),A(e),W(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),A(s),W(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))),Gt=k.fromPromise,$t=k.fromSafePromise,Jt=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}},Qt=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",We="application/json";var Ae=["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&&Ae.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:atob(i.body),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??We,"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
|
|
package/dist/nextjs/index.d.mts
CHANGED
|
@@ -1648,6 +1648,7 @@ declare function verifySignatureAppRouter(handler: ((request: Request, params?:
|
|
|
1648
1648
|
* @param options workflow options
|
|
1649
1649
|
* @returns
|
|
1650
1650
|
*/
|
|
1651
|
-
declare const serve: <TInitialPayload = unknown>(routeFunction: RouteFunction<TInitialPayload>, options?: Omit<WorkflowServeOptions<NextResponse, TInitialPayload>, "onStepFinish">) => ((request:
|
|
1651
|
+
declare const serve: <TInitialPayload = unknown>(routeFunction: RouteFunction<TInitialPayload>, options?: Omit<WorkflowServeOptions<NextResponse, TInitialPayload>, "onStepFinish">) => ((request: Request) => Promise<NextResponse>);
|
|
1652
|
+
declare const servePagesRouter: <TInitialPayload = unknown>(routeFunction: RouteFunction<TInitialPayload>, options?: Omit<WorkflowServeOptions<Response, TInitialPayload>, "onStepFinish">) => NextApiHandler;
|
|
1652
1653
|
|
|
1653
|
-
export { type VerifySignatureConfig, serve, verifySignature, verifySignatureAppRouter, verifySignatureEdge };
|
|
1654
|
+
export { type VerifySignatureConfig, serve, servePagesRouter, verifySignature, verifySignatureAppRouter, verifySignatureEdge };
|
package/dist/nextjs/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{NextResponse as K}from"next/server";import*as
|
|
2
|
-
`).filter(Boolean);for(let c of u)if(c.startsWith("data: ")){let d=c.slice(6);if(d==="[DONE]")break;yield JSON.parse(d)}}}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 V({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 C=(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 X=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}=C({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?C({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},u="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...u?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[u?"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"){Xe(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ze(s),a=n?C({name:n.name,token:n.token},i,o,"custom"):void 0;a?(xe(e,a),r.url=a.baseURL):(r.url=`${o}/v1/chat/completions`,e.set("Authorization",`Bearer ${i}`))}function Xe(r,e,t,s){if(s){let n=C({name:s.name,token:s.token},String(t.authorization).split("Bearer ")[1],r.api?.provider?.baseUrl,"upstash");xe(e,n),r.url=n.baseURL}else r.api={name:"llm"}}function Ze(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 xe(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 Z=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 et=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function E(r){let e=[...r.keys()].filter(t=>!et(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 H(r){let e=E(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 F(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ie="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",tt=21;function Ce(){return[...crypto.getRandomValues(new Uint8Array(tt))].map(r=>Ie[r%Ie.length]).join("")}var ee=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=H(e),s=F(e);return await this.http.request({path:["v2","enqueue",this.queueName,s],body:e.body,headers:t,method:"POST"})}async enqueueJSON(e){let t=E(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 te=class{http;constructor(e){this.http=e}async create(e){let t=E(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 re=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 N=class{http;token;constructor(e){this.http=new Y({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 re(this.http)}get topics(){return this.urlGroups}get dlq(){return new J(this.http)}get messages(){return new Z(this.http)}get schedules(){return new te(this.http)}get workflow(){return new se(this.http)}queue(e){return new ee(this.http,e?.queueName)}chat(){return new X(this.http,this.token)}async publish(e){let t=H(e);return await this.http.request({path:["v2","publish",F(e)],body:e.body,headers:t,method:"POST"})}async publishJSON(e){let t=E(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=H(o),a=Object.fromEntries(i.entries());t.push({destination:F(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 rt={withStackTrace:!1},Ue=(r,e,t=rt)=>{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{u(s.next(c))}catch(d){i(d)}}function l(c){try{u(s.throw(c))}catch(d){i(d)}}function u(c){c.done?o(c.value):n(c.value).then(a,l)}u((s=s.apply(r,[])).next())})}function Ne(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 x(r){return this instanceof x?(this.v=r,this):new x(r)}function st(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(p){s[p]&&(n[p]=function(w){return new Promise(function(f,g){o.push([p,w,f,g])>1||a(p,w)})})}function a(p,w){try{l(s[p](w))}catch(f){d(o[0][3],f)}}function l(p){p.value instanceof x?Promise.resolve(p.value.v).then(u,c):d(o[0][2],p)}function u(p){a("next",p)}function c(p){a("throw",p)}function d(p,w){p(w),o.shift(),o.length&&a(o[0][0],o[0][1])}}function nt(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:x(r[n](i)),done:n==="return"}:o?o(i):i}:o}}function ot(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 Ne=="function"?Ne(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(u){o({value:u,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 R(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 R(t?t(n):n)}}))}static combine(e){return it(e)}static combineWithAllErrors(e){return at(e)}map(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?new R(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 R(t.error);let s=yield e(t.value);return s.isErr()?new R(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 R(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 R(yield e(t.error))})))}andThen(e){return new r(this._promise.then(t=>{if(t.isErr())return new R(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 st(this,arguments,function*(){return yield x(yield x(yield*nt(ot(yield x(this._promise.then(t=>t.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}};var we=r=>new k(Promise.resolve(new R(r))),$t=k.fromPromise,Qt=k.fromSafePromise,Jt=k.fromThrowable,Oe=r=>{let e=m([]);for(let t of r)if(t.isErr()){e=y(t.error);break}else e.map(s=>s.push(t.value));return e},it=r=>k.fromSafePromise(Promise.all(r)).andThen(Oe),qe=r=>{let e=m([]);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},at=r=>k.fromSafePromise(Promise.all(r)).andThen(qe),Re;(function(r){function e(n,o){return(...i)=>{try{let a=n(...i);return m(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 qe(n)}r.combineWithAllErrors=s})(Re||(Re={}));var m=r=>new T(r);function y(r){return new R(r)}var T=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return m(e(this.value))}mapErr(e){return m(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 m(this.value)}orElse(e){return m(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)}},R=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 we(this.error)}asyncAndThrough(e){return we(this.error)}asyncMap(e){return we(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}},Vt=Re.fromThrowable;var B="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",_e="Upstash-Workflow-Url",ne="Upstash-Workflow-Is-Failure",D="1",oe="Upstash-Workflow-Sdk-Version",Ae="application/json";var We=["Initial","Run","SleepFor","SleepUntil","Call"];var He=async(r,e)=>{let t=ie("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}),m("success")}catch(s){return y(s)}},Fe=async({onCleanup:r,onStep:e})=>{try{return await e(),await r(),m("workflow-finished")}catch(t){let s=t;return s instanceof b?m("step-finished"):y(s)}},Be=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)},G=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},De=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),m("call-will-retry");let a=r.headers.get(B),l=r.headers.get("Upstash-Workflow-StepId"),u=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),d=r.headers.get("Upstash-Workflow-Concurrent"),p=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&u&&We.includes(c)&&d&&p))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:u,stepType:c,concurrentString:d,contentType:p})}`);let w=G(r.headers),f=ie("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:u,stepType:c,out:Buffer.from(i.body,"base64").toString(),concurrent:Number(d)};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}),m("is-call-return")}else return m("continue-workflow")}catch(i){let a=r.headers.get("Upstash-Workflow-Callback");return y(new h(`Error when handling call return (isCallReturn=${a}): ${i}`))}},ie=(r,e,t,s,n,o)=>{let i={[Le]:r,[B]:e,[_e]:t,[`Upstash-Forward-${oe}`]:D,...o?{[`Upstash-Failure-Callback-Forward-${ne}`]:"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(([u,c])=>[`Upstash-Forward-${u}`,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},Ge=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 h(`Failed to verify that the Workflow request comes from QStash: ${s}
|
|
1
|
+
import{NextResponse as K}from"next/server";import*as Ee from"jose";import Pe from"crypto-js";var _=class extends Error{constructor(e){super(e),this.name="SignatureError"}},v=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 Ee.jwtVerify(t.signature,new TextEncoder().encode(e),{issuer:"Upstash",clockTolerance:t.clockTolerance}).catch(a=>{throw new _(a.message)})).payload;if(t.url!==void 0&&n.sub!==t.url)throw new _(`invalid subject: ${n.sub}, want: ${t.url}`);let o=Pe.SHA256(t.body).toString(Pe.enc.Base64url),i=new RegExp(/=+$/);if(n.body.replace(i,"")!==o.replace(i,""))throw new _(`body hash does not match, want: ${n.body}, got: ${o}`);return!0}};var J=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"}},V=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"}},h=class extends P{constructor(e){super(e),this.name="QStashWorkflowError"}},b=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}},xe=r=>r instanceof Error?{error:r.name,message:r.message}:{error:"Error",message:"An error occured while executing workflow."};var Y=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 u=o.decode(a,{stream:!0}).split(`
|
|
2
|
+
`).filter(Boolean);for(let c of u)if(c.startsWith("data: ")){let d=c.slice(6);if(d==="[DONE]")break;yield JSON.parse(d)}}}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 V({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 C=(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 X=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}=C({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?C({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},u="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...u?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[u?"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"){Xe(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ze(s),a=n?C({name:n.name,token:n.token},i,o,"custom"):void 0;a?(Ie(e,a),r.url=a.baseURL):(r.url=`${o}/v1/chat/completions`,e.set("Authorization",`Bearer ${i}`))}function Xe(r,e,t,s){if(s){let n=C({name:s.name,token:s.token},String(t.authorization).split("Bearer ")[1],r.api?.provider?.baseUrl,"upstash");Ie(e,n),r.url=n.baseURL}else r.api={name:"llm"}}function Ze(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 Ie(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 Z=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 et=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function E(r){let e=[...r.keys()].filter(t=>!et(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 H(r){let e=E(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 F(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",tt=21;function Ne(){return[...crypto.getRandomValues(new Uint8Array(tt))].map(r=>Ce[r%Ce.length]).join("")}var ee=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=H(e),s=F(e);return await this.http.request({path:["v2","enqueue",this.queueName,s],body:e.body,headers:t,method:"POST"})}async enqueueJSON(e){let t=E(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 te=class{http;constructor(e){this.http=e}async create(e){let t=E(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 re=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 N=class{http;token;constructor(e){this.http=new Y({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 re(this.http)}get topics(){return this.urlGroups}get dlq(){return new J(this.http)}get messages(){return new Z(this.http)}get schedules(){return new te(this.http)}get workflow(){return new se(this.http)}queue(e){return new ee(this.http,e?.queueName)}chat(){return new X(this.http,this.token)}async publish(e){let t=H(e);return await this.http.request({path:["v2","publish",F(e)],body:e.body,headers:t,method:"POST"})}async publishJSON(e){let t=E(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=H(o),a=Object.fromEntries(i.entries());t.push({destination:F(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 rt={withStackTrace:!1},Oe=(r,e,t=rt)=>{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{u(s.next(c))}catch(d){i(d)}}function l(c){try{u(s.throw(c))}catch(d){i(d)}}function u(c){c.done?o(c.value):n(c.value).then(a,l)}u((s=s.apply(r,[])).next())})}function Ue(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 x(r){return this instanceof x?(this.v=r,this):new x(r)}function st(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(p){s[p]&&(n[p]=function(w){return new Promise(function(f,g){o.push([p,w,f,g])>1||a(p,w)})})}function a(p,w){try{l(s[p](w))}catch(f){d(o[0][3],f)}}function l(p){p.value instanceof x?Promise.resolve(p.value.v).then(u,c):d(o[0][2],p)}function u(p){a("next",p)}function c(p){a("throw",p)}function d(p,w){p(w),o.shift(),o.length&&a(o[0][0],o[0][1])}}function nt(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:x(r[n](i)),done:n==="return"}:o?o(i):i}:o}}function ot(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 Ue=="function"?Ue(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(u){o({value:u,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 R(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 R(t?t(n):n)}}))}static combine(e){return it(e)}static combineWithAllErrors(e){return at(e)}map(e){return new r(this._promise.then(t=>U(this,void 0,void 0,function*(){return t.isErr()?new R(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 R(t.error);let s=yield e(t.value);return s.isErr()?new R(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 R(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 R(yield e(t.error))})))}andThen(e){return new r(this._promise.then(t=>{if(t.isErr())return new R(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 st(this,arguments,function*(){return yield x(yield x(yield*nt(ot(yield x(this._promise.then(t=>t.safeUnwrap()))))))})}then(e,t){return this._promise.then(e,t)}};var we=r=>new k(Promise.resolve(new R(r))),$t=k.fromPromise,Qt=k.fromSafePromise,Jt=k.fromThrowable,qe=r=>{let e=m([]);for(let t of r)if(t.isErr()){e=y(t.error);break}else e.map(s=>s.push(t.value));return e},it=r=>k.fromSafePromise(Promise.all(r)).andThen(qe),Le=r=>{let e=m([]);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},at=r=>k.fromSafePromise(Promise.all(r)).andThen(Le),Re;(function(r){function e(n,o){return(...i)=>{try{let a=n(...i);return m(a)}catch(a){return y(o?o(a):a)}}}r.fromThrowable=e;function t(n){return qe(n)}r.combine=t;function s(n){return Le(n)}r.combineWithAllErrors=s})(Re||(Re={}));var m=r=>new T(r);function y(r){return new R(r)}var T=class{constructor(e){this.value=e}isOk(){return!0}isErr(){return!this.isOk()}map(e){return m(e(this.value))}mapErr(e){return m(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 m(this.value)}orElse(e){return m(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 Oe("Called `_unsafeUnwrapErr` on an Ok",this,e)}},R=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 we(this.error)}asyncAndThrough(e){return we(this.error)}asyncMap(e){return we(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 Oe("Called `_unsafeUnwrap` on an Err",this,e)}_unsafeUnwrapErr(e){return this.error}},Vt=Re.fromThrowable;var B="Upstash-Workflow-RunId",_e="Upstash-Workflow-Init",Ae="Upstash-Workflow-Url",ne="Upstash-Workflow-Is-Failure",D="1",oe="Upstash-Workflow-Sdk-Version",We="application/json";var He=["Initial","Run","SleepFor","SleepUntil","Call"];var Fe=async(r,e)=>{let t=ie("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}),m("success")}catch(s){return y(s)}},Be=async({onCleanup:r,onStep:e})=>{try{return await e(),await r(),m("workflow-finished")}catch(t){let s=t;return s instanceof b?m("step-finished"):y(s)}},De=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)},G=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},Ge=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),m("call-will-retry");let a=r.headers.get(B),l=r.headers.get("Upstash-Workflow-StepId"),u=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),d=r.headers.get("Upstash-Workflow-Concurrent"),p=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&u&&He.includes(c)&&d&&p))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:u,stepType:c,concurrentString:d,contentType:p})}`);let w=G(r.headers),f=ie("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:u,stepType:c,out:atob(i.body),concurrent:Number(d)};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}),m("is-call-return")}else return m("continue-workflow")}catch(i){let a=r.headers.get("Upstash-Workflow-Callback");return y(new h(`Error when handling call return (isCallReturn=${a}): ${i}`))}},ie=(r,e,t,s,n,o)=>{let i={[_e]:r,[B]:e,[Ae]:t,[`Upstash-Forward-${oe}`]:D,...o?{[`Upstash-Failure-Callback-Forward-${ne}`]:"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(([u,c])=>[`Upstash-Forward-${u}`,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??We,"Upstash-Workflow-CallType":"toCallback"}}return i},Ke=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 h(`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}},ut=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}},ue=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}}},pe=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})}},ce=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})}},de=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 I=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:u,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=u??JSON.stringify(this.requestPayload),this.env=c??{},this.executor=new le(this,this.steps,a)}async run(e,t){let s=()=>this.executor.wrapStep(e,t);return this.addStep(new ue(e,s))}async sleep(e,t){await this.addStep(new pe(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 ce(e,s))}async call(e,t,s,n,o){return await this.addStep(new de(e,t,s,n,o??{}))}async addStep(e){return await this.executor.addStep(e)}},he=class r extends I{static disabledMessage="disabled-qstash-worklfow-run";async addStep(e){throw new b(r.disabledMessage)}static async tryAuthentication(e,t){let s=new r({qstashClient:new N({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 b&&n.stepName===this.disabledMessage?m("step-found"):y(n)}return m("run-ended")}};var Ke=["DEBUG","INFO","SUBMIT","WARN","ERROR"],me=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 Ke.indexOf(e)>=Ke.indexOf(this.options.logLevel)}static getLogger(e){return typeof e=="object"?e:e?new r({logLevel:"INFO",logOutput:"console"}):void 0}};var Me=async r=>{try{return await r.text()}catch{return}},pt=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}},ct=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},dt=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(oe),t=!e;if(!t&&e!==D)throw new h(`Incompatible workflow sdk protocol version. Expected ${D}, got ${e} from the request.`);let s=t?`wfr_${Ce()}`:r.headers.get(B)??"";if(s.length===0)throw new h("Couldn't get workflow id from header");return{isFirstInvocation:t,workflowRunId:s}},Te=async(r,e,t)=>{if(e)return{rawInitialPayload:r??"",steps:[],isLastDuplicate:!1};{if(!r)throw new h("Only first call can have an empty body");let{rawInitialPayload:s,steps:n}=pt(r),o=await dt(n,t),i=ct(n);return{rawInitialPayload:s,steps:i,isLastDuplicate:o}}},Qe=async(r,e,t,s,n,o)=>{if(r.headers.get(ne)!=="true")return m("not-failure-callback");if(!n)return y(new h("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:u,sourceHeader:c,sourceBody:d,workflowRunId:p}=JSON.parse(e),w=l?atob(l):"{}",f=JSON.parse(w),{rawInitialPayload:g,steps:S,isLastDuplicate:fe}=await Te(atob(d),!1,o),q=new I({qstashClient:t,workflowRunId:p,initialPayload:s(g),rawInitialPayload:g,headers:G(new Headers(c)),steps:S,url:u,failureUrl:u,debug:o});await n(q,i,f.message,a)}catch(i){return y(i)}return m("is-failure-callback")};var ht=r=>{let e=r?.env??(typeof process>"u"?{}:process.env),t=!!(e.QSTASH_CURRENT_SIGNING_KEY&&e.QSTASH_NEXT_SIGNING_KEY);return{qstashClient:new N({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 v({currentSigningKey:e.QSTASH_CURRENT_SIGNING_KEY,nextSigningKey:e.QSTASH_NEXT_SIGNING_KEY}):void 0,baseUrl:e.UPSTASH_WORKFLOW_URL,env:e,...r}},Je=(r,e)=>{let{qstashClient:t,onStepFinish:s,initialPayloadParser:n,url:o,verbose:i,receiver:a,failureUrl:l,failureFunction:u,baseUrl:c,env:d}=ht(e),p=me.getLogger(i),w=async f=>{let g=o??f.url,S=c?g.replace(/^(https?:\/\/[^/]+)(\/.*)?$/,(Q,mt,Ye)=>c+(Ye||"")):g;S!==g&&await p?.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 fe=u?S:l,q=await Me(f)??"";await Ge(q,f.headers.get("upstash-signature"),a),await p?.log("INFO","ENDPOINT_START");let ye=await Qe(f,q,t,n,u);if(ye.isErr())throw ye.error;if(ye.value==="is-failure-callback")return await p?.log("WARN","RESPONSE_DEFAULT","failureFunction executed"),s("no-workflow-id","failure-callback");let{isFirstInvocation:Se,workflowRunId:ke}=$e(f);p?.setWorkflowRunId(ke);let{rawInitialPayload:ge,steps:je,isLastDuplicate:ze}=await Te(q,Se,p);if(ze)return s("no-workflow-id","duplicate-step");let L=new I({qstashClient:t,workflowRunId:ke,initialPayload:n(ge),rawInitialPayload:ge,headers:G(f.headers),steps:je,url:S,failureUrl:fe,debug:p,env:d}),M=await he.tryAuthentication(r,L);if(M.isErr())throw await p?.log("ERROR","ERROR",{error:M.error.message}),M.error;if(M.value==="run-ended")return s("no-workflow-id","auth-fail");let $=await De(f,ge,t,S,fe,p);if($.isErr())throw await p?.log("ERROR","SUBMIT_THIRD_PARTY_RESULT",{error:$.error.message}),$.error;if($.value==="continue-workflow"){let Q=Se?await He(L,p):await Fe({onStep:async()=>r(L),onCleanup:async()=>{await Be(L,p)}});if(Q.isErr())throw await p?.log("ERROR","ERROR",{error:Q.error.message}),Q.error;return await p?.log("INFO","RESPONSE_WORKFLOW"),s(L.workflowRunId,"success")}return await p?.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(Ee(g)),{status:500})}}};var se=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 Ve=400;function Hr(r,e){let t=e?.currentSigningKey??process.env.QSTASH_CURRENT_SIGNING_KEY;if(!t)throw new Error("currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY");let s=e?.nextSigningKey??process.env.QSTASH_NEXT_SIGNING_KEY;if(!s)throw new Error("nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY");let n=new v({currentSigningKey:t,nextSigningKey:s});return async(o,i)=>{let a=o.headers["upstash-signature"];if(!a){i.status(Ve),i.send("`Upstash-Signature` header is missing"),i.end();return}if(typeof a!="string")throw new TypeError("`Upstash-Signature` header is not a string");let l=[];for await(let d of o)l.push(typeof d=="string"?Buffer.from(d):d);let u=Buffer.concat(l).toString("utf8");if(!await n.verify({signature:a,body:u,clockTolerance:e?.clockTolerance})){i.status(Ve),i.send("Invalid signature"),i.end();return}try{o.body=o.headers["content-type"]==="application/json"?JSON.parse(u):u}catch{o.body=u}return r(o,i)}}function Fr(r,e){let t=e?.currentSigningKey??process.env.QSTASH_CURRENT_SIGNING_KEY;if(!t)throw new Error("currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY");let s=e?.nextSigningKey??process.env.QSTASH_NEXT_SIGNING_KEY;if(!s)throw new Error("nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY");let n=new v({currentSigningKey:t,nextSigningKey:s});return async(o,i)=>{let a=o.clone(),l=o.headers.get("upstash-signature");if(!l)return new K(new TextEncoder().encode("`Upstash-Signature` header is missing"),{status:403});if(typeof l!="string")throw new TypeError("`Upstash-Signature` header is not a string");let u=await a.text();return await n.verify({signature:l,body:u,clockTolerance:e?.clockTolerance})?r(o,i):new K(new TextEncoder().encode("invalid signature"),{status:403})}}function Br(r,e){let t=e?.currentSigningKey??process.env.QSTASH_CURRENT_SIGNING_KEY;if(!t)throw new Error("currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY");let s=e?.nextSigningKey??process.env.QSTASH_NEXT_SIGNING_KEY;if(!s)throw new Error("nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY");let n=new v({currentSigningKey:t,nextSigningKey:s});return async(o,i)=>{let a=o.clone(),l=o.headers.get("upstash-signature");if(!l)return new K(new TextEncoder().encode("`Upstash-Signature` header is missing"),{status:403});if(typeof l!="string")throw new TypeError("`Upstash-Signature` header is not a string");let u=await a.text();return await n.verify({signature:l,body:u,clockTolerance:e?.clockTolerance})?r(o,i):new K(new TextEncoder().encode("invalid signature"),{status:403})}}var Dr=(r,e)=>{let t=Je(r,{onStepFinish:s=>new K(JSON.stringify({workflowRunId:s}),{status:200}),...e});return async s=>await t(s)};export{Dr as serve,Hr as verifySignature,Br as verifySignatureAppRouter,Fr as verifySignatureEdge};
|
|
10
|
+
Step Types expected: ${JSON.stringify(n)}`)}throw t}},ut=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}},ue=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}}},pe=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})}},ce=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})}},de=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 I=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:u,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=u??JSON.stringify(this.requestPayload),this.env=c??{},this.executor=new le(this,this.steps,a)}async run(e,t){let s=()=>this.executor.wrapStep(e,t);return this.addStep(new ue(e,s))}async sleep(e,t){await this.addStep(new pe(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 ce(e,s))}async call(e,t,s,n,o){return await this.addStep(new de(e,t,s,n,o??{}))}async addStep(e){return await this.executor.addStep(e)}},he=class r extends I{static disabledMessage="disabled-qstash-worklfow-run";async addStep(e){throw new b(r.disabledMessage)}static async tryAuthentication(e,t){let s=new r({qstashClient:new N({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 b&&n.stepName===this.disabledMessage?m("step-found"):y(n)}return m("run-ended")}};var Me=["DEBUG","INFO","SUBMIT","WARN","ERROR"],me=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 $e=async r=>{try{return await r.text()}catch{return}},pt=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}},ct=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},dt=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},Qe=r=>{let e=r.headers.get(oe),t=!e;if(!t&&e!==D)throw new h(`Incompatible workflow sdk protocol version. Expected ${D}, got ${e} from the request.`);let s=t?`wfr_${Ne()}`:r.headers.get(B)??"";if(s.length===0)throw new h("Couldn't get workflow id from header");return{isFirstInvocation:t,workflowRunId:s}},Te=async(r,e,t)=>{if(e)return{rawInitialPayload:r??"",steps:[],isLastDuplicate:!1};{if(!r)throw new h("Only first call can have an empty body");let{rawInitialPayload:s,steps:n}=pt(r),o=await dt(n,t),i=ct(n);return{rawInitialPayload:s,steps:i,isLastDuplicate:o}}},Je=async(r,e,t,s,n,o)=>{if(r.headers.get(ne)!=="true")return m("not-failure-callback");if(!n)return y(new h("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:u,sourceHeader:c,sourceBody:d,workflowRunId:p}=JSON.parse(e),w=l?atob(l):"{}",f=JSON.parse(w),{rawInitialPayload:g,steps:S,isLastDuplicate:fe}=await Te(atob(d),!1,o),q=new I({qstashClient:t,workflowRunId:p,initialPayload:s(g),rawInitialPayload:g,headers:G(new Headers(c)),steps:S,url:u,failureUrl:u,debug:o});await n(q,i,f.message,a)}catch(i){return y(i)}return m("is-failure-callback")};var ht=r=>{let e=r?.env??(typeof process>"u"?{}:process.env),t=!!(e.QSTASH_CURRENT_SIGNING_KEY&&e.QSTASH_NEXT_SIGNING_KEY);return{qstashClient:new N({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 v({currentSigningKey:e.QSTASH_CURRENT_SIGNING_KEY,nextSigningKey:e.QSTASH_NEXT_SIGNING_KEY}):void 0,baseUrl:e.UPSTASH_WORKFLOW_URL,env:e,...r}},Se=(r,e)=>{let{qstashClient:t,onStepFinish:s,initialPayloadParser:n,url:o,verbose:i,receiver:a,failureUrl:l,failureFunction:u,baseUrl:c,env:d}=ht(e),p=me.getLogger(i),w=async f=>{let g=o??f.url,S=c?g.replace(/^(https?:\/\/[^/]+)(\/.*)?$/,(Q,mt,Ye)=>c+(Ye||"")):g;S!==g&&await p?.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 fe=u?S:l,q=await $e(f)??"";await Ke(q,f.headers.get("upstash-signature"),a),await p?.log("INFO","ENDPOINT_START");let ye=await Je(f,q,t,n,u);if(ye.isErr())throw ye.error;if(ye.value==="is-failure-callback")return await p?.log("WARN","RESPONSE_DEFAULT","failureFunction executed"),s("no-workflow-id","failure-callback");let{isFirstInvocation:ke,workflowRunId:ve}=Qe(f);p?.setWorkflowRunId(ve);let{rawInitialPayload:ge,steps:je,isLastDuplicate:ze}=await Te(q,ke,p);if(ze)return s("no-workflow-id","duplicate-step");let L=new I({qstashClient:t,workflowRunId:ve,initialPayload:n(ge),rawInitialPayload:ge,headers:G(f.headers),steps:je,url:S,failureUrl:fe,debug:p,env:d}),M=await he.tryAuthentication(r,L);if(M.isErr())throw await p?.log("ERROR","ERROR",{error:M.error.message}),M.error;if(M.value==="run-ended")return s("no-workflow-id","auth-fail");let $=await Ge(f,ge,t,S,fe,p);if($.isErr())throw await p?.log("ERROR","SUBMIT_THIRD_PARTY_RESULT",{error:$.error.message}),$.error;if($.value==="continue-workflow"){let Q=ke?await Fe(L,p):await Be({onStep:async()=>r(L),onCleanup:async()=>{await De(L,p)}});if(Q.isErr())throw await p?.log("ERROR","ERROR",{error:Q.error.message}),Q.error;return await p?.log("INFO","RESPONSE_WORKFLOW"),s(L.workflowRunId,"success")}return await p?.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(xe(g)),{status:500})}}};var se=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 Ve=400;function Hr(r,e){let t=e?.currentSigningKey??process.env.QSTASH_CURRENT_SIGNING_KEY;if(!t)throw new Error("currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY");let s=e?.nextSigningKey??process.env.QSTASH_NEXT_SIGNING_KEY;if(!s)throw new Error("nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY");let n=new v({currentSigningKey:t,nextSigningKey:s});return async(o,i)=>{let a=o.headers["upstash-signature"];if(!a){i.status(Ve),i.send("`Upstash-Signature` header is missing"),i.end();return}if(typeof a!="string")throw new TypeError("`Upstash-Signature` header is not a string");let l=[];for await(let d of o)l.push(typeof d=="string"?Buffer.from(d):d);let u=Buffer.concat(l).toString("utf8");if(!await n.verify({signature:a,body:u,clockTolerance:e?.clockTolerance})){i.status(Ve),i.send("Invalid signature"),i.end();return}try{o.body=o.headers["content-type"]==="application/json"?JSON.parse(u):u}catch{o.body=u}return r(o,i)}}function Fr(r,e){let t=e?.currentSigningKey??process.env.QSTASH_CURRENT_SIGNING_KEY;if(!t)throw new Error("currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY");let s=e?.nextSigningKey??process.env.QSTASH_NEXT_SIGNING_KEY;if(!s)throw new Error("nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY");let n=new v({currentSigningKey:t,nextSigningKey:s});return async(o,i)=>{let a=o.clone(),l=o.headers.get("upstash-signature");if(!l)return new K(new TextEncoder().encode("`Upstash-Signature` header is missing"),{status:403});if(typeof l!="string")throw new TypeError("`Upstash-Signature` header is not a string");let u=await a.text();return await n.verify({signature:l,body:u,clockTolerance:e?.clockTolerance})?r(o,i):new K(new TextEncoder().encode("invalid signature"),{status:403})}}function Br(r,e){let t=e?.currentSigningKey??process.env.QSTASH_CURRENT_SIGNING_KEY;if(!t)throw new Error("currentSigningKey is required, either in the config or as env variable QSTASH_CURRENT_SIGNING_KEY");let s=e?.nextSigningKey??process.env.QSTASH_NEXT_SIGNING_KEY;if(!s)throw new Error("nextSigningKey is required, either in the config or as env variable QSTASH_NEXT_SIGNING_KEY");let n=new v({currentSigningKey:t,nextSigningKey:s});return async(o,i)=>{let a=o.clone(),l=o.headers.get("upstash-signature");if(!l)return new K(new TextEncoder().encode("`Upstash-Signature` header is missing"),{status:403});if(typeof l!="string")throw new TypeError("`Upstash-Signature` header is not a string");let u=await a.text();return await n.verify({signature:l,body:u,clockTolerance:e?.clockTolerance})?r(o,i):new K(new TextEncoder().encode("invalid signature"),{status:403})}}var Dr=(r,e)=>{let t=Se(r,{onStepFinish:s=>new K(JSON.stringify({workflowRunId:s}),{status:200}),...e});return async s=>await t(s)},Gr=(r,e)=>{let t=Se(r,e);return async(s,n)=>{if(s.method?.toUpperCase()!=="POST"){n.status(405).json("Only POST requests are allowed in worklfows");return}else if(!s.url){n.status(400).json("url not found in the request");return}let o=s.headers["x-forwarded-proto"],i=e?.baseUrl??`${o}://${s.headers.host}`,a=new Request(e?.url??`${i}${s.url}`,{body:JSON.stringify(s.body)??"",headers:new Headers(s.headersDistinct),method:"POST"}),l=await t(a);n.status(l.status).json(await l.json())}};export{Dr as serve,Gr as servePagesRouter,Hr as verifySignature,Br as verifySignatureAppRouter,Fr as verifySignatureEdge};
|
package/dist/solidjs/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import*as Pe from"jose";import ke from"crypto-js";var A=class extends Error{constructor(e){super(e),this.name="SignatureError"}},I=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 A(a.message)})).payload;if(t.url!==void 0&&n.sub!==t.url)throw new A(`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 A(`body hash does not match, want: ${n.body}, got: ${o}`);return!0}};var K=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"}},Q=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"]}},V=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 z=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 V({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new Q({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 x=(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}=x({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?x({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 W(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){ze(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ye(s),a=n?x({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 ze(r,e,t,s){if(s){let n=x({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 _(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 H(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 F(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=H(e),s=F(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"),_(e),W(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 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))),Nt=k.fromPromise,Lt=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}},At=we.fromThrowable;var B="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",re="Upstash-Workflow-Is-Failure",D="1",se="Upstash-Workflow-Sdk-Version",Ae="application/json";var We=["Initial","Run","SleepFor","SleepUntil","Call"];var _e=async(r,e)=>{let t=ne("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)},M=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(B),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=M(r.headers),f=ne("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}`))}},ne=(r,e,t,s,n,o)=>{let i={[Le]:r,[B]:e,[qe]:t,[`Upstash-Forward-${se}`]:D,...o?{[`Upstash-Failure-Callback-Forward-${re}`]:"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}
|
|
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 V({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new Q({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 x=(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}=x({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?x({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 W(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){ze(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ye(s),a=n?x({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 ze(r,e,t,s){if(s){let n=x({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 _(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 H(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 F(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=H(e),s=F(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"),_(e),W(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 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))),Nt=k.fromPromise,Lt=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}},At=we.fromThrowable;var B="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",re="Upstash-Workflow-Is-Failure",D="1",se="Upstash-Workflow-Sdk-Version",Ae="application/json";var We=["Initial","Run","SleepFor","SleepUntil","Call"];var _e=async(r,e)=>{let t=ne("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)},M=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(B),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=M(r.headers),f=ne("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:p,stepType:c,out:atob(i.body),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}`))}},ne=(r,e,t,s,n,o)=>{let i={[Le]:r,[B]:e,[qe]:t,[`Upstash-Forward-${se}`]:D,...o?{[`Upstash-Failure-Callback-Forward-${re}`]:"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
|
|
package/dist/svelte/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import*as Pe from"jose";import ke from"crypto-js";var W=class extends Error{constructor(e){super(e),this.name="SignatureError"}},I=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 W(a.message)})).payload;if(t.url!==void 0&&n.sub!==t.url)throw new W(`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 W(`body hash does not match, want: ${n.body}, got: ${o}`);return!0}};var K=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"}},Q=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"]}},V=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 z=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 u=o.decode(a,{stream:!0}).split(`
|
|
2
|
-
`).filter(Boolean);for(let c of u)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 V({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new Q({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 x=(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}=x({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?x({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},u="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...u?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[u?"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"){ze(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ye(s),a=n?x({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 ze(r,e,t,s){if(s){let n=x({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 _(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 H(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 F(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=H(e),s=F(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"),_(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 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{u(s.next(c))}catch(m){i(m)}}function l(c){try{u(s.throw(c))}catch(m){i(m)}}function u(c){c.done?o(c.value):n(c.value).then(a,l)}u((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(p){s[p]&&(n[p]=function(w){return new Promise(function(f,g){o.push([p,w,f,g])>1||a(p,w)})})}function a(p,w){try{l(s[p](w))}catch(f){m(o[0][3],f)}}function l(p){p.value instanceof E?Promise.resolve(p.value.v).then(u,c):m(o[0][2],p)}function u(p){a("next",p)}function c(p){a("throw",p)}function m(p,w){p(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(u){o({value:u,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))),Nt=k.fromPromise,qt=k.fromSafePromise,Lt=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}},Wt=we.fromThrowable;var B="Upstash-Workflow-RunId",qe="Upstash-Workflow-Init",Le="Upstash-Workflow-Url",re="Upstash-Workflow-Is-Failure",D="1",se="Upstash-Workflow-Sdk-Version",We="application/json";var Ae=["Initial","Run","SleepFor","SleepUntil","Call"];var _e=async(r,e)=>{let t=ne("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)},M=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(B),l=r.headers.get("Upstash-Workflow-StepId"),u=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),m=r.headers.get("Upstash-Workflow-Concurrent"),p=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&u&&Ae.includes(c)&&m&&p))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:u,stepType:c,concurrentString:m,contentType:p})}`);let w=M(r.headers),f=ne("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:u,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}`))}},ne=(r,e,t,s,n,o)=>{let i={[qe]:r,[B]:e,[Le]:t,[`Upstash-Forward-${se}`]:D,...o?{[`Upstash-Failure-Callback-Forward-${re}`]:"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(([u,c])=>[`Upstash-Forward-${u}`,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??We,"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}
|
|
2
|
+
`).filter(Boolean);for(let c of u)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 V({limit:e.headers.get("RateLimit-Limit"),remaining:e.headers.get("RateLimit-Remaining"),reset:e.headers.get("RateLimit-Reset")}):new Q({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 x=(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}=x({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?x({name:o.name,token:o.token},s,t,n):{defaultHeaders:void 0,baseURL:t},u="stream"in e&&e.stream,c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,...u?{Connection:"keep-alive",Accept:"text/event-stream","Cache-Control":"no-cache"}:{},...l.defaultHeaders};return await this.http[u?"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"){ze(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ye(s),a=n?x({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 ze(r,e,t,s){if(s){let n=x({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 _(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 H(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 F(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=H(e),s=F(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"),_(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 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{u(s.next(c))}catch(m){i(m)}}function l(c){try{u(s.throw(c))}catch(m){i(m)}}function u(c){c.done?o(c.value):n(c.value).then(a,l)}u((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(p){s[p]&&(n[p]=function(w){return new Promise(function(f,g){o.push([p,w,f,g])>1||a(p,w)})})}function a(p,w){try{l(s[p](w))}catch(f){m(o[0][3],f)}}function l(p){p.value instanceof E?Promise.resolve(p.value.v).then(u,c):m(o[0][2],p)}function u(p){a("next",p)}function c(p){a("throw",p)}function m(p,w){p(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(u){o({value:u,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))),Nt=k.fromPromise,qt=k.fromSafePromise,Lt=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}},Wt=we.fromThrowable;var B="Upstash-Workflow-RunId",qe="Upstash-Workflow-Init",Le="Upstash-Workflow-Url",re="Upstash-Workflow-Is-Failure",D="1",se="Upstash-Workflow-Sdk-Version",We="application/json";var Ae=["Initial","Run","SleepFor","SleepUntil","Call"];var _e=async(r,e)=>{let t=ne("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)},M=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(B),l=r.headers.get("Upstash-Workflow-StepId"),u=r.headers.get("Upstash-Workflow-StepName"),c=r.headers.get("Upstash-Workflow-StepType"),m=r.headers.get("Upstash-Workflow-Concurrent"),p=r.headers.get("Upstash-Workflow-ContentType");if(!(a&&l&&u&&Ae.includes(c)&&m&&p))throw new Error(`Missing info in callback message source header: ${JSON.stringify({workflowRunId:a,stepIdString:l,stepName:u,stepType:c,concurrentString:m,contentType:p})}`);let w=M(r.headers),f=ne("false",a,s,w,void 0,n),g={stepId:Number(l),stepName:u,stepType:c,out:atob(i.body),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}`))}},ne=(r,e,t,s,n,o)=>{let i={[qe]:r,[B]:e,[Le]:t,[`Upstash-Forward-${se}`]:D,...o?{[`Upstash-Failure-Callback-Forward-${re}`]:"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(([u,c])=>[`Upstash-Forward-${u}`,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??We,"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
|
|
package/dist/workflow/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
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 W(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){ze(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ve(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 ze(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 Ve(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 A(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 Ye=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function v(r){let e=[...r.keys()].filter(t=>!Ye(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 F(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",Xe=21;function Ie(){return[...crypto.getRandomValues(new Uint8Array(Xe))].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=F(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"),A(e),W(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",F(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"),A(e),W(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:F(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),A(s),W(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 Ze={withStackTrace:!1},Ue=(r,e,t=Ze)=>{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 et(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 tt(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 rt(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 st(e)}static combineWithAllErrors(e){return nt(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 et(this,arguments,function*(){return yield E(yield E(yield*tt(rt(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))),Mt=k.fromPromise,Gt=k.fromSafePromise,$t=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},st=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},nt=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}},Jt=we.fromThrowable;var H="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",se="Upstash-Workflow-Is-Failure",B="1",ne="Upstash-Workflow-Sdk-Version",We="application/json";var Ae=["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)}},Fe=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)}},He=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(H),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&&Ae.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,[H]: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??We,"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}
|
|
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 W(r,e,t){if(!r.api)return;let s=r.api.provider,n=r.api.analytics;if(s?.owner==="upstash"){ze(r,e,t,n);return}if(!("provider"in r.api))return;let{baseUrl:o,token:i}=Ve(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 ze(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 Ve(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 A(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 Ye=r=>{let e=r.toLowerCase();return e.startsWith("content-type")||e.startsWith("upstash-")};function v(r){let e=[...r.keys()].filter(t=>!Ye(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 F(r){return r.url??r.urlGroup??r.topic??`api/${r.api?.name}`}var Ce="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_",Xe=21;function Ie(){return[...crypto.getRandomValues(new Uint8Array(Xe))].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=F(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"),A(e),W(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",F(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"),A(e),W(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:F(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),A(s),W(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 Ze={withStackTrace:!1},Ue=(r,e,t=Ze)=>{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 et(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 tt(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 rt(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 st(e)}static combineWithAllErrors(e){return nt(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 et(this,arguments,function*(){return yield E(yield E(yield*tt(rt(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))),Mt=k.fromPromise,Gt=k.fromSafePromise,$t=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},st=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},nt=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}},Jt=we.fromThrowable;var H="Upstash-Workflow-RunId",Le="Upstash-Workflow-Init",qe="Upstash-Workflow-Url",se="Upstash-Workflow-Is-Failure",B="1",ne="Upstash-Workflow-Sdk-Version",We="application/json";var Ae=["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)}},Fe=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)}},He=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(H),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&&Ae.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:atob(i.body),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,[H]: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??We,"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
|
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "version": "v2.7.
|
|
1
|
+
{ "version": "v2.7.4", "name": "@upstash/qstash", "description": "Official Typescript client for QStash", "author": "Andreas Thomas <dev@chronark.com>", "license": "MIT", "homepage": "https://github.com/upstash/sdk-qstash-ts#readme", "repository": { "type": "git", "url": "git+https://github.com/upstash/sdk-qstash-ts.git" }, "bugs": { "url": "https://github.com/upstash/sdk-qstash-ts/issues" }, "files": [ "dist" ], "main": "./dist/base/index.mjs", "module": "./dist/base/index.mjs", "types": "./dist/base/index.d.mts", "exports": { ".": { "types": "./dist/base/index.d.mts", "import": "./dist/base/index.mjs", "require": "./dist/base/index.js" }, "./nextjs": { "import": "./dist/nextjs/index.mjs" }, "./dist/nextjs": { "import": "./dist/nextjs/index.mjs" }, "./h3": { "types": "./dist/h3/index.d.mts", "import": "./dist/h3/index.mjs" }, "./nuxt": { "types": "./dist/h3/index.d.mts", "import": "./dist/h3/index.mjs" }, "./svelte": { "types": "./dist/svelte/index.d.mts", "import": "./dist/svelte/index.mjs" }, "./solidjs": { "types": "./dist/solidjs/index.d.mts", "import": "./dist/solidjs/index.mjs" }, "./workflow": { "types": "./dist/workflow/index.d.mts", "import": "./dist/workflow/index.mjs" }, "./hono": { "types": "./dist/hono/index.d.mts", "import": "./dist/hono/index.mjs" }, "./cloudflare": { "types": "./dist/cloudflare/index.d.mts", "import": "./dist/cloudflare/index.mjs" } }, "keywords": [ "qstash", "queue", "events", "serverless", "upstash" ], "scripts": { "build": "tsup", "test": "bun test src", "fmt": "prettier --write .", "lint": "tsc && eslint \"src/**/*.{js,ts,tsx}\" --quiet --fix", "prepare": "husky" }, "devDependencies": { "@commitlint/cli": "^19.2.2", "@commitlint/config-conventional": "^19.2.2", "@types/bun": "^1.1.1", "@types/crypto-js": "^4.2.0", "@typescript-eslint/eslint-plugin": "^7.0.1", "@typescript-eslint/parser": "^7.0.1", "ai": "^3.1.28", "bun-types": "^1.1.7", "eslint": "^8", "eslint-plugin-unicorn": "^51.0.1", "husky": "^9.0.10", "neverthrow": "^7.0.1", "next": "^14.0.2", "prettier": "^3.2.5", "tsup": "latest", "typescript": "^5.4.5", "undici-types": "^6.16.0", "@solidjs/start": "^1.0.6", "@sveltejs/kit": "^2.5.18", "hono": "^4.5.8", "h3": "^1.12.0", "vitest": "latest" }, "dependencies": { "crypto-js": ">=4.2.0", "jose": "^ 5.2.3" } }
|