libfx 0.0.14-dev.1534.g6afa7c33dac5 → 0.0.14
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/README.md +49 -4
- package/chatgpt.js +2 -1
- package/durable/local.mjs +12 -12
- package/durable/vercel.mjs +1 -1
- package/durable/world.mjs +1 -1
- package/durable.js +229 -68
- package/fx-core.wasm +0 -0
- package/fx-sdk.js +82 -7
- package/fx-term.wasm +0 -0
- package/libfx.darwin-arm64.node +0 -0
- package/libfx.darwin-x64.node +0 -0
- package/libfx.linux-arm64.node +0 -0
- package/libfx.linux-x64.node +0 -0
- package/mcp.js +11 -2
- package/node.cjs +396 -48
- package/node.js +2 -0
- package/package.json +1 -1
- package/subscription.js +2 -0
- package/tool-observation.js +185 -0
- package/types/browser.d.ts +7 -0
- package/types/durable-world.d.ts +7 -1
- package/types/libfx.d.cts +129 -3
- package/types/mcp.d.ts +6 -1
- package/types/node.d.cts +7 -0
- package/types/wasm.d.ts +7 -0
package/durable/vercel.mjs
CHANGED
|
@@ -265,4 +265,4 @@ To fix this, either:
|
|
|
265
265
|
- Deploy to Vercel (OIDC tokens are provisioned automatically)
|
|
266
266
|
- Provide a token explicitly: \`new QueueClient({ token: '...' })\`
|
|
267
267
|
|
|
268
|
-
Cause: ${r}`)}}buildUrl(t,...r){let n=encodeURIComponent(t),o=r.map((a)=>encodeURIComponent(a)),s=o.length>0?"/"+o.join("/"):"",i=zb(this.baseUrl.pathname);return`${this.baseUrl.origin}${i}${dYe}/${n}${s}`}async fetch(t,r){let n=r.method||"GET";if($X()){let i={method:n,url:t,headers:r.headers},a=r.body;if(a!==void 0&&a!==null)if(a instanceof ArrayBuffer)i.bodySize=a.byteLength;else if(a instanceof Uint8Array)i.bodySize=a.byteLength;else if(typeof a==="string")i.bodySize=a.length;else i.bodyType=typeof a;console.debug("[VQS Debug] Request:",JSON.stringify(i,null,2))}r.headers.set("User-Agent","@vercel/queue/0.8.0"),r.headers.set("Vqs-Client-Ts",new Date().toISOString());let o=this.dispatcher?{...r,dispatcher:this.dispatcher}:r,s=await fetch(t,o);if($X()){let i={method:n,url:t,status:s.status,statusText:s.statusText,headers:s.headers};console.debug("[VQS Debug] Response:",JSON.stringify(i,null,2))}return s}async sendMessage(t){let r=this.transport,{queueName:n,payload:o,telemetry:s}=t,i=this.buildMessageHeaders(t,r.contentType);i.set("Authorization",`Bearer ${await this.getToken()}`);let a=this.getSendDeploymentId();if(a)i.set("Vqs-Deployment-Id",a);let c=r.serialize(o),A=Buffer.isBuffer(c)?new Uint8Array(c):c,u=wm(this.telemetry,s);return HX(n,async(l)=>{await PX(i,u);let d=await this.fetch(this.buildUrl(n),{method:"POST",body:A,headers:i,...A instanceof ReadableStream&&{duplex:"half"}});if(!d.ok){let h=await KA(d);if(d.status===502&&d.headers.get("Vqs-Error-Code")==="consumer_discovery_failed")throw new rD(h.message||"Consumer discovery failed",a);XA(h,"send message")}if(d.status===202)return await d.text(),{messageId:null};let f=await d.json();if(l&&f.messageId)l.setMessageId(f.messageId);return f},u)}async sendBatch(t){let r=this.transport,{queueName:n,messages:o,telemetry:s}=t;if(o.length<1||o.length>100)throw RangeError("Batch size must be between 1 and 100 messages");let i=new Headers(this.customHeaders);i.set("Authorization",`Bearer ${await this.getToken()}`);let a=this.getSendDeploymentId();if(a)i.set("Vqs-Deployment-Id",a);let c=tYe(o.map((u)=>({headers:this.buildMessageHeaders(u,r.contentType),body:()=>r.serialize(u.payload)})));i.set("Content-Type",c.contentType);let A=wm(this.telemetry,s);return HX(n,async()=>{try{await PX(i,A);let u=await this.fetch(this.buildUrl(n,"batch"),{method:"POST",body:c.body,headers:i,duplex:"half"});if(!u.ok){let d=await KA(u);XA(d,"send message batch")}let{results:l}=await u.json();if(l.length!==o.length)throw new XX(`Invalid batch response: expected ${o.length} results, received ${l.length}`);return l}catch(u){throw await c.cancel(u),u}},A)}buildMessageHeaders(t,r){let n=new Headers(this.customHeaders);n.delete("Authorization");for(let[o,s]of Object.entries(t.headers??{})){let i=o.toLowerCase();if(s!==void 0&&i!=="authorization"&&i!=="content-type"&&!i.startsWith("vqs-"))n.set(o,s)}if(n.set("Content-Type",r),t.idempotencyKey)n.set("Vqs-Idempotency-Key",t.idempotencyKey);if(t.retentionSeconds!==void 0)n.set("Vqs-Retention-Seconds",t.retentionSeconds.toString());if(t.delaySeconds!==void 0)n.set("Vqs-Delay-Seconds",t.delaySeconds.toString());return n}async*receiveMessages(t){let r=this.transport,{queueName:n,consumerGroup:o,visibilityTimeoutSeconds:s,limit:i,cursorFallback:a}=t;if(i!==void 0&&(i<1||i>10))throw new BWe(i);let c=new Headers({Authorization:`Bearer ${await this.getToken()}`,Accept:"multipart/mixed",...this.customHeaders});if(s!==void 0)c.set("Vqs-Visibility-Timeout-Seconds",s.toString());if(i!==void 0)c.set("Vqs-Max-Messages",i.toString());if(a!==void 0)c.set("Vqs-Cursor-Fallback",a);let A=this.getConsumeDeploymentId();if(A)c.set("Vqs-Deployment-Id",A);let u=await this.fetch(this.buildUrl(n,"consumer",o),{method:"POST",headers:c});if(u.status===204){await u.text();return}if(!u.ok)XA(await KA(u),"receive messages");for await(let l of Ub(u))try{let d=GX(l.headers);if(!d){console.warn("Missing required queue headers in multipart part"),await Jb(l.payload);continue}let f=await r.deserialize(l.payload);yield{...d,payload:f}}catch(d){console.warn("Failed to process multipart message:",d),await Jb(l.payload)}}async receiveMessageById(t){let r=this.transport,{queueName:n,consumerGroup:o,messageId:s,visibilityTimeoutSeconds:i}=t,a=new Headers({Authorization:`Bearer ${await this.getToken()}`,Accept:"multipart/mixed",...this.customHeaders});if(i!==void 0)a.set("Vqs-Visibility-Timeout-Seconds",i.toString());let c=this.getConsumeDeploymentId();if(c)a.set("Vqs-Deployment-Id",c);let A=await this.fetch(this.buildUrl(n,"consumer",o,"id",s),{method:"POST",headers:a});if(!A.ok){let u=await KA(A);if(A.status===404)throw new eu(s);if(A.status===409){if(u.originalMessageId)throw new tu(s,`This message was a duplicate - use originalMessageId: ${u.originalMessageId}`);throw new yWe(s,f6(A.headers.get("Retry-After")))}if(A.status===410)throw new e6(s);XA(u,"receive message by ID")}for await(let u of Ub(A)){let l=GX(u.headers);if(!l)throw await Jb(u.payload),new IWe(s,"Missing required queue headers in response");let d=await r.deserialize(u.payload);return{message:{...l,payload:d}}}throw new eu(s)}async acknowledgeMessage(t){let{messageId:r,queueName:n,consumerGroup:o,receiptHandle:s}=t,i=new Headers({Authorization:`Bearer ${await this.getToken()}`,...this.customHeaders}),a=this.getConsumeDeploymentId();if(a)i.set("Vqs-Deployment-Id",a);let c=await this.fetch(this.buildUrl(n,"consumer",o,"lease",s),{method:"DELETE",headers:i});if(!c.ok){let A=await KA(c);if(c.status===404)throw new eu(r);if(c.status===409)throw new tu(r,A.message||"Invalid receipt handle, message not in correct state, or already processed");XA(A,"acknowledge message","Missing or invalid receipt handle")}return await c.text(),{acknowledged:!0}}async changeVisibility(t){let{messageId:r,queueName:n,consumerGroup:o,receiptHandle:s,visibilityTimeoutSeconds:i}=t,a=new Headers({Authorization:`Bearer ${await this.getToken()}`,"Content-Type":"application/json",...this.customHeaders}),c=this.getConsumeDeploymentId();if(c)a.set("Vqs-Deployment-Id",c);let A=await this.fetch(this.buildUrl(n,"consumer",o,"lease",s),{method:"PATCH",headers:a,body:JSON.stringify({visibilityTimeoutSeconds:i})});if(!A.ok){let u=await KA(A);if(A.status===404)throw new eu(r);if(A.status===409)throw new tu(r,u.message||"Invalid receipt handle, message not in correct state, or already processed");XA(u,"change visibility","Missing receipt handle or invalid visibility timeout")}return await A.text(),{success:!0}}},tD=new WeakMap,h6=Symbol.for("@vercel/queue.apiClient");function hYe(e,t){tD.set(e,t),Object.defineProperty(e,h6,{value:t,writable:!1,enumerable:!1,configurable:!1})}function rs(e){let t=tD.get(e);if(t)return t;let r=e[h6];if(typeof r==="object"&&r!==null){let n=r;return tD.set(e,n),n}throw Error("QueueClient not initialized. This may happen when multiple bundled copies of @vercel/queue are loaded in local dev.")}function gYe(e){if("request"in e)return e.request;return e}function jX(e){if(e instanceof e6||e instanceof Error&&e.name==="MessageAlreadyProcessedError")return"already_processed";if(e instanceof tu||e instanceof Error&&e.name==="MessageNotAvailableError")return"not_available";return null}function WX(e,t){return console.debug(`Queue callback skipped (${e}) for message ${t??"<unknown>"}: the message was already handled or is no longer available to this consumer.`),{status:"skipped",reason:e,...t!==void 0?{messageId:t}:{}}}function g6(e){return rs(e)}var YX="iad1";function pYe(e){if(e)return e;let t=process.env.VERCEL_REGION;if(t)return t;if(!Jr())console.warn(`[QueueClient] Region not detected — defaulting to "${YX}". On Vercel this is set automatically via VERCEL_REGION. To silence this warning, pass region explicitly: new QueueClient({ region: "iad1" })`);return YX}var cD=class{constructor(e={}){let t=pYe(e.region);hYe(this,new fYe({...e,region:t}))}send=async(e,t,r)=>{let n=rs(this),o=await n.sendMessage({queueName:e,payload:t,idempotencyKey:r?.idempotencyKey,retentionSeconds:r?.retentionSeconds,delaySeconds:r?.delaySeconds,headers:r?.headers,telemetry:r?.telemetry});if(o.messageId&&Jr()&&!n.usesLocalBroker())Bm(e,o.messageId,n.getRegion(),r?.delaySeconds,r?.retentionSeconds);return{messageId:o.messageId}};experimental_sendBatch=async(e,t,r)=>{let n=rs(this),o=await n.sendBatch({queueName:e,messages:t,telemetry:r?.telemetry});if(!Jr()||n.usesLocalBroker())return o;let s=n.getRegion();for(let[i,a]of o.entries()){if(a.status!=="sent")continue;let c=t[i];mWe(c),Bm(e,a.messageId,s,c.delaySeconds,c.retentionSeconds)}return o};handleCallback=(e,t)=>{if(Jr()&&!rs(this).usesLocalBroker())Em(e,this,t);let r=wm(rs(this).getTelemetry?.());return async(n)=>{let o=gYe(n);if(Jr()&&!rs(this).usesLocalBroker()&&o.headers.get("x-vercel-queue-prime")==="1"){let i=o.headers.get("x-vercel-queue-prime-file");if(i)Em(e,this,t,i);return Response.json({status:"primed"})}let s;try{s=await kWe(o);let i=s;return await VX(o.headers,()=>Zb(e,i,{client:this,visibilityTimeoutSeconds:t?.visibilityTimeoutSeconds,retry:t?.retry}),r),Response.json({status:"success"})}catch(i){let a=jX(i);if(a)return Response.json(WX(a,s?.messageId));if(console.error("Queue callback error:",i),i instanceof Error&&(i.message.includes("Invalid content type")||i.message.includes("Invalid CloudEvent")||i.message.includes("Missing required CloudEvent")||i.message.includes("Failed to parse CloudEvent")||i.message.includes("Binary mode callback")))return Response.json({error:i.message},{status:400});return Response.json({error:"Failed to process queue message"},{status:500})}}};handleNodeCallback=(e,t)=>{if(Jr()&&!rs(this).usesLocalBroker())Em(e,this,t);let r=wm(rs(this).getTelemetry?.());return async(n,o)=>{if(n.method!=="POST"){o.status(200).end();return}let s=n.headers["x-vercel-queue-prime"];if(Jr()&&!rs(this).usesLocalBroker()&&s==="1"){let a=n.headers["x-vercel-queue-prime-file"],c=Array.isArray(a)?a[0]:a;if(c)Em(e,this,t,c);o.status(200).json({status:"primed"});return}let i;try{i=n6(n.body,n.headers);let a=i;await VX(n.headers,()=>Zb(e,a,{client:this,visibilityTimeoutSeconds:t?.visibilityTimeoutSeconds,retry:t?.retry}),r),o.status(200).json({status:"success"})}catch(a){let c=jX(a);if(c){o.status(200).json(WX(c,i?.messageId));return}if(console.error("Queue callback error:",a),a instanceof Error&&(a.message.includes("Invalid content type")||a.message.includes("Invalid CloudEvent")||a.message.includes("Missing required CloudEvent")||a.message.includes("Failed to parse CloudEvent")||a.message.includes("Binary mode callback"))){o.status(400).json({error:a.message});return}o.status(500).json({error:"Failed to process queue message"})}}}};No();Er();kl();XB();function yf(e){return`${e} requires VERCEL_DEPLOYMENT_ID, which Vercel sets in every deployment, so this process is not running inside one. The Vercel world is only selected automatically when `+"that variable is set, so it was requested explicitly here — most often by WORKFLOW_TARGET_WORLD=vercel "+"in a process that is not a deployment, such as a production server started locally or in CI. To use the local filesystem world instead, set WORKFLOW_TARGET_WORLD=local or unset it."}Eo();Nn();Dr();var x6=100;function OYe(){let e=process.env.VERCEL_QUEUE_TRACE_PROPAGATION?.toLowerCase();return e==="off"||e==="0"||e==="false"}function UYe(e){if(e===void 0)return{messageId:null,error:"Queue batch returned no result for this message",retryable:!0};if(e.status==="failed")return{messageId:null,error:e.error,retryable:e.retryable};return{messageId:e.messageId?cl.parse(e.messageId):null}}class U6{contentType="application/cbor";serialize(e){return Buffer.from(Ts(e))}async deserialize(e){let t=[],r=e.getReader();while(!0){let{done:n,value:o}=await r.read();if(n)break;if(o)t.push(o)}return Ir(Buffer.concat(t))}}class M6{contentType="application/json";serialize(e){return Buffer.from(JSON.stringify(e))}async deserialize(e){let t=[],r=e.getReader();while(!0){let{done:n,value:o}=await r.read();if(n)break;if(o)t.push(o)}return JSON.parse(Buffer.concat(t).toString())}}class F6{contentType="application/cbor";serialize(e){return Buffer.from(Ts(e))}async deserialize(e){let t=[],r=e.getReader();while(!0){let{done:o,value:s}=await r.read();if(o)break;if(s)t.push(s)}let n=Buffer.concat(t);try{return Ir(n)}catch{return JSON.parse(n.toString())}}}var Dm=new NYe,MYe="x-vercel-internal-workflow-step-ids",FYe=10;function L6(e){let t=Dm.getStore();if(t?.collectStepIds&&t.stepIds.size<FYe)t.stepIds.add(e)}function LYe(e,t){if(t.stepIds.size===0)return e;let r=new Headers(e.headers);return r.set(MYe,JSON.stringify(Array.from(t.stepIds))),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})}var PYe=j(H({payload:nw,queueName:ew,deploymentId:Q().optional()})),HYe=Number(process.env.VERCEL_QUEUE_MAX_DELAY_SECONDS||82800),gD=1,P6=900,VYe=0.25;function $Ye(e){if(typeof e!=="object"||e===null)return;let t=e.retryAfter;if(typeof t!=="number"||!Number.isFinite(t)||t<=0)return;return Math.min(Math.ceil(t),P6)}function GYe(e,t){let r=Math.min(Math.max(gD,2**(t-1)),P6),n=Math.floor(Math.random()*(Math.ceil(r*VYe)+1)),o=Math.max(gD,r-n);return Math.max(o,$Ye(e)??gD)}var jYe="iad1";function H6(e){if("runId"in e&&typeof e.runId==="string")return e.runId;return}function WYe(e){try{return tw(e).id}catch{return}}var YYe=(e,t,r)=>{let n;return{open(){if(!e||!Qm(t))return;n=Promise.resolve().then(() => (bm(),{})).then(({})=>hD(e,r,{workflowName:t})).catch(()=>{return})},async close(){(await n)?.()}}},N6="wrun_";function qYe(e){if(!e)return;let t=e.startsWith(N6)?e.slice(N6.length):e;try{let r=HA(t);if(!r.tagged)return;if(r.regionId===Fn.unknown)return;return r.region??void 0}catch{return}}function JYe(e,t){if(j0(t?.region))return t.region;let r=qYe(H6(e));if(r)return r;let n=process.env.VERCEL_REGION;if(j0(n))return n;return jYe}function zYe(e){let t={};if("runId"in e&&typeof e.runId==="string")t["x-vercel-workflow-run-id"]=e.runId;if("stepId"in e&&typeof e.stepId==="string")t["x-vercel-workflow-step-id"]=e.stepId;return Object.keys(t).length>0?t:void 0}var ZYe=/^__([a-z][a-z0-9]*_)?wkf_workflow_/,O6=Yt("@workflow/world-vercel//queueLogLatches",1,()=>({loggedSequentialReplays:!1}));function KYe(){return process.env.WORKFLOW_SEQUENTIAL_REPLAYS==="1"}function XYe(e,t){if(!KYe()||!ZYe.test(e))return e;if(!O6.loggedSequentialReplays)O6.loggedSequentialReplays=!0,console.warn("[workflow] WORKFLOW_SEQUENTIAL_REPLAYS=1: routing flow messages to per-run queue topics");if("__healthCheck"in t&&typeof t.correlationId==="string")return`${e}_${t.correlationId}`;if("runId"in t&&typeof t.runId==="string"){if("stepId"in t&&typeof t.stepId==="string")return`${e}_${t.runId}_${t.stepId}`;return`${e}_${t.runId}`}return e}function pD(e){let{baseUrl:t,usingProxy:r}=Un(e),n=L0(e,{usingProxy:r}),o=new U6,s=new M6,i=new F6,a={dispatcher:g8(e),transport:i,...r&&{resolveBaseUrl:()=>new URL(`${t}/queues-proxy`),token:e?.token},headers:Object.fromEntries(n.entries())},c=(g,p,I)=>{let m=I?.deploymentId??process.env.VERCEL_DEPLOYMENT_ID;if(!m)throw Error(`${yf("Enqueuing a workflow message")} Callers outside a deployment can instead pass an explicit deploymentId in options.`);let C=(I?.specVersion??Sg)>=lw,b=JYe(p,I),D=XYe(g,p).replace(/[^A-Za-z0-9-_]/g,"-");return{deploymentId:m,useCbor:C,region:b,topic:D,wrapper:{payload:p,queueName:g,deploymentId:I?.deploymentId},sendOptions:{idempotencyKey:I?.idempotencyKey,delaySeconds:I?.delaySeconds,headers:{...zYe(p),...I?.headers}}}},A=(g)=>new cD({...a,...r&&{headers:{...a.headers,"x-vercel-queue-region":g.region}},region:g.region,deploymentId:g.deploymentId,transport:g.useCbor?o:s}),u=async(g,p,I)=>{let m=c(g,p,I),C=A(m),{messageId:b}=await C.send(m.topic,m.wrapper,m.sendOptions);return{messageId:b?cl.parse(b):null}};return{queue:u,queueBatch:async(g,p)=>{let I=Array(p.length);if(p.length===0)return I;let m=OYe()?{}:await b0(),C=new Map;for(let[b,D]of p.entries()){let v=c(g,D.message,D.opts),P=`${v.region}\x00${v.deploymentId}\x00${v.useCbor}\x00${v.topic}`,T=C.get(P)??{route:v,entries:[]};T.entries.push({index:b,topic:v.topic,message:{payload:v.wrapper,...v.sendOptions,headers:{...v.sendOptions.headers,...m}}}),C.set(P,T)}return await Promise.all([...C.values()].map(async({route:b,entries:D})=>{let v=A(b);for(let P=0;P<D.length;P+=x6){let T=D.slice(P,P+x6),V=await v.experimental_sendBatch(T[0].topic,T.map((L)=>L.message));for(let[L,ee]of T.entries())I[ee.index]=UYe(V[L])}})),I},createQueueHandler:(g,p)=>{let m=new cD(a).handleCallback(async(C,b)=>{if(!C||!b)return;let D=Dm.getStore(),v=D?.requestId,{payload:P,queueName:T,deploymentId:V}=PYe.parse(C),L=YYe(H6(P),WYe(T),e),ee=!(("stepId"in P)&&typeof P.stepId==="string");L.open();try{let K=()=>p(P,{queueName:T,messageId:cl.parse(b.messageId),attempt:b.deliveryCount,requestId:v}),w=await(D?Dm.run({...D,collectStepIds:ee},K):K());if(!(("invoke"in P)&&P.invoke===!0)&&typeof w==="object"&&w!==null&&"timeoutSeconds"in w&&typeof w.timeoutSeconds==="number"){let F=w.timeoutSeconds>0?Math.min(w.timeoutSeconds,HYe):void 0;await u(T,P,{deploymentId:V,delaySeconds:F})}}finally{await L.close()}},{retry:(C,{messageId:b,deliveryCount:D})=>{let v=GYe(C,D);return console.error(`[workflow] Queue handler failed for message "${b}" on delivery attempt ${D}; retrying in ${v}s:`,C),{afterSeconds:v}}});return async(C)=>{let v={collectStepIds:!1,requestId:C.headers.get("x-vercel-id")?.trim()||void 0,stepIds:new Set},P=await Dm.run(v,()=>m(C));return LYe(P,v)}},getDeploymentId:async()=>{let g=process.env.VERCEL_DEPLOYMENT_ID;if(!g)throw Error(yf("Starting a workflow run"));return g},isDeploymentUnavailableError:(g)=>g instanceof rD}}at();var V6=Ke(Pc(),1);Eo();On();var eqe=j(H({id:Q()}));async function tqe(e){if(e?.token)return e.token;if(process.env.VERCEL==="1"){let t=await V6.getVercelOidcToken().catch(()=>null);if(t)return t}return VE(e)}function $6(e){return async function(){let r=process.env.VERCEL_DEPLOYMENT_ID;if(!r)throw Error(yf("Resolving the latest deployment for deploymentId: 'latest'"));let n=await tqe(e);if(!n)throw Error("Cannot resolve latest deployment: no OIDC token or VERCEL_TOKEN available");let o=e?.projectConfig?.teamId,s=o?`?${new URLSearchParams({teamId:o})}`:"",i=`https://api.vercel.com/v1/workflow/resolve-latest-deployment/${encodeURIComponent(r)}${s}`,c=await(await Kt({method:"GET",url:i,headers:new Headers({Authorization:`Bearer ${n}`}),dispatcher:po(e),peerService:"vercel-api",timeoutMs:null,buildError:async(u)=>{let l;try{l=await u.text()}catch{l="<unable to read response body>"}let d=u.status===404?". The deployment exists but was not visible to the identity this request authenticated as, which means the request resolved to a different team. Set the World's `projectConfig.teamId` to scope it explicitly.":"";return Error(`Failed to resolve latest deployment for ${r}: HTTP ${u.status} ${u.statusText}${l?` — ${l}`:""}${d}`)}})).json(),A=eqe.safeParse(c);if(!A.success)throw Error(`Invalid response from Vercel API: expected { id: string }. Zod error: ${A.error.message}`);return A.data.id}}Ur();Er();dg();Ur();class qa extends Error{error;constructor(e){super("Replay event observer failed",{cause:e});this.error=e,this.name="ReplayEventObserverError"}}class iu extends Error{error;constructor(e){super("Event log read after a committed write failed",{cause:e});this.error=e,this.name="AfterCommitError"}}var rqe=new Set(["step_completed","step_retrying"]);function nqe(e){return rqe.has(e)}var oqe={run_created:{retryable:!0,reason:"conditional create → 409 if exists"},step_created:{retryable:!0,reason:"conditional create → 409 if exists"},wait_created:{retryable:!0,reason:"conditional create → 409 if exists"},hook_created:{retryable:!0,reason:"transactional token uniqueness → 409 if exists"},run_started:{retryable:!0,reason:"early-returns if already running, no duplicate row"},run_completed:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},run_failed:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},run_cancelled:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},step_completed:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},step_failed:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},wait_completed:{retryable:!0,reason:"waiting-state guard → 409, no duplicate row"},hook_disposed:{retryable:!0,reason:"conditional delete (exists) → 409, no duplicate row"},attr_set:{retryable:!0,reason:"correlationId constraint reuses eventId (idempotent replay)"},step_started:{retryable:!1,reason:"unconditional attempt increment → a retry double-counts attempts"},step_retrying:{retryable:!1,reason:"no duplicate guard → a retry appends a second event row"},hook_received:{retryable:!1,reason:"no server guard → a retry duplicates the row / re-delivers payload. "+"EXCEPTION: the atomic lazy-resume shape (resumeId + digest) is deduplicated server-side by the (runId, resumeId) claim, so those writes opt in via withEventPostRetry({ idempotentHookResume })"},hook_conflict:{retryable:!1,reason:"server-originated; never POSTed by the SDK"},noop:{retryable:!1,reason:"server-originated; never POSTed by the SDK"}},sqe=2,iqe=30000,aqe=15000,cqe=900000,Aqe=1,uqe=100,lqe=50,dqe=new Set(["ECONNRESET","ECONNREFUSED","ENOTFOUND","ENETDOWN","ENETUNREACH","EHOSTDOWN","EHOSTUNREACH","EPIPE","ETIMEDOUT","UND_ERR_SOCKET","UND_ERR_REQ_RETRY","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","TimeoutError","RequestRetryError"]);function Rm(e,t=0){if(t>5||e===null||typeof e!=="object")return[];let r=[],n=e;if(typeof n.code==="string")r.push(n.code);if(typeof n.name==="string")r.push(n.name);if(n.cause)r.push(...Rm(n.cause,t+1));return r}function fqe(e){if(e instanceof qa)return!1;if(Vi.is(e)||Oo.is(e)||$i.is(e)||Gi.is(e)||Dn.is(e))return!1;if(G.is(e)||gt.is(e)){if(e.code==="PARSE_ERROR")return!0;if(e.code==="TRANSPORT")return!0;if(typeof e.status==="number")return e.status>=500&&e.status<=599;if(e.code==="STREAM_ERROR")return!Rm(e).some((t)=>["AbortError","ABORT_ERR","UND_ERR_ABORTED","ERR_HTTP2_STREAM_CANCEL"].includes(t))}return Rm(e).some((t)=>dqe.has(t))}var j6=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}let o=()=>{clearTimeout(s),n(t?.reason)},s=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e);t?.addEventListener("abort",o,{once:!0})}),hqe=typeof process<"u"&&typeof process.env.DEBUG==="string"&&(process.env.DEBUG.includes("workflow:")||process.env.DEBUG==="*");function ED(e,t){if(!hqe)return;let r=Object.entries(t).map(([n,o])=>`${n}=${o}`).join(" ");console.debug(`[workflow:world-vercel:event-retry] ${e} ${r}`)}function G6(e){if(G.is(e))return e.code??(e.status!=null?`status_${e.status}`:e.name);return Rm(e)[0]??(e instanceof Error?e.name:"unknown")}async function gqe(){try{let t=(await dm())?.getTime();return t!==void 0&&Number.isFinite(t)?t:void 0}catch{return}}function wf(e,t){let r=0,n;return async(o,s)=>{let i=Math.max(1,typeof o.retryAfter==="number"?o.retryAfter:Aqe)*1000;if(n===void 0){let c=await gqe();n={budgetMs:t==="invocation"&&c!==void 0?cqe:iqe,deadlineMs:c}}let a=n.deadlineMs!==void 0&&Date.now()+i>n.deadlineMs-aqe;if(r+i>n.budgetMs||a)throw ED("throttle retry budget exhausted; surfacing to the queue",{target:e,budget:t,waitedMs:r,retryAfter:o.retryAfter,outlastsInvocation:a}),o;r+=i,console.warn(`[workflow] Throttled (429) ${e}; retrying in-process in ${i/1000}s`),await j6(i,s)}}function pqe(e,t){if(t?.batchIdempotent!==void 0)return"bounded";return t?.afterStepBody===!0||nqe(e)?"invocation":"bounded"}function Eqe(e,t){if(t?.inBand===!0)return!1;if(t?.batchIdempotent!==void 0)return t.batchIdempotent;return e==="hook_received"&&t?.idempotentHookResume===!0||(oqe[e]?.retryable??!1)}async function mD(e,t,r){let n=Eqe(t,r),o=wf(`writing ${t} event`,pqe(t,r));for(let s=0;;)try{return await e()}catch(i){if(i instanceof iu)throw i;if(Dn.is(i)){await o(i);continue}if(!n||!fqe(i))throw i;if(s>=sqe)throw ED("exhausted in-process retries; surfacing for queue redelivery",{eventType:t,attempts:s+1,error:G6(i)}),i;let a=uqe*2**s+Math.floor(Math.random()*lqe);s++,ED("retrying event POST after transient failure",{eventType:t,attempt:s,backoffMs:a,error:G6(i)}),await j6(a)}}Ur();No();Er();kl();at();import SD from"node:assert/strict";ou();Eo();On();Ur();var ID=4,mqe="devl",Iqe="encr",W6="gzip",yD="zstd",yqe=new TextDecoder,Cqe=new Set([mqe,Iqe,W6,yD]);function Bqe(){try{return globalThis.process?.getBuiltinModule?.("node:zlib")}catch{return}}function Y6(e){if(!(e instanceof Uint8Array)||e.byteLength<ID)return null;return yqe.decode(e.subarray(0,ID))}function q6(e){let t=Y6(e);return t!==null&&Cqe.has(t)}function wqe(e,t){let r=Bqe(),n=e===yD?r?.zstdDecompressSync:r?.gunzipSync;if(!n)throw new G(`Received ${e}-compressed workflow data, but this Node.js runtime does not support ${e} decompression. Use a compatible Node.js runtime or request unresolved data.`);return new Uint8Array(n(t))}function fi(e){let t=Y6(e);if(t!==yD&&t!==W6)return e;return wqe(t,e.subarray(ID))}function Qqe(e){try{return fi(e)}catch(t){if(G.is(t))throw t;throw new G("Stored dynamic workflow code could not be decompressed.",{code:"WORLD_CONTRACT_ERROR",cause:t})}}function CD(e){return{...e,input:fi(e.input),output:fi(e.output),error:fi(e.error),...e.dynamicWorkflowCode!==void 0?{dynamicWorkflowCode:Qqe(e.dynamicWorkflowCode)}:{}}}function BD(e){return{...e,input:fi(e.input),output:fi(e.output),error:fi(e.error)}}function J6(e){return{...e,metadata:fi(e.metadata)}}Er();at();Dr();var au=j(qB.omit({error:!0}).extend({error:vo([Se,Wt()]).optional(),errorRef:Wt().optional()})),z6=j(au.omit({input:!0,output:!0}).extend({inputRef:Wt().optional(),outputRef:Wt().optional(),input:_c(Uint8Array).optional(),output:_c(Uint8Array).optional()}));function Qf(e){let{error:t,errorRef:r,...n}=e,o={...n},s=t??r;if(s!==void 0&&s!==null)o.error=s;return o}function Z6(e,t){if(t==="none"){let{inputRef:r,outputRef:n,...o}=e;return{...BD(Qf(o)),input:void 0,output:void 0}}return BD(Qf(e))}async function K6(e,t){let{runId:r,pagination:n,resolveData:o=yn}=e,s=new URLSearchParams;if(n?.cursor)s.set("cursor",n.cursor);if(n?.limit)s.set("limit",n.limit.toString());if(n?.sortOrder)s.set("sortOrder",n.sortOrder);let i=o==="none"?"lazy":"resolve";s.set("remoteRefBehavior",i);let a=s.toString(),c=`/v2/runs/${encodeURIComponent(r)}/steps${a?`?${a}`:""}`,A=await Te({endpoint:c,options:{method:"GET"},config:t,schema:or(i==="lazy"?z6:au)});return{...A,data:A.data.map((u)=>Z6(u,o))}}async function X6(e,t,r,n){let o=r?.resolveData??yn,s=o==="none"?"lazy":"resolve",i=new URLSearchParams;i.set("remoteRefBehavior",s);let a=i.toString(),c=`/v2/runs/${encodeURIComponent(e)}/steps/${encodeURIComponent(t)}${a?`?${a}`:""}`,A=await Te({endpoint:c,options:{method:"GET"},config:n,schema:s==="lazy"?z6:au});return Z6(A,o)}Nn();Dr();async function km(e,t,r,n,o){let s=TE(r),i=await Kt({method:t.method,url:e,headers:t.headers,body:t.body,dispatcher:s,attributes:o,onTransportOutcome:(A)=>NA(s,A),deferTransportSuccessUntilBody:!0,timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:n,buildError:async(A)=>u7(A.status,LA(A.headers),new Uint8Array(await A.arrayBuffer()),n,e)});if(!i.body)return NA(s),i;let a=i.body.getReader(),c=new ReadableStream({async pull(A){try{let u=await a.read();if(u.done)NA(s),A.close();else A.enqueue(u.value)}catch(u){NA(s,u);let l=qd(u);A.error(l?new gt(`v4 ${n}: response stream transport failure (${l})`,{cause:u,url:e}):u)}},cancel(A){return NA(s),a.cancel(A)}});return new Response(c,{status:i.status,statusText:i.statusText,headers:i.headers})}var n7="x-wf-event-id",o7="x-wf-max-events";function s7(e,t,r){return`${e}/v4/runs/${encodeURIComponent(t)}/events/${encodeURIComponent(r)}`}var e7=Symbol("omitted event payload"),Ja=j(t2((e)=>{if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t=e,r=typeof t.eventType==="string"?Bs(t.eventType):void 0,n=t.eventData;if(!r||typeof n!=="object"||n===null||Array.isArray(n)||Object.hasOwn(n,r))return e;return{...t,eventData:{...n,[r]:e7}}},$B).transform((e)=>{let t=Bs(e.eventType);if(!t||!("eventData"in e))return e;let r=e.eventData;if(typeof r!=="object"||r===null||Array.isArray(r)||r[t]!==e7)return e;let n={...r};return delete n[t],{...e,eventData:n}})),Tm=H({event:Ja,run:ol.optional(),step:au.transform(Qf).optional(),hook:ws.optional(),wait:zB.optional(),stepCreated:ue(!0).optional(),maxEvents:z().int().positive().optional(),allocated:z().int().nonnegative().optional()}),vm=vo([H({events:_n(Ja),cursor:Q().nullable(),hasMore:jt()}),H({events:Wn().optional(),cursor:Wn().optional(),hasMore:Wn().optional()})]),lr=Tm.and(vm),i7={run_created:Tm.extend({run:ol}).and(vm),run_started:Tm.extend({run:ol.and(H({startedAt:Ie.date()}))}).and(vm),step_started:Tm.extend({step:au.extend({startedAt:Ie.date()}).transform((e)=>({...Qf(e),startedAt:e.startedAt}))}).and(vm),run_completed:lr,run_failed:lr,run_cancelled:lr,attr_set:lr,step_created:lr,step_completed:lr,step_failed:lr,step_retrying:lr,hook_created:lr,hook_received:lr,hook_disposed:lr,hook_conflict:lr,wait_created:lr,wait_completed:lr,noop:lr},a7=j(Ie.number().int().positive()),c7=j(H({seq:z().int().nonnegative(),seqInBand:z().int().nonnegative()}).refine(({seq:e,seqInBand:t})=>t<=e)),_qe="x-wf-snapshot-seq",Sqe="x-wf-snapshot-seq-in-band",t7=/^\d+$/;function bqe(e){let t=e.get(_qe),r=e.get(Sqe);if(t===null||r===null||!t7.test(t)||!t7.test(r))return;let n=c7.safeParse({seq:Number(t),seqInBand:Number(r)});return n.success?n.data:void 0}function Dqe(e){if(e===void 0)return;let t=c7.safeParse(e);return t.success?t.data:void 0}var Rqe=j(H({_end:ue(1),next:Q().optional(),hasMore:jt(),snapshot:Ui().optional()})),Tqe=j(H({_error:ue(1),code:Q(),message:Q().optional()})),vqe="payload-missing",kqe=new Set(["run_failed","step_failed","step_retrying"]);function xqe(e){if(q6(e))return e;try{let t=sw.safeParse(Ir(e.slice()));return t.success?t.data:e}catch{return e}}function A7({meta:e,body:t}){let r=pr.parse(e.eventType);if(t.byteLength===0)return Ja.parse(e);let n=Bs(r);return SD(n,`Event type ${r} cannot carry a payload body`),SD(e.eventData&&typeof e.eventData==="object"),Ja.parse({...e,eventData:{...e.eventData,[n]:kqe.has(r)?xqe(t):t}})}function RD(e){let t={eventType:e.eventType,specVersion:e.specVersion};if(e.executorSpecVersion!==void 0)t.executorSpecVersion=e.executorSpecVersion;if(e.correlationId!==void 0)t.correlationId=e.correlationId;if(e.vercelId!==void 0)t.vercelId=e.vercelId;if(e.computeInstanceId!==void 0)t.computeInstanceId=e.computeInstanceId;if(e.occurredAt!==void 0)t.occurredAt=e.occurredAt;if(e.remoteRefBehavior!==void 0)t.remoteRefBehavior=e.remoteRefBehavior;if(e.eventsRemoteRefBehavior!==void 0)t.eventsRemoteRefBehavior=e.eventsRemoteRefBehavior;if(e.deploymentId!==void 0)t.deploymentId=e.deploymentId;if(e.workflowName!==void 0)t.workflowName=e.workflowName;if(e.stepName!==void 0)t.stepName=e.stepName;if(e.attempt!==void 0)t.attempt=e.attempt;if(e.resumeAt!==void 0)t.resumeAt=e.resumeAt;if(e.retryAfter!==void 0)t.retryAfter=e.retryAfter;if(e.hookToken!==void 0)t.hookToken=e.hookToken;if(e.hookTokenRetentionUntil!==void 0)t.hookTokenRetentionUntil=e.hookTokenRetentionUntil;if(e.hookIsWebhook!==void 0)t.hookIsWebhook=e.hookIsWebhook;if(e.hookIsSystem!==void 0)t.hookIsSystem=e.hookIsSystem;if(e.hookForce!==void 0)t.hookForce=e.hookForce;if(e.resumeId!==void 0)t.resumeId=e.resumeId;if(e.errorCode!==void 0)t.errorCode=e.errorCode;if(e.cancelReason!==void 0)t.cancelReason=e.cancelReason;if(e.ownerMessageId!==void 0)t.ownerMessageId=e.ownerMessageId;if(e.executionContext!==void 0)t.executionContext=e.executionContext;if(e.attributes!==void 0)t.attributes=e.attributes;if(e.changes!==void 0)t.changes=e.changes;if(e.writer!==void 0)t.writer=e.writer;if(e.allowReservedAttributes!==void 0)t.allowReservedAttributes=e.allowReservedAttributes;if(e.encryptionPublicKey!==void 0)t.encryptionPublicKey=e.encryptionPublicKey;if(e.dynamicWorkflowCode!==void 0)t.dynamicWorkflowCode=e.dynamicWorkflowCode;if(e.dynamicWorkflowCodeRef!==void 0)t.dynamicWorkflowCodeRef=e.dynamicWorkflowCodeRef;if(e.ttfs!==void 0)t.ttfs=e.ttfs;if(e.stso!==void 0)t.stso=e.stso;if(e.stepCount!==void 0)t.stepCount=e.stepCount;if(e.eventCount!==void 0)t.eventCount=e.eventCount;if(e.rsfs!==void 0)t.rsfs=e.rsfs;if(e.finalSchedulingReplay!==void 0)t.finalSchedulingReplay=e.finalSchedulingReplay;if(e.optimizations!==void 0)t.optimizations=e.optimizations;if(e.sinceCursor!==void 0)t.sinceCursor=e.sinceCursor;if(e.skipPreload)t.skipPreload=!0;if(e.maxSlot!==void 0)t.maxSlot=e.maxSlot;if(e.replayDivergenceCount!==void 0)t.replayDivergenceCount=e.replayDivergenceCount;if(e.resumePayloadDigest!==void 0)t.resumePayloadDigest=e.resumePayloadDigest;if(e.viaStepDispatch!==void 0)t.viaStepDispatch=e.viaStepDispatch;if(e.inBand!==void 0)t.inBand=e.inBand;if(e.expectedSeqInBand!==void 0)t.expectedSeqInBand=e.expectedSeqInBand;return t}function TD(e){return{...e.inBand!==void 0?R8(e.inBand):{},...e.expectedSeqInBand!==void 0?T8(e.expectedSeqInBand):{}}}function u7(e,t,r,n,o){let s=`v4 ${n} failed: HTTP ${e}`,i,a,{record:c,text:A}=Oqe(r,wD(t,"content-type"));if(c){if(typeof c.message==="string")s=c.message;if(typeof c.code==="string")i=c.code;else if(typeof c.error==="string")i=c.error;if(e===412)a=i===gl?Nqe(c):Uqe(c);if(e===409&&i==="hook-force-claimed")a={claimedBy:c.claimedBy}}else if(A)s+=` ${A}`;let u=Ha(wD(t,"retry-after"));return Va(e,s,{retryAfter:u,code:i,url:o,mitigated:wD(t,"x-vercel-mitigated"),...a!==void 0?{details:a}:{}})}function Nqe(e){let t=Yd(e.seq),r=Yd(e.seqInBand);return{...t!==void 0?{seq:t}:{},...r!==void 0?{seqInBand:r}:{}}}function Oqe(e,t){if(typeof e!=="string"&&t?.includes("application/cbor")){try{let n=Ir(e.slice());if(typeof n==="object"&&n!==null)return{record:n}}catch{}return{}}let r=typeof e==="string"?e:new TextDecoder().decode(e);try{let n=JSON.parse(r);if(typeof n==="object"&&n!==null)return{record:n}}catch{}return{text:r}}function Uqe(e){if(!Array.isArray(e.events)||e.events.length===0)return;let t=[];for(let r of e.events){if(typeof r!=="object"||r===null)return;let n=r;if(typeof n.eventId!=="string")return;if(Mqe(n))return;let o=Ja.safeParse(n);if(!o.success)return;t.push(o.data)}return{events:t,...typeof e.cursor==="string"?{cursor:e.cursor}:{}}}function Mqe(e){let t=e.eventType;if(typeof t!=="string")return!1;let r=Bs(t);if(!r)return!1;let n=e.eventData;if(typeof n!=="object"||n===null)return!1;let o=n[r];if(o===void 0)return!1;return!(o instanceof Uint8Array)}async function vD(e,t,r){let{baseUrl:n,headers:o}=await Ye(r),s=new Headers(o);if(s.set("Content-Type","application/octet-stream"),t==="event-stream")s.set("Accept",di);let i=zr(RD(e),e.payload??new Uint8Array(0)),a=s7(n,e.runId,e.eventType);return km(a,{method:"POST",headers:s,body:i},r,"createEvent",{...MA("http"),...D0(e.eventType),...R0(`@workflow/world-vercel/${ho}`),...TD(e),...e.eventType==="step_started"?{...LE(e.payload===void 0?e.ownerMessageId!==void 0?"single_owned_recovery":"single_bare":"single_lazy_create_claim"),...PE(e.ownerMessageId!==void 0)}:{},...e.stso!==void 0?T0(e.stso):{},...e.optimizations!==void 0?v0(e.optimizations):{}})}var Fqe=new Set(["step_completed"]);function Lqe(e){if(!m6()||!Cf())return;if(!Fqe.has(e))return;throw Error(`world-vercel: ${e} fell back to the HTTP events transport while the WS gate was on. WORKFLOW_INTERNAL_EVENTS_TRANSPORT_STRICT is set, so this is a failure rather than a silent demotion: no channel was resolvable for this run at write time.`)}async function l7(e,t){if(E6()){let o=await Wqe(e,t);if(o)return bD(o,e.eventType);Lqe(e.eventType)}let r=await vD(e,"materialized",t);if(r.headers.get("content-type")?.startsWith(di))throw new G("v4 createEvent: unexpected event page",{code:"SCHEMA_VALIDATION"});return bD(r,e.eventType)}var r7=new Map;function Pqe(e){return i7[e].refine(({event:t})=>t.eventType===e||e==="hook_created"&&t.eventType==="hook_conflict",{path:["event","eventType"]})}function Hqe(e){let t=r7.get(e);if(t)return t;let r=j(Pqe(e));return r7.set(e,r),r}async function bD(e,t){let r;try{r=new Uint8Array(await e.arrayBuffer())}catch(i){if(gt.is(i))throw i;throw new G("v4 createEvent: failed to read response body",{code:"TRANSPORT",cause:i})}if(r.byteLength===0)throw new G("v4 createEvent: empty response body",{code:"PARSE_ERROR"});let n=Hqe(t),o;try{o=Ir(r)}catch(i){throw new G("v4 createEvent: invalid CBOR response body",{code:"PARSE_ERROR",cause:i})}let s=n.safeParse(o);if(!s.success)throw new G("v4 createEvent: invalid response body",{code:"SCHEMA_VALIDATION",cause:s.error});return s.data}async function d7(e,t,r){let n=await vD({...e,eventType:"run_started"},"event-stream",t),o=await m7(n,e,t,r);if(!o.cursor)throw new G("v4 createEvent: event stream missing cursor",{code:"SCHEMA_VALIDATION"});let s=a7.safeParse(n.headers.get(o7));if(!s.success)throw new G("v4 createEvent: invalid max-events header",{code:"SCHEMA_VALIDATION",cause:s.error});return{...o,maxEvents:s.data}}var Vqe=j(H({status:z().int(),error:Q(),message:Q()}));async function f7(e,t){SD(e.events.length>0,"v4 createEventBatch: empty batch");let{baseUrl:r,headers:n}=await Ye(t),o=new Headers(n);o.set("Content-Type","application/octet-stream");let s=e.events.map((h)=>zr(RD(h),h.payload??new Uint8Array(0))),i=0;for(let h of s)i+=h.byteLength;let a=new Uint8Array(i),c=0;for(let h of s)a.set(h,c),c+=h.byteLength;let A=`${r}/v4/runs/${encodeURIComponent(e.runId)}/events/batch`,u=await km(A,{method:"POST",headers:o,body:a},t,"createEventBatch",{...MA("http"),"workflow.batch.bytes":a.byteLength,...TD(e.events[0]),...e.events.some((h)=>h.eventType==="step_started")?{...LE(e.events.some((h)=>h.eventType==="step_created")?"batch_create_claim":"batch_bare"),...PE(e.events.some((h)=>h.ownerMessageId!==void 0))}:{}}),l=new Uint8Array(await u.arrayBuffer()),d=l.byteLength>0?Ir(l):{};if(!Array.isArray(d.results)||d.results.length!==e.events.length)throw new G(`v4 createEventBatch: response \`results\` length (${Array.isArray(d.results)?d.results.length:"non-array"}) != ${e.events.length} submitted frames`,{code:"SCHEMA_VALIDATION"});return{results:d.results.map((h,g)=>{let p=Vqe.safeParse(h);if(p.success&&p.data.status!==200)return p.data;if(h?.status!==200)throw new G(`v4 createEventBatch: result at index ${g} is neither a success (status 200) nor a well-formed failure`,{code:"SCHEMA_VALIDATION"});let I=e.events[g].eventType,m=i7[I].safeParse(h);if(!m.success)throw new G(`v4 createEventBatch: invalid result body at index ${g} (${I})`,{code:"SCHEMA_VALIDATION",cause:m.error});if(m.data.event.eventType!==I)throw new G(`v4 createEventBatch: result at index ${g} carries a ${m.data.event.eventType} event, expected ${I}`,{code:"SCHEMA_VALIDATION"});return{status:200,...m.data}})}}function $qe(e){let t={};if(typeof e.eventId==="string")t[n7]=e.eventId;if(typeof e.retryAfter==="string")t["retry-after"]=e.retryAfter;if(typeof e.mitigated==="string")t["x-vercel-mitigated"]=e.mitigated;return t}function Gqe(e,t){let{replyParts:r=1}=t;if(r>1)e?.setAttributes({...O8(r)})}function jqe(e,t){let{status:r}=e.meta;if(typeof r!=="number")throw new G(`Failed to parse response body for POST ${t}: reply frame carried no numeric status (type: ${String(e.meta.type??"absent")}). Refusing to treat an `+"unrecognized reply as success — the write may or may not have been "+"applied.",{url:t,code:"PARSE_ERROR"});return r}async function Wqe(e,t){await Promise.resolve().then(() => bm());let{runId:n}=e,o=k6(n,t);if(!o)return;let{transport:s,wsUrl:i}=o,a=`${i}#runs/${encodeURIComponent(n)}/events`,c=s7(Un(t).baseUrl,n,e.eventType);return ri({method:"POST",url:c,attributes:{...MA("ws"),...D0(e.eventType),...R0(`@workflow/world-vercel/${ho}`),...TD(e),...e.stso!==void 0?T0(e.stso):{},...e.optimizations!==void 0?v0(e.optimizations):{},...e.eventType==="step_started"?{...LE(e.payload===void 0?e.ownerMessageId!==void 0?"single_owned_recovery":"single_bare":"single_lazy_create_claim"),...PE(e.ownerMessageId!==void 0)}:{},...NE("websocket"),...k8(i)}},async(A)=>{let u=Date.now(),l;try{l=await s.request((p)=>(A?.setAttributes({...x8(p)}),zr({reqId:p,type:"event",event:RD(e)},e.payload??new Uint8Array(0))),{onMessages:(p)=>{if(p>1)A?.setAttributes({...N8(p)})}})}catch(p){let I=new G(`POST ${a} transport failure: ${p instanceof Error?p.message:String(p)}`,{url:i,code:"TRANSPORT",cause:p});throw A?.setAttributes({...br("TRANSPORT")}),A?.recordException?.(I),I}let d=Date.now()-u;Gqe(A,l);let f=jqe(l,a),h=$qe(l.meta),g={get:(p)=>h[p.toLowerCase()]??null};if(Jd("POST","createEvent",{status:f,headers:g},d),M0(A,f),f<200||f>=300){let p=u7(f,h,new TextDecoder().decode(l.body),"createEvent",a);throw O0(A,p),A?.recordException?.(p),p}return{headers:g,arrayBuffer:async()=>l.body.slice().buffer}})}async function h7(e,t,r){let n=await vD({...e,eventType:"hook_received"},"event-stream",t);if(!n.headers.get("content-type")?.startsWith(di))return{kind:"materialized",result:await bD(n,"hook_received")};let s=await m7(n,e,t,r),i=a7.safeParse(n.headers.get(o7));return{kind:"stream",...s,canonicalEventId:n.headers.get(n7)??void 0,maxEvents:i.success?i.data:void 0}}function wD(e,t){let r=e[t];if(typeof r==="string")return r;if(Array.isArray(r)&&r.length>0)return r[0];return}async function g7(e,t,r,n){let{baseUrl:o,headers:s}=await Ye(n),i=`${o}/v4/runs/${encodeURIComponent(e)}/events/${encodeURIComponent(t)}?remoteRefBehavior=${r}`,a=await km(i,{method:"GET",headers:s},n,"getEvent"),c=a.headers.get("content-type");if(!c?.startsWith(di))throw Error(`v4 getEvent: expected ${di}, got ${c??"(none)"}`);let A=a.body;try{for await(let u of AD(A)){if(u.meta._error===1)throw p7(u.meta,"getEvent");if(Object.keys(u.meta).some((l)=>l.startsWith("_")))throw Error("v4 getEvent: unexpected control frame");return A7(u)}}catch(u){if(u instanceof ns&>.is(u.cause))throw u.cause;throw u}throw Error(`v4 getEvent: empty frame stream for ${t}`)}function p7(e,t){let r=Tqe.safeParse(e);if(!r.success)return new G(`v4 ${t}: malformed terminal error frame`,{code:"SCHEMA_VALIDATION",cause:r.error});let{code:n,message:o}=r.data,s=o??"(no detail)";if(n===vqe)return new vg(`the event log references a payload that no longer exists in storage: ${s}`);return new G(`v4 ${t}: stream ended with terminal error "${n}": ${s}`,{code:"WORLD_CONTRACT_ERROR"})}var Yqe=2;function QD(e,t){let r=e.at(-1)?.eventId;if(!r)throw t;return{kind:"partial",events:e,cursor:`eid:${r}`,hasMore:!0,error:t}}async function E7(e,t,r){let n=e.headers.get("content-type");if(!n?.startsWith(di))throw new G(`v4 ${t}: expected ${di}, got ${n??"(none)"}`,{code:"SCHEMA_VALIDATION"});if(!e.body)throw new G(`v4 ${t}: response body is missing`,{code:"TRANSPORT"});let o=[];try{for await(let s of AD(e.body)){if(s.meta._end===1){let a=Rqe.parse(s.meta),c=Dqe(a.snapshot)??bqe(e.headers);return{kind:"complete",events:o,cursor:a.next??null,hasMore:a.hasMore,...c?{snapshot:c}:{}}}if(s.meta._error===1)throw p7(s.meta,t);if(Object.keys(s.meta).some((a)=>a.startsWith("_")))throw Error(`v4 ${t}: unexpected control frame`);let i=A7(s);o.push(i);try{r?.(i)}catch(a){throw new qa(a)}}}catch(s){if(s instanceof qa||vg.is(s)||G.is(s))throw s;if(s instanceof ns&>.is(s.cause))return QD(o,s.cause);if(!(s instanceof ns))throw new G(`v4 ${t}: invalid event frame stream`,{code:"SCHEMA_VALIDATION",cause:s});return QD(o,new G(`v4 ${t}: incomplete event frame stream`,{code:"TRANSPORT",cause:s}))}return QD(o,new G(`v4 ${t}: frame stream ended without the end-of-stream sentinel (${o.length} events read)`,{code:"TRANSPORT"}))}async function m7(e,{runId:t,eventsRemoteRefBehavior:r},n,o){let s=await E7(e,"createEvent",o);if(!s.hasMore)return{events:s.events,cursor:s.cursor,hasMore:!1};if(!s.cursor)throw new G("v4 createEvent: partial event stream missing cursor",{code:"SCHEMA_VALIDATION"});let i;try{i=await kD(t,{cursor:s.cursor,remoteRefBehavior:r==="skip-step-inputs"?"skip-step-inputs":"resolve"},n,o)}catch(a){if(Dn.is(a))throw new iu(a);throw a}return{events:[...s.events,...i.events],cursor:i.cursor??s.cursor,hasMore:i.hasMore}}async function _D(e,t,r,n,o){let s=await km(e,{method:"GET",headers:t},r,n);return E7(s,n,o)}var DD=Yt("@workflow/world-vercel//skipStepInputsSupport",2,()=>({unsupportedSince:new Map})),qqe=600000;function Jqe(e){let t=DD.unsupportedSince.get(e);if(t===void 0)return!1;if(Date.now()-t<qqe)return!0;return DD.unsupportedSince.delete(e),!1}function zqe(e){return e instanceof G&&e.status===400&&e.code==="validation-error"}async function I7(e,t,r,n,o,s,i){if(t==="skip-step-inputs"&&!Jqe(e)){try{return await _D(r(t),n,o,s,i)}catch(c){if(!zqe(c))throw c}let a=await _D(r("resolve"),n,o,s,i);return DD.unsupportedSince.set(e,Date.now()),a}return _D(r(t==="skip-step-inputs"?"resolve":t),n,o,s,i)}function y7(e,t){if(t.cursor)e.set("cursor",t.cursor);if(t.limit!==void 0)e.set("limit",String(t.limit));if(t.sortOrder)e.set("sortOrder",t.sortOrder);if(t.remoteRefBehavior)e.set("remoteRefBehavior",t.remoteRefBehavior)}function Zqe(e){let t=new URLSearchParams;if(e.limit===void 0)t.set("returnAll","true");return y7(t,e),`?${t.toString()}`}async function kD(e,t={},r,n){let{baseUrl:o,headers:s}=await Ye(r),i=[],a=t.cursor??null,c=0,A,u=t.limit===void 0,l=wf("reading events","bounded");for(;;){let d=a??void 0;try{A=await I7(o,t.remoteRefBehavior,(h)=>`${o}/v4/runs/${encodeURIComponent(e)}/events`+Zqe({...t,remoteRefBehavior:h,cursor:d}),s,r,"listEvents",n)}catch(h){if(!u||!Dn.is(h))throw h;await l(h);continue}let f=!!A.cursor&&A.cursor!==a;if(A.kind==="partial"){if(t.limit!==void 0||!f||c===Yqe)throw A.error;c++,a=A.cursor}else if(!f&&(A.events.length>0||A.hasMore))throw new G("v4 listEvents: response did not advance cursor",{code:"SCHEMA_VALIDATION"});for(let h of A.events)i.push(h);if(A.kind!=="partial")break}return{events:i,cursor:A.cursor||(c>0?a:null),hasMore:A.hasMore,...A.kind==="complete"&&A.snapshot?{snapshot:A.snapshot}:{}}}async function C7(e,t,r={},n){let{baseUrl:o,headers:s}=await Ye(n),i=await I7(o,r.remoteRefBehavior,(a)=>{let c=new URLSearchParams;return c.set("correlationId",e),c.set("runId",t),y7(c,{...r,remoteRefBehavior:a}),`${o}/v4/events?${c.toString()}`},s,n,"listEventsByCorrelationId");if(i.kind==="partial")throw i.error;return{events:i.events,cursor:i.cursor,hasMore:i.hasMore}}Ur();No();Er();at();On();Dr();var w7=j(Li.omit({error:!0,errorCode:!0}).extend({error:vo([Se,Wt()]).optional(),errorCode:Q().optional(),blobStorageBytes:z().optional(),streamStorageBytes:z().optional()})),xm=j(w7),xD=j(w7.omit({input:!0,output:!0}).extend({inputRef:Wt().optional(),outputRef:Wt().optional(),input:vo([_c(Uint8Array),Wt()]).optional(),output:vo([_c(Uint8Array),Wt()]).optional(),dynamicWorkflowCode:Wt().optional()}));function ND(e,t){if(t==="none"){let{inputRef:r,outputRef:n,dynamicWorkflowCode:o,...s}=e;return{...CD(GE(s)),input:void 0,output:void 0}}return CD(GE(e))}async function Q7(e={},t){let{workflowName:r,status:n,pagination:o,resolveData:s=yn}=e,i=new URLSearchParams;if(r)i.set("workflowName",r);if(Array.isArray(n))throw new G("listWorkflowRuns: status does not support an array of statuses on world-vercel yet; pass a single status",{code:"INVALID_ARGUMENT",field:"status"});if(n)i.set("status",n);if(o?.limit)i.set("limit",o.limit.toString());if(o?.cursor)i.set("cursor",o.cursor);if(o?.sortOrder)i.set("sortOrder",o.sortOrder);let a=s==="none"?"lazy":"resolve";i.set("remoteRefBehavior",a);let c=i.toString(),A=`/v2/runs${c?`?${c}`:""}`,u=await Te({endpoint:A,options:{method:"GET"},config:t,schema:or(a==="lazy"?xD:xm)});return{...u,data:u.data.map((l)=>ND(l,s))}}async function _7(e,t){let r=await Te({endpoint:"/v1/runs/create",options:{method:"POST"},data:e,config:t,schema:xm});return GE(r)}async function _f(e,t,r){let n=t?.resolveData??yn;try{return await S7(e,{resolveData:n},r)}catch(o){if(o instanceof G&&o.status===404)throw new Uc(e);throw o}}async function S7(e,t,r){let{resolveData:n,waitMs:o,signal:s}=t,i=n==="none"?"lazy":"resolve",a=new URLSearchParams;if(a.set("remoteRefBehavior",i),o!==void 0)a.set("waitMs",String(o));let c=o===void 0?"":"/status",A=a.toString(),u=`/v2/runs/${encodeURIComponent(e)}${c}${A?`?${A}`:""}`,l=await Te({endpoint:u,options:{method:"GET",...s?{signal:s}:{}},config:r,retryConnectTimeout:!0,schema:i==="lazy"?xD:xm});return ND(l,n)}var Kqe=1e4,Xqe=300000,B7=Yt("@workflow/world-vercel//runStatusLongPollSupport",1,()=>({unsupportedUntilByBaseUrl:new Map}));function eJe(e){if(e.status===404||e.status===405||e.status===501)return!0;if(e.status===504)return!0;return e.status===void 0&&(e.code==="TIMEOUT"||e.code==="TRANSPORT")}async function b7(e,t,r){let n=t?.resolveData??yn,o=Math.max(0,Math.min(t?.timeoutMs??0,Zo()-Kqe)),{baseUrl:s}=Un(r),i=B7.unsupportedUntilByBaseUrl.get(s)??0;if(o===0||Date.now()<i)return _f(e,{resolveData:n},r);try{return await S7(e,{resolveData:n,waitMs:o,...t?.signal?{signal:t.signal}:{}},r)}catch(a){if(t?.signal?.aborted)throw a;if(!(a instanceof G)||!eJe(a))throw a;let c=await _f(e,{resolveData:n},r);return B7.unsupportedUntilByBaseUrl.set(s,Date.now()+Xqe),c}}async function D7(e,t,r){let n=[...new Set(e)],o=await Promise.all(n.map(async(i)=>{try{return await _f(i,t,r)}catch(a){if(a instanceof Uc)return null;throw a}})),s=new Map(n.map((i,a)=>[i,o[a]]));return e.map((i)=>s.get(i)??null)}async function R7(e,t,r){let n=t?.resolveData??yn,o=n==="none"?"lazy":"resolve",s=new URLSearchParams;s.set("remoteRefBehavior",o);let i=s.toString(),a=`/v1/runs/${encodeURIComponent(e)}/cancel${i?`?${i}`:""}`;try{let c=await Te({endpoint:a,options:{method:"PUT"},config:r,schema:o==="lazy"?xD:xm});return ND(c,n)}catch(c){if(c instanceof G&&c.status===404)throw new Uc(e);throw c}}async function T7(e,t){let{runIds:r,cancelReason:n}=jB.parse(e),o=await Te({endpoint:"/v4/runs/cancel",options:{method:"POST"},data:n!==void 0?{runIds:r,cancelReason:n}:{runIds:r},config:t,schema:WB}),s=new Map(o.results.map((c)=>[c.runId,c]));if(!(s.size===o.results.length&&o.results.length===r.length&&r.every((c)=>s.has(c))))throw new G(`Bulk cancel response did not contain exactly one result per requested run ID (requested ${r.length}, received ${o.results.length}).`);let a=r.map((c)=>s.get(c));return{summary:o.summary,results:a}}var tJe=j(H({attributes:Nr(Q(),Q())}));async function v7(e,t,r,n){try{return{attributes:(await Te({endpoint:`/v2/runs/${encodeURIComponent(e)}/attributes`,options:{method:"POST"},data:r?.allowReservedAttributes?{changes:t,allowReservedAttributes:!0}:{changes:t},config:n,schema:tJe})).attributes}}catch(o){if(o instanceof G&&o.status===404)throw new Uc(e);throw o}}Dr();function rJe(e){let t=e.startsWith("wrun_")?e.slice(5):e;try{return Dg(`wrun_${HA(t).ulid}`,"wrun_")}catch{return Dg(e,"wrun_")}}var nJe=new Set(["run_created","run_started","step_started"]);function oJe(){}oJe();function x7(e){if(e.eventType==="attr_set")try{OB(e.eventData)}catch(s){if(!(s instanceof ko))throw s;throw new G(s.message,{status:400})}let t=e.eventData??{},r=Bs(e.eventType),n={};if(typeof t.deploymentId==="string")n.deploymentId=t.deploymentId;if(typeof t.workflowName==="string")n.workflowName=t.workflowName;if(typeof t.stepName==="string")n.stepName=t.stepName;if(typeof t.attempt==="number")n.attempt=t.attempt;if(t.resumeAt instanceof Date)n.resumeAt=t.resumeAt;else if(typeof t.resumeAt==="string"){let s=new Date(t.resumeAt);if(!Number.isNaN(s.getTime()))n.resumeAt=s}if(t.retryAfter instanceof Date)n.retryAfter=t.retryAfter;else if(typeof t.retryAfter==="string"){let s=new Date(t.retryAfter);if(!Number.isNaN(s.getTime()))n.retryAfter=s}if(typeof t.token==="string")n.hookToken=t.token;if(t.tokenRetentionUntil instanceof Date)n.hookTokenRetentionUntil=t.tokenRetentionUntil;if(typeof t.isWebhook==="boolean")n.hookIsWebhook=t.isWebhook;if(typeof t.isSystem==="boolean")n.hookIsSystem=t.isSystem;if(t.force===!0)n.hookForce=!0;if(typeof t.errorCode==="string")n.errorCode=t.errorCode;if(typeof t.cancelReason==="string")n.cancelReason=t.cancelReason;if(typeof t.ownerMessageId==="string")n.ownerMessageId=t.ownerMessageId;if(t.executionContext!==void 0&&t.executionContext!==null&&typeof t.executionContext==="object")n.executionContext=t.executionContext;if(t.attributes!==void 0&&t.attributes!==null&&typeof t.attributes==="object")n.attributes=t.attributes;if(Array.isArray(t.changes))n.changes=t.changes;if(t.writer!==void 0&&t.writer!==null&&typeof t.writer==="object")n.writer=t.writer;if(typeof t.allowReservedAttributes==="boolean")n.allowReservedAttributes=t.allowReservedAttributes;if(typeof t.encryptionPublicKey==="string")n.encryptionPublicKey=t.encryptionPublicKey;if(t.dynamicWorkflowCode instanceof Uint8Array)n.dynamicWorkflowCode=t.dynamicWorkflowCode;if(typeof t.dynamicWorkflowCodeRef==="string")n.dynamicWorkflowCodeRef=t.dynamicWorkflowCodeRef;if(typeof t.ttfs==="number")n.ttfs=t.ttfs;if(typeof t.stso==="number")n.stso=t.stso;if(typeof t.stepCount==="number"&&Number.isSafeInteger(t.stepCount)&&t.stepCount>0)n.stepCount=t.stepCount;if(typeof t.eventCount==="number"&&Number.isSafeInteger(t.eventCount)&&t.eventCount>0)n.eventCount=t.eventCount;if(typeof t.rsfs==="number")n.rsfs=t.rsfs;if(typeof t.finalSchedulingReplay==="number")n.finalSchedulingReplay=t.finalSchedulingReplay;if(Array.isArray(t.optimizations)&&t.optimizations.every((s)=>typeof s==="string"))n.optimizations=t.optimizations;let o;if(r&&r in t){let s=t[r];if(s!==void 0){if(!(s instanceof Uint8Array))throw TypeError(`world-vercel v4: eventData.${r} for ${e.eventType} must be a Uint8Array (the runtime's dehydrated wire form); got ${typeof s==="object"?s===null?"null":s.constructor?.name??typeof s:typeof s}.`);o=s}}return{payload:o,meta:n}}async function N7(e,t,r,n){return g7(e,t,r?.resolveData==="none"?"lazy":"resolve",n)}async function OD(e,t){let{pagination:r,resolveData:n=yn}=e,o={...r,remoteRefBehavior:n==="none"?"lazy":n==="skip-step-inputs"?"skip-step-inputs":"resolve"},s=await("correlationId"in e?C7(e.correlationId,e.runId,o,t):kD(e.runId,o,t));return{data:"correlationId"in e?s.events.filter((i)=>i.runId===e.runId):s.events,cursor:s.cursor,hasMore:s.hasMore,...s.snapshot?{snapshot:s.snapshot}:{}}}async function O7(e,t,r,n){if(t.length===0)throw new G("world-vercel: createBatch requires at least one event",{status:400});if(t.some(({event:a})=>a.eventType==="hook_received"))throw new G("world-vercel: hook_received cannot be batched (it has no entity condition, so a batch retry would append the delivery twice); send it through the single-event path",{status:400});let o=t.map(({event:a,occurredAt:c,computeInstanceId:A})=>{let{payload:u,meta:l}=x7(a);return{runId:e,eventType:a.eventType,specVersion:a.specVersion??2,...a.correlationId?{correlationId:a.correlationId}:{},occurredAt:c??new Date,...A!==void 0?{computeInstanceId:A}:{},remoteRefBehavior:r?.resolveData==="all"?"resolve":"lazy",...r?.requestId?{vercelId:r.requestId}:{},payload:u,...l,...r?.inBand!==void 0?{inBand:r.inBand}:{},...r?.expectedSeqInBand!==void 0?{expectedSeqInBand:r.expectedSeqInBand}:{}}}),s=t.every(({event:a})=>a.eventType!=="step_started"&&a.eventType!=="step_retrying");return{results:(await mD(()=>f7({runId:e,events:o},n),t[0].event.eventType,{batchIdempotent:s,inBand:r?.inBand===!0})).results.map((a)=>{if(a.error!==void 0)return{status:a.status,error:a.error,message:a.message};return{status:200,event:a.event,...a.run?{run:a.run}:{},...a.step?{step:a.step}:{},...a.wait?{wait:a.wait}:{}}})}}async function U7(e,t,r,n){try{let o=await mD(()=>sJe(e,t,r,n),t.eventType,{idempotentHookResume:t.eventType==="hook_received"&&r?.resumeId!==void 0&&r?.resumePayloadDigest!==void 0,afterStepBody:r?.afterStepBody===!0,inBand:r?.inBand===!0});if(t.eventType==="run_created"&&!o.run)throw new G(`${t.eventType} response is missing the run entity`,{code:"SCHEMA_VALIDATION"});if(t.eventType==="run_started"&&!o.run?.startedAt)throw new G("run_started response is missing run.startedAt",{code:"SCHEMA_VALIDATION"});if(t.eventType==="step_started"&&!o.step?.startedAt)throw new G("step_started response is missing step.startedAt",{code:"SCHEMA_VALIDATION"});return o}catch(o){if(o instanceof qa)throw o.error;if(o instanceof iu)throw o.error;if(Oo.is(o)&&t.eventType==="hook_received"){let s=t.eventData?.token;throw new Oo(typeof s==="string"?s:o.token,o.claimedByRunId,o.claimedByHookId)}if(HB(t.eventType)&&G.is(o)&&o.status===404&&t.correlationId)throw new dl(t.correlationId);throw o}}async function sJe(e,t,r,n){if(r?.v1Compat){if(t.eventType==="run_cancelled"&&e)return{run:await R7(e,{...r,resolveData:ow(r.resolveData)},n)};if(t.eventType==="run_created")return{run:await _7(t.eventData,n)};if(e===null)throw new G(`world-vercel: v1Compat=true requires a runId for ${t.eventType}`,{status:400});return{event:await Te({endpoint:`/v1/runs/${encodeURIComponent(e)}/events`,options:{method:"POST"},data:t,config:n,schema:Ja})}}if(e===null)throw new G("world-vercel v4: createWorkflowRunEvent requires a client-generated runId for run_created (the runId is part of the payload storage ref key). Generate a wrun_ ULID before calling.",{status:400});if(t.eventType==="run_created"){let c=rJe(e);if(c)throw new G(c,{status:400})}let o=nJe.has(t.eventType)?"resolve":"lazy",{payload:s,meta:i}=x7(t),a={runId:e,specVersion:t.specVersion??2,...t.eventType==="run_started"?{executorSpecVersion:n?.mintedSpecVersion??Al()}:{},...t.correlationId?{correlationId:t.correlationId}:{},...r?.requestId?{vercelId:r.requestId}:{},...r?.computeInstanceId?{computeInstanceId:r.computeInstanceId}:{},...r?.eventCount!==void 0?{maxSlot:r.eventCount}:{},replayDivergenceCount:r?.replayDivergenceCount,...r?.inBand!==void 0?{inBand:r.inBand}:{},...r?.expectedSeqInBand!==void 0?{expectedSeqInBand:r.expectedSeqInBand}:{},occurredAt:r?.occurredAt??new Date,...r?.sinceCursor?{sinceCursor:r.sinceCursor}:{},...r?.resumeId?{resumeId:r.resumeId}:{},...r?.resumePayloadDigest?{resumePayloadDigest:r.resumePayloadDigest}:{},...r?.viaStepDispatch?{viaStepDispatch:!0}:{},...r?.resolveData==="skip-step-inputs"?{eventsRemoteRefBehavior:"skip-step-inputs"}:{},remoteRefBehavior:o,payload:s,...i};if(t.eventType==="run_started"&&!r?.skipPreload){let c=await d7(a,n,r?.replayEventObserver),A=k7(c.events);if(!A)throw new G("v4 createEvent: run_started stream is missing lifecycle events",{code:"SCHEMA_VALIDATION"});return{event:A.event,run:A.run,events:c.events,cursor:c.cursor,hasMore:c.hasMore,maxEvents:c.maxEvents}}if(t.eventType==="hook_received"&&r?.preloadEvents===!0&&r.resumeId!==void 0&&r.resumePayloadDigest!==void 0){let c=await h7({...a,remoteRefBehavior:"lazy"},n,r.replayEventObserver);if(c.kind==="materialized")return c.result;let{canonicalEventId:A,maxEvents:u,events:l,cursor:d,hasMore:f}=c,h=l.find((p)=>p.eventId===A),g=k7(l);return{...h?{event:h}:{},...g?{run:g.run}:{},events:l,cursor:d,hasMore:f,...u!==void 0?{maxEvents:u}:{}}}return l7(t.eventType==="run_started"?{...a,eventType:"run_started",skipPreload:!0}:{...a,eventType:t.eventType},n)}function k7(e){let t=e.find((s)=>s.eventType==="run_created"),r=e.find((s)=>s.eventType==="run_started");if(!t||!r)return;let n=t.eventData.attributes??{},o=r.createdAt;for(let s of e)if(s.eventType==="attr_set")n=UB(n,s.eventData.changes),o=s.createdAt;return{event:r,run:{runId:t.runId,status:"running",deploymentId:t.eventData.deploymentId,workflowName:t.eventData.workflowName,specVersion:t.specVersion,executionContext:t.eventData.executionContext,input:t.eventData.input,attributes:n,encryptionPublicKey:t.eventData.encryptionPublicKey,startedAt:r.createdAt,createdAt:t.createdAt,updatedAt:o}}}Ur();Er();at();Dr();function M7(e,t){if(t==="none"){let{metadataRef:r,...n}=e;return n}return J6(e)}var iJe=j(ws.omit({metadata:!0}).extend({metadataRef:Wt().optional()}));async function F7(e,t){let{runId:r,pagination:n,resolveData:o=yn}=e,s=new URLSearchParams;if(n?.limit)s.set("limit",n.limit.toString());if(n?.cursor)s.set("cursor",n.cursor);if(n?.sortOrder)s.set("sortOrder",n.sortOrder);let i=o==="none"?"lazy":"resolve";if(s.set("remoteRefBehavior",i),r)s.set("runId",r);let a=s.toString(),c=`/v2/hooks${a?`?${a}`:""}`,A=await Te({endpoint:c,options:{method:"GET"},config:t,schema:or(i==="lazy"?iJe:ws)});return{...A,data:A.data.map((u)=>M7(u,o))}}async function L7(e,t,r){let n=t?.resolveData||"all",o=`/v2/hooks/${encodeURIComponent(e)}`,s=await Te({endpoint:o,options:{method:"GET"},config:r,schema:ws});return M7(s,n)}async function P7(e,t){try{return await Te({endpoint:`/v2/hooks/by-token?token=${encodeURIComponent(e)}`,options:{method:"GET"},config:t,schema:ws})}catch(r){if(G.is(r)&&r.status===404)throw new dl(e);throw r}}Ur();Er();Q0();Eo();On();Nn();Dr();function aJe(e){let t={};for(let[r,n]of e)t[r]=n;return t}function Nm(e){if(!FA)return;console.debug("[workflow:world-vercel:http] WORLD_SNAPSHOT_DIAG",e)}var H7=67108864;function V7(e){return{async save(t,r,n){let o=performance.now(),{baseUrl:s,headers:i}=await Ye(e),a=`${s}/v2/runs/${encodeURIComponent(t)}/snapshot`,c=Aw(n,r);if(c.byteLength>H7)throw Nm({op:"save",runId:t,outcome:"too_large",wireBytes:c.byteLength}),new G(`Snapshot for run ${t} is ${c.byteLength} bytes, over the ${H7}-byte limit; not uploading`,{url:a});i.set("Content-Type","application/octet-stream"),i.set("X-Snapshot-Events-Cursor",n.eventsCursor??""),i.set("X-Snapshot-Created-At",n.createdAt.toISOString()),await In(i);let A=performance.now(),u=await w0(a,{method:"PUT",body:c,headers:aJe(i),dispatcher:po(e)}),l=Math.round(performance.now()-A);if(u.statusCode<200||u.statusCode>=300){let d=await u.body.text().catch(()=>"");throw new G(`PUT /v2/runs/${t}/snapshot -> HTTP ${u.statusCode}: ${d}`,{url:a,status:u.statusCode})}await u.body.text(),Nm({op:"save",runId:t,wireBytes:c.byteLength,putDurationMs:l,totalDurationMs:Math.round(performance.now()-o)})},async load(t){let r=performance.now(),{baseUrl:n,headers:o}=await Ye(e),s=`${n}/v2/runs/${encodeURIComponent(t)}/snapshot`;o.set("Accept","application/octet-stream"),await In(o);let i=performance.now(),a=await fetch(s,{method:"GET",headers:o,dispatcher:po(e)}),c=Math.round(performance.now()-i);if(a.status===404)return await a.text().catch(()=>{}),Nm({op:"load",runId:t,outcome:"not_found",getDurationMs:c,totalDurationMs:Math.round(performance.now()-r)}),null;if(!a.ok){let d=await a.text().catch(()=>"");throw new G(`GET /v2/runs/${t}/snapshot -> HTTP ${a.status}: ${d}`,{url:s,status:a.status})}let A=await a.arrayBuffer(),u=new Uint8Array(A),l=uw(u);return Nm({op:"load",runId:t,outcome:l?"ok":"undecodable_envelope",wireBytes:u.byteLength,getDurationMs:c,totalDurationMs:Math.round(performance.now()-r)}),l},async delete(t){let{baseUrl:r,headers:n}=await Ye(e),o=`${r}/v2/runs/${encodeURIComponent(t)}/snapshot`;await In(n);let s=await fetch(o,{method:"DELETE",headers:n,dispatcher:po(e)});if(!s.ok&&s.status!==404){let i=await s.text().catch(()=>"");throw new G(`DELETE /v2/runs/${t}/snapshot -> HTTP ${s.status}: ${i}`,{url:o,status:s.status})}await s.text()}}}function UD(e){let t=V7(e),r={runs:{get:(n,o)=>_f(n,o,e),waitForTerminalStatus:(n,o)=>b7(n,o,e),getMany:(n,o)=>D7(n,o,e),list:(n)=>Q7(n,e),experimentalSetAttributes:(n,o,s)=>v7(n,o,s,e),cancelMany:(n)=>T7(n,e)},steps:{get:(n,o,s)=>X6(n,o,s,e),list:(n)=>K6(n,e)},events:{create:(n,o,s)=>U7(n,o,s,e),createBatch:(n,o,s)=>O7(n,o,s,e),get:(n,o,s)=>N7(n,o,s,e),list:(n)=>OD(n,e),listByCorrelationId:(n)=>OD(n,e)},hooks:{get:(n,o)=>L7(n,o,e),getByToken:(n)=>P7(n,e),list:(n)=>F7(n,e)},experimental_snapshots:t};return{runs:Ai("world.runs",r.runs),steps:Ai("world.steps",r.steps),events:Ai("world.events",r.events),hooks:Ai("world.hooks",r.hooks),experimental_snapshots:Ai("world.experimental_snapshots",t)}}Ur();Er();at();Eo();On();var Sf=1000;function bf(e){let t=new TextEncoder;return e.map((r)=>typeof r==="string"?t.encode(r):r)}function Om(e){return MD(bf(e))}function MD(e){let t=0;for(let s of e)if(t+=4+s.length,t>4294967295)throw RangeError(`encoded stream chunks exceed the u32 body-length limit: ${t} bytes`);let r=new Uint8Array(t),n=new DataView(r.buffer),o=0;for(let s of e)n.setUint32(o,s.length,!1),o+=4,r.set(s,o),o+=s.length;return r}Nn();Dr();var nee=Ke(Pc(),1);ou();On();at();ou();var j7=Sf,$7=10485760,cJe=128,G7=4,FD=z().int().nonnegative(),Df=FD,LD=Q().regex(/^wrtr_[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/),W7=H({type:ue("write"),reqId:Df,chunkSeq:FD,numChunks:z().int().positive().max(j7)}),Y7=H({type:ue("close"),reqId:Df}),Bst=Mi("type",[W7,Y7]),AJe=H({type:ue("write_ack"),reqId:Df}),uJe=H({type:ue("close_ack"),reqId:Df}),lJe=H({type:ue("error"),reqId:Df.optional(),status:z().int(),message:Q().optional(),retryAfter:Q().optional()}),dJe=H({type:ue("drain"),reason:Cs(["auth_expiry","max_duration"]),graceMs:FD}),fJe=Mi("type",[AJe,uJe,lJe,dJe]);function q7(e,t,r,n){let o=LD.parse(n),s=new URL(e);return s.protocol=s.protocol==="https:"?"wss:":"ws:",s.pathname=`${s.pathname.replace(/\/$/,"")}/websockets/v1/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(r)}`,s.search=new URLSearchParams({writerId:o}).toString(),s}function J7(e,t){let r=W7.parse(e);if(r.numChunks!==t.length)throw Error(`stream WebSocket write declares ${r.numChunks} chunks but received ${t.length}`);let n=bf(t);for(let o of n){let s=o.byteLength;if(s>$7)throw Error(`stream WebSocket chunk is ${s} bytes; maximum is ${$7}`)}return zr(r,MD(n))}function z7(e,t,r){let n=Math.min(e.length,t+j7),o=cJe+G7+e[t].byteLength,s=t+1;while(s<n){if(o+=G7+e[s].byteLength,o>r)break;s++}return s}function Z7(e){return zr(Y7.parse(e),new Uint8Array)}function K7(e,t){if(t.byteLength!==0)throw Error("stream WebSocket reply body must be empty");return fJe.parse(e)}Nn();Dr();fD();Nn();var X7=1e4,eee=250,hJe=250;function PD(e,t){if(e.readyState===3)return;let r=!1,n=new Promise((s)=>{let i=!1,a=()=>{if(i)return;i=!0,clearTimeout(c),s()},c=setTimeout(()=>{r=!0,a()},hJe);c.unref?.(),e.once("close",a)}),o=mo("workflow.stream.ws.close.cleanup",async(s)=>{await n,s?.setAttribute("workflow.stream.ws.close_cleanup_timeout",r)});Promise.resolve().then(() => Ke(Nb(),1)).then(({waitUntil:s})=>s(o)).catch(()=>{}),o.catch(()=>{}),e.close(1000,t)}var tee=3;function ss(){return performance.now()}function gJe(e,t,r){if(!e)return{};return{"workflow.stream.ws.session_first_write":e.sessionFirstWrite,"workflow.stream.ws.connection_first_write":t?.firstWriteSent===!1,"workflow.stream.ws.connection_attempt":t?.attempt??0,"workflow.stream.ws.session_to_write_ms":e.startedAt-r}}function pJe(e,t,r){if(r)r.firstWriteSent=!0;let n=r?.openedAt,o=r?.socketStartedAt,s=r?.configFinishedAt;e?.setAttributes({"workflow.stream.ws.write_wait_for_open_ms":n?Math.max(0,n-t.startedAt):0,...o&&s?{"workflow.stream.ws.connect_setup_ms":o-s}:{},...o&&n?{"workflow.stream.ws.connect_ms":n-o}:{},...s&&r?{"workflow.stream.ws.config_token_ms":s-r.configStartedAt}:{}})}function EJe(e,t,r,n){let o=ss();n.sentAt=o,e?.setAttributes({"workflow.stream.ws.write_to_send_ms":o-t.startedAt,...r?.openedAt?{"workflow.stream.ws.open_to_send_ms":Math.max(0,o-r.openedAt)}:{}})}function mJe(e,t,r){if(r?.sentAt===void 0||r.replyReceivedAt===void 0)return;let n=ss();e?.setAttributes({"workflow.stream.ws.send_to_reply_ms":r.replyReceivedAt-r.sentAt,"workflow.stream.ws.reply_processing_ms":n-r.replyReceivedAt,"workflow.stream.ws.write_total_ms":n-t.startedAt})}var IJe=86400000;function ree(e){return e.get("authorization")}class za extends Error{constructor(e){super(e instanceof Error?e.message:String(e),{cause:e});this.name="StreamWsRequestNotSentError"}}class HD extends Error{retryAfter;constructor(e,t){super(e);this.retryAfter=t,this.name="StreamWsThrottledError"}}class VD extends Error{constructor(e){super(e);this.name="StreamWsCloseRetriableError"}}function yJe(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")return new TextEncoder().encode(e);return new Uint8Array(e)}class oee{runId;name;writerId;config;writeHttp;closeHttp;connectAfterFirstWrite;mode="connecting";socket;connect=Promise.resolve();transportDecision=Promise.resolve();tail=Promise.resolve();inbound=Promise.resolve();nextReqId=1;pending;poisonError;throttledSocket;terminated=new AbortController;wsUrl;closeAcknowledged=!1;idleReconnects=0;drainReason;drainTimer;releaseDrainWait;lastAuthorization=null;sessionCreatedAt=ss();sessionHasWrite=!1;connectionAttempt=0;connectionTiming;constructor(e,t,r,n,o,s,i){if(this.runId=e,this.name=t,this.writerId=r,this.config=n,this.writeHttp=o,this.closeHttp=s,this.connectAfterFirstWrite=i,i)this.mode="deferred";else this.startInitialConnect()}write(e,t){let r={startedAt:ss(),sessionFirstWrite:!this.sessionHasWrite};return this.sessionHasWrite=!0,this.enqueue(()=>this.writeInternal(e,t,r))}async writeInternal(e,t,r){if(this.assertUsable(),this.mode==="deferred"){await this.writeFirstGroup(t,r);return}if(this.mode==="waiting_to_connect"){await this.writeSecondGroupAndStartConnect(t,r);return}if(this.shouldWriteHttpWhileConnecting()){await this.writeWhileInitialConnectRuns(t,r);return}if(await this.transportDecision,this.assertUsable(),this.mode==="http"){await this.writeHttpOrFail(t);return}let n=Bf(),o=bf(t);for(let s=0;s<t.length;){let i=z7(o,s,n),a=o.slice(s,i),c;try{c=await this.requestRetryingThrottle("write",(A)=>J7({type:"write",reqId:A,chunkSeq:e+s,numChunks:a.length},a),s===0?r:void 0,{chunkSeq:e+s,numChunks:a.length},n)}catch(A){if(!(A instanceof za))throw A;this.fallbackToHttpBeforeSend(),await this.writeHttpOrFail(t.slice(s));return}if(c.type!=="write_ack")throw this.poison(Error(`stream WebSocket write received ${c.type}`));s=i}}async writeHttpOrFail(e){try{await this.writeHttp(e)}catch(t){throw this.failUnknown(t),this.poisonError}}shouldWriteHttpWhileConnecting(){return this.mode==="connecting"&&this.connectionAttempt===1}async writeWhileInitialConnectRuns(e,t){try{await this.writeHttp(e,{"workflow.stream.ws.session_first_write":t.sessionFirstWrite,"workflow.stream.ws.connection_attempt":this.connectionAttempt,"workflow.stream.ws.connecting_at_write":!0,"workflow.stream.ws.session_to_write_ms":t.startedAt-this.sessionCreatedAt})}catch(r){throw this.failUnknown(r),this.poisonError}}async writeSecondGroupAndStartConnect(e,t){try{await this.writeHttp(e,{"workflow.stream.ws.session_first_write":t.sessionFirstWrite,"workflow.stream.ws.connection_attempt":0,"workflow.stream.ws.connecting_at_write":!1,"workflow.stream.ws.connect_after_http_group":2,"workflow.stream.ws.session_to_write_ms":t.startedAt-this.sessionCreatedAt},()=>{if(this.mode!=="waiting_to_connect")return;this.startInitialConnect()})}catch(r){throw this.failUnknown(r),this.poisonError}}async writeFirstGroup(e,t){try{await this.writeHttp(e,{"workflow.stream.ws.session_first_write":t.sessionFirstWrite,"workflow.stream.ws.connection_attempt":0,"workflow.stream.ws.connecting_at_write":!1,"workflow.stream.ws.connect_deferred_at_write":!0,"workflow.stream.ws.http_group_ordinal":1,"workflow.stream.ws.session_to_write_ms":t.startedAt-this.sessionCreatedAt})}catch(r){throw this.failUnknown(r),this.poisonError}if(this.mode==="deferred")this.mode="waiting_to_connect"}release(){return this.enqueue(async()=>{if(this.mode==="closed"||this.mode==="poisoned")return;this.fallbackToHttpBeforeSend("stream writer released")})}dispose(){if(this.mode==="closed")return;this.mode="closed",this.terminated.abort(),this.finishDrainWait();let e=this.pending;if(this.pending=void 0,e)clearTimeout(e.timer),e.reject(Error("stream writer transport disposed"));this.socket?.close(1000,"stream writer disposed")}close(){return this.enqueue(async()=>{if(this.assertUsable(),this.mode==="deferred"||this.mode==="waiting_to_connect"||this.connectAfterFirstWrite&&this.mode==="connecting"&&this.connectionAttempt===1){await this.closeHttp(),this.mode="closed",this.socket?.close(1000,"stream closed over HTTP");return}if(await this.transportDecision,this.assertUsable(),this.mode==="http"){await this.closeHttp(),this.mode="closed";return}await this.closeOverWs()})}async closeOverWs(){let e;try{e=await this.requestRetryingThrottle("close",(t)=>Z7({type:"close",reqId:t}))}catch(t){if(!(t instanceof za||t instanceof VD))throw t;this.fallbackToHttpBeforeSend(),await this.closeHttp(),this.mode="closed";return}if(e.type!=="close_ack")throw this.poison(Error(`stream WebSocket close received ${e.type}`));if(this.mode="closed",this.socket)PD(this.socket,"stream closed")}enqueue(e){let t=this.tail.then(e);return this.tail=t.catch(()=>{}),t}assertUsable(){if(this.mode==="poisoned")throw this.poisonError;if(this.mode==="closed")throw Error("stream writer is closed")}startInitialConnect(){this.mode="connecting",this.connect=this.startConnect(),this.transportDecision=this.makeTransportDecision(!1)}makeTransportDecision(e){return new Promise((t)=>{let r=!1,n=()=>{if(r)return;r=!0,clearTimeout(o),t()},o=setTimeout(()=>{if(this.mode==="connecting")this.mode="http",this.socket?.close(1000,"connect budget expired");n()},e?eee:X7);o.unref?.(),this.connect.then(n)})}startConnect(e=!1){let t=ss(),r={attempt:++this.connectionAttempt,configStartedAt:t,firstWriteSent:!1};return this.connectionTiming=r,this.connectSocket(e,r).catch(()=>{if(this.mode==="connecting")this.mode="http"})}async connectSocket(e,t){if(!_m()){this.mode="http";return}if(e)await nee.getVercelOidcToken({expirationBufferMs:IJe}).catch(()=>{return});let r=Ye(this.config).then((i)=>(t.configFinishedAt=ss(),i)),[{WebSocket:n},o]=await Promise.all([Promise.resolve().then(() => (um(),vb)),r]);if(this.mode!=="connecting")return;if(e&&ree(o.headers)===this.lastAuthorization){this.mode="http";return}if(this.lastAuthorization=ree(o.headers),o.usingProxy){this.mode="http";return}if(this.mode!=="connecting")return;let s=q7(o.baseUrl,this.runId,this.name,this.writerId);this.wsUrl=s.toString(),await ri({method:"GET",url:this.wsUrl,spanName:"workflow.stream.ws.connect",attributes:{"workflow.stream.transport":"ws"}},async()=>{if(await In(o.headers),this.mode!=="connecting")return;t.socketStartedAt=ss();let i=new n(s,{headers:LA(o.headers)});this.socket=i,i.binaryType="nodebuffer",await new Promise((a)=>{let c=!1,A=()=>{if(c)return;if(this.mode==="connecting")this.mode="http";a()};i.once("open",()=>{if(c=!0,t.openedAt=ss(),this.mode!=="connecting"){i.close(1000,"HTTP fallback selected"),a();return}this.mode="ws",a()}),i.once("unexpected-response",(u,l)=>{let d=l;d.resume?.(),d.destroy?.(),i.close(1000,"upgrade declined"),A()}),i.once("error",(u)=>{if(!c){A();return}this.inbound.then(()=>{if(i!==this.socket)return;if(this.isIdleThrottledSocket(i)){this.leaveThrottledSocketForHttp();return}this.failUnknown(u)})}),i.once("close",(u)=>{if(!c){A();return}this.inbound.then(()=>this.handleSocketClose(Number(u),i))}),i.on("message",(u)=>{let l=ss();this.inbound=this.inbound.then(()=>this.handleMessage(yJe(u),l))})})})}async handleMessage(e,t){try{let r=nu(e),n=K7(r.meta,r.body);if(n.type==="drain"){this.handleDrain(n.reason,n.graceMs);return}let o=this.pending;if(!o||n.reqId===void 0||n.reqId!==o.reqId){if(n.type==="error")throw Error(`stream WebSocket connection failed (${n.status}): ${n.message??"unknown error"}`);throw Error("stream WebSocket reply cannot be correlated")}if(this.pending=void 0,o.replyReceivedAt=t,clearTimeout(o.timer),n.type==="close_ack")this.closeAcknowledged=!0;if(n.type==="error")o.reject(this.requestError(o,n));else{if(n.type==="write_ack")this.idleReconnects=0;o.resolve(n)}}catch(r){this.failUnknown(r)}}handleDrain(e,t){if(this.mode==="draining"){if(e==="auth_expiry")this.drainReason=e;return}if(this.mode!=="ws")return;this.mode="draining",this.drainReason=e,this.transportDecision=new Promise((n)=>{this.releaseDrainWait=n});let r=this.socket;this.drainTimer=setTimeout(()=>{if(this.drainTimer=void 0,this.mode!=="draining"||r!==this.socket)return;if(this.pending){this.failUnknown(Error("stream WebSocket drain expired before request reply"));return}r?.close(1001,"stream drain grace expired"),this.handleSocketClose(1001,r)},Math.min(t,2147483647)),this.drainTimer.unref?.()}handleSocketClose(e,t=this.socket){if(t!==this.socket)return;if(this.drainTimer)clearTimeout(this.drainTimer),this.drainTimer=void 0;if(this.mode==="closed"||this.mode==="http"||this.mode==="poisoned"||this.closeAcknowledged)return;if(this.pending){this.failUnknown(Error("stream WebSocket closed before reply"));return}if(t&&this.isIdleThrottledSocket(t)&&this.mode==="ws"){this.leaveThrottledSocketForHttp();return}if(this.mode==="draining"&&e!==1001){this.drainReason=void 0,this.mode="http",this.socket=void 0,this.finishDrainWait();return}if(this.mode==="draining"){let r=this.drainReason==="auth_expiry";if(this.drainReason=void 0,this.idleReconnects>=tee){this.mode="http",this.socket=void 0,this.finishDrainWait();return}this.idleReconnects++,this.mode="connecting",this.socket=void 0,this.connect=this.startConnect(r);let n=this.makeTransportDecision(!0);this.transportDecision=n,n.then(()=>this.finishDrainWait());return}if(this.idleReconnects>=tee){this.mode="http",this.socket=void 0;return}this.idleReconnects++,this.mode="connecting",this.socket=void 0,this.connect=this.startConnect(),this.transportDecision=this.makeTransportDecision(!0)}async request(e,t,r,n,o=Bf()){this.assertUsable();let s=this.socket;if(this.mode!=="ws"||!s||s.readyState!==1)throw new za(Error("stream WebSocket is not open before send"));let i=this.nextReqId++,a;try{a=t(i)}catch(l){throw new za(l)}if(a.byteLength>o)throw new za(Error(`stream WebSocket message is ${a.byteLength} bytes; maximum is ${o}`));let c=this.connectionTiming,A=c?.firstWriteSent===!1,u=r&&(r.sessionFirstWrite||A)?r:void 0;return ri({method:"POST",url:this.wsUrl??"ws://unknown",spanName:"workflow.stream.write",attributes:{"workflow.stream.transport":"ws","workflow.stream.ws.req_id":i,...n?{"workflow.stream.ws.chunk_seq":n.chunkSeq,"workflow.stream.ws.num_chunks":n.numChunks}:{},...gJe(u,c,this.sessionCreatedAt)}},async(l)=>{if(u)pJe(l,u,c);let d,f=new Promise((h,g)=>{let p=setTimeout(()=>{this.failUnknown(Error(`stream WebSocket request ${i} timed out with no reply`))},Zo());p.unref?.(),d={reqId:i,operation:e,resolve:h,reject:g,timer:p},this.pending=d;try{if(u)EJe(l,u,c,d);s.send(a,(I)=>{if(!I)return;this.failUnknown(I)})}catch(I){this.failUnknown(I)}});try{return await f}finally{if(u)mJe(l,u,d)}})}finishDrainWait(){if(this.drainTimer)clearTimeout(this.drainTimer),this.drainTimer=void 0;let e=this.releaseDrainWait;this.releaseDrainWait=void 0,e?.()}fallbackToHttpBeforeSend(e="HTTP fallback before send"){this.mode="http",this.drainReason=void 0;let t=this.socket;if(this.socket=void 0,this.transportDecision=Promise.resolve(),this.finishDrainWait(),t)PD(t,e)}requestError(e,t){let r=`(${t.status}): ${t.message??"unknown error"}`;if(t.status===429)return this.throttledSocket=this.socket,new HD(`stream WebSocket ${e.operation} throttled ${r}`,Ha(t.retryAfter));if(e.operation==="close"&&t.status>=500&&t.status<=599)return this.fallbackToHttpBeforeSend("stream close retried over HTTP"),new VD(`stream WebSocket close failed ${r}`);let n=this.poison(Error(`stream WebSocket request failed ${r}`));return this.socket?.close(1011,"stream request failed"),n}async requestRetryingThrottle(e,t,r,n,o){let s=wf(e==="write"?"writing stream chunks":"writing stream close","bounded");for(let i=0;;i++)try{return await this.request(e,t,i===0?r:void 0,n,o)}catch(a){if(!(a instanceof HD))throw a;await this.waitOutThrottle(s,a)}}async waitOutThrottle(e,t){try{await e(t,this.terminated.signal)}catch{throw this.assertUsable(),this.fallbackToHttpBeforeSend("stream request throttled"),new za(t)}finally{this.throttledSocket=void 0}await this.transportDecision,this.assertUsable()}isIdleThrottledSocket(e){return!this.pending&&e===this.throttledSocket&&e===this.socket}leaveThrottledSocketForHttp(){this.drainReason=void 0,this.mode="http",this.socket=void 0,this.finishDrainWait()}failUnknown(e){let t=this.poison(e);this.finishDrainWait();let r=this.pending;if(this.pending=void 0,r)clearTimeout(r.timer),r.reject(t);this.socket?.close(1011,"unknown stream write outcome")}poison(e){if(this.mode!=="poisoned")this.mode="poisoned",this.poisonError=e,this.terminated.abort();return this.poisonError}}function see(e,t,r,n,o,s,i=!0){return new oee(e,t,LD.parse(r),n,o,s,i)}var CJe=Sf,iee=()=>Yn("WORKFLOW_MAX_CHUNKS_PER_REQUEST",CJe,{integer:!0,min:1});function Rf(e,t,r){return new URL(`${r.baseUrl}/v2/runs/${encodeURIComponent(t)}/stream/${encodeURIComponent(e)}`)}function BJe(e,t,r){return new URL(`${r.baseUrl}/v3/runs/${encodeURIComponent(t)}/stream/${encodeURIComponent(e)}`)}function cu(e){return{...Wd(e.runId),...S8(e.name),...b8(e.operation),...typeof e.startIndex==="number"?D8(e.startIndex):{}}}async function wJe(e){let t=`Failed to fetch stream: ${e.status}`;if(e.status!==410)return new gt(t,{status:e.status});try{let r=await e.json();return Va(e.status,typeof r.message==="string"?r.message:t,{code:r.error,details:r.details})}catch{return new gt(t,{status:e.status})}}function $D(e,t){if(G.is(t)||Vi.is(t)||$i.is(t)||gt.is(t)||fl.is(t)||Gi.is(t)||Dn.is(t)||hl.is(t))return t;return new gt(e,{cause:t})}function Tf(e,t,r,n){let o=[`PUT ${t.origin}${t.pathname}`,...HE(r.headers)];return new gt(`Stream ${e} failed: HTTP ${r.status} (${o.join("; ")}): ${n}`,{url:t.toString(),status:r.status})}var QJe=j(H({tailIndex:z(),done:jt()})),_Je=j(H({data:_n(H({index:z(),data:_c(Uint8Array)})),cursor:Q().nullable(),hasMore:jt(),done:jt()}));async function SJe(e,t,r,n,o,s){let i=await Ye(n);i.headers.set("X-Stream-Multi","true");let a=Math.min(iee(),Sf);for(let c=0;c<r.length;c+=a){let A=Rf(t,e,i);await(await Kt({method:"PUT",url:A.toString(),body:Om(r.slice(c,c+a)),headers:i.headers,dispatcher:vE(n),timeoutMs:null,logLabel:A.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",onRequestDispatched:c===0?s:void 0,attributes:{...cu({runId:e,name:t,operation:"write_multi"}),...c===0?o:void 0},buildError:async(l)=>Tf("write",A,l,await l.text())})).text()}}async function bJe(e,t,r){let n=await Ye(r);n.headers.set("X-Stream-Done","true");let o=Rf(t,e,n);await(await Kt({method:"PUT",url:o.toString(),headers:n.headers,dispatcher:S0(r),timeoutMs:null,logLabel:o.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",attributes:cu({runId:e,name:t,operation:"close"}),buildError:async(i)=>Tf("close",o,i,await i.text())})).text()}function GD(e){return{streams:{..._m()&&!Un(e).usingProxy?{createWriteSession(t,r,{writerId:n}){return see(t,r,n,e,(o,s,i)=>SJe(t,r,o,e,s,i),()=>bJe(t,r,e))}}:{},async write(t,r,n){let o=await t,s=await Ye(e),i=Rf(r,o,s);await(await Kt({method:"PUT",url:i.toString(),body:n,headers:s.headers,dispatcher:vE(e),timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:i.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",attributes:cu({runId:o,name:r,operation:"write"}),buildError:async(c)=>Tf("write",i,c,await c.text())})).text()},async writeMulti(t,r,n){if(n.length===0)return;let o=await t,s=await Ye(e);s.headers.set("X-Stream-Multi","true");let i=iee();for(let a=0;a<n.length;a+=i){let c=n.slice(a,a+i),A=Om(c),u=Rf(r,o,s);await(await Kt({method:"PUT",url:u.toString(),body:A,headers:s.headers,dispatcher:vE(e),timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:u.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",attributes:cu({runId:o,name:r,operation:"write_multi"}),buildError:async(d)=>Tf("write",u,d,await d.text())})).text()}},async close(t,r){let n=await t,o=await Ye(e);o.headers.set("X-Stream-Done","true");let s=Rf(r,n,o);await(await Kt({method:"PUT",url:s.toString(),headers:o.headers,dispatcher:S0(e),timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:s.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",attributes:cu({runId:n,name:r,operation:"close"}),buildError:async(a)=>Tf("close",s,a,await a.text())})).text()},async get(t,r,n){let o=await Ye(e);o.headers.set("Accept","application/json");let s=BJe(r,t,o);if(typeof n==="number")s.searchParams.set("startIndex",String(n));let i=await Kt({method:"GET",url:s.toString(),headers:o.headers,dispatcher:void 0,timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:s.pathname,spanName:"workflow.stream.read.connect",attributes:cu({runId:t,name:r,operation:"read",startIndex:n}),buildError:wJe});if(!i.body)throw new gt("No response body for stream",{url:s.toString()});return i.body},async getChunks(t,r,n){let o=new URLSearchParams;if(n?.limit!=null)o.set("limit",String(n.limit));if(n?.cursor)o.set("cursor",n.cursor);let s=o.toString(),i=`/v2/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(r)}/chunks${s?`?${s}`:""}`;try{return await Te({endpoint:i,config:e,schema:_Je})}catch(a){throw $D(`Failed to read stream chunks for ${r}`,a)}},async getInfo(t,r){let n=`/v2/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(r)}/info`;try{return await Te({endpoint:n,config:e,schema:QJe})}catch(o){throw $D(`Failed to read stream info for ${r}`,o)}},async list(t){let r=await Ye(e),n=new URL(`${r.baseUrl}/v2/runs/${encodeURIComponent(t)}/streams`),o=await Kt({method:"GET",url:n.toString(),headers:r.headers,dispatcher:void 0,timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:n.pathname,buildError:(s)=>new gt(`Failed to list streams: ${s.status}`,{url:n.toString(),status:s.status})});try{return await o.json()}catch(s){throw $D("Failed to parse stream list response",s)}}}}}Dr();bm();function aee(e){let t=e?.projectConfig?.projectId||process.env.VERCEL_PROJECT_ID,r=Al();return e={...e,mintedSpecVersion:r},{specVersion:r,capabilities:{hookRetention:{active:!0},maxConcurrency:!0,deploymentAffinity:!0,inBandFence:!0,hookForceClaim:!0,dynamicWorkflowCode:!0},validateRunExecutionContext:X0,getRuntimeDeadline:dm,...pD(e),...UD(e),analytics:process.env.WORKFLOW_DISABLE_ANALYTICS_READS==="1"?void 0:P0(e),...Ai("world.streams",GD(e)),createRunId:Y0,describeRun:q0,getEnvironment:()=>F0(e),uploadDynamicWorkflowCode:(n,o)=>J0(n,o,e),getEncryptionKeyForRun:Z0(t,e?.projectConfig?.teamId,e?.token,e?.dispatcher),resolveLatestDeploymentId:$6(e),telemetry:{recordStepExecution:L6}}}var DJe=Symbol.for("libfx.durability");function cee(e,t={}){let r=typeof e==="function";if(!r&&!(e&&typeof e==="object"))throw TypeError("world() takes a World or a function that creates one");if(!t||typeof t!=="object"||Array.isArray(t))throw TypeError("world() options must be an object");let{name:n="world",livenessKnown:o=!1,queueLeases:s=!1,runInRequest:i=s,waitUntil:a,queueDurable:c=!1,pollMs:A,leaseMs:u,maxDurationMs:l,reserveMs:d,alive:f,holderInfo:h,gatewayKey:g}=t;if(typeof n!=="string"||n.length===0)throw TypeError("world() name must be a non-empty string");for(let[p,I]of Object.entries({livenessKnown:o,queueLeases:s,runInRequest:i,queueDurable:c}))if(typeof I!=="boolean")throw TypeError(`${n}() ${p} must be a boolean`);if(A!==void 0&&!(Number.isSafeInteger(A)&&A>0))throw TypeError(`${n}() pollMs must be a positive integer`);if(u!==void 0&&!(Number.isSafeInteger(u)&&u>=1000))throw TypeError(`${n}() leaseMs must be an integer of at least 1000`);for(let[p,I]of Object.entries({maxDurationMs:l,reserveMs:d}))if(I!==void 0&&!(Number.isSafeInteger(I)&&I>=0))throw TypeError(`${n}() ${p} must be a non-negative integer`);for(let[p,I]of Object.entries({alive:f,holderInfo:h,gatewayKey:g,waitUntil:a}))if(I!==void 0&&typeof I!=="function")throw TypeError(`${n}() ${p} must be a function`);if(o&&!f)throw TypeError(`${n}() livenessKnown needs alive()`);if(i&&!s)throw TypeError(`${n}() runInRequest needs queueLeases`);return{[DJe]:!0,name:n,world:r?e:()=>e,owned:r,livenessKnown:o,queueLeases:s,runInRequest:i,queueDurable:c,...A===void 0?{}:{pollMs:A},...u===void 0?{}:{leaseMs:u},...l===void 0?{}:{maxDurationMs:l},...d===void 0?{}:{reserveMs:d},...f===void 0?{}:{alive:f},...h===void 0?{}:{holderInfo:h},...g===void 0?{}:{gatewayKey:g},...a===void 0?{}:{waitUntil:a}}}function Cit({reserveMs:e,leaseMs:t}={}){return cee(()=>aee(),{name:"vercel",gatewayKey:()=>Aee.getVercelOidcToken(),livenessKnown:!1,queueLeases:t===void 0,waitUntil:(r)=>globalThis[Symbol.for("@vercel/request-context")]?.get?.()?.waitUntil?.(r),queueDurable:!0,pollMs:1000,reserveMs:e,leaseMs:t})}export{Cit as vercel};
|
|
268
|
+
Cause: ${r}`)}}buildUrl(t,...r){let n=encodeURIComponent(t),o=r.map((a)=>encodeURIComponent(a)),s=o.length>0?"/"+o.join("/"):"",i=zb(this.baseUrl.pathname);return`${this.baseUrl.origin}${i}${dYe}/${n}${s}`}async fetch(t,r){let n=r.method||"GET";if($X()){let i={method:n,url:t,headers:r.headers},a=r.body;if(a!==void 0&&a!==null)if(a instanceof ArrayBuffer)i.bodySize=a.byteLength;else if(a instanceof Uint8Array)i.bodySize=a.byteLength;else if(typeof a==="string")i.bodySize=a.length;else i.bodyType=typeof a;console.debug("[VQS Debug] Request:",JSON.stringify(i,null,2))}r.headers.set("User-Agent","@vercel/queue/0.8.0"),r.headers.set("Vqs-Client-Ts",new Date().toISOString());let o=this.dispatcher?{...r,dispatcher:this.dispatcher}:r,s=await fetch(t,o);if($X()){let i={method:n,url:t,status:s.status,statusText:s.statusText,headers:s.headers};console.debug("[VQS Debug] Response:",JSON.stringify(i,null,2))}return s}async sendMessage(t){let r=this.transport,{queueName:n,payload:o,telemetry:s}=t,i=this.buildMessageHeaders(t,r.contentType);i.set("Authorization",`Bearer ${await this.getToken()}`);let a=this.getSendDeploymentId();if(a)i.set("Vqs-Deployment-Id",a);let c=r.serialize(o),A=Buffer.isBuffer(c)?new Uint8Array(c):c,u=wm(this.telemetry,s);return HX(n,async(l)=>{await PX(i,u);let d=await this.fetch(this.buildUrl(n),{method:"POST",body:A,headers:i,...A instanceof ReadableStream&&{duplex:"half"}});if(!d.ok){let h=await KA(d);if(d.status===502&&d.headers.get("Vqs-Error-Code")==="consumer_discovery_failed")throw new rD(h.message||"Consumer discovery failed",a);XA(h,"send message")}if(d.status===202)return await d.text(),{messageId:null};let f=await d.json();if(l&&f.messageId)l.setMessageId(f.messageId);return f},u)}async sendBatch(t){let r=this.transport,{queueName:n,messages:o,telemetry:s}=t;if(o.length<1||o.length>100)throw RangeError("Batch size must be between 1 and 100 messages");let i=new Headers(this.customHeaders);i.set("Authorization",`Bearer ${await this.getToken()}`);let a=this.getSendDeploymentId();if(a)i.set("Vqs-Deployment-Id",a);let c=tYe(o.map((u)=>({headers:this.buildMessageHeaders(u,r.contentType),body:()=>r.serialize(u.payload)})));i.set("Content-Type",c.contentType);let A=wm(this.telemetry,s);return HX(n,async()=>{try{await PX(i,A);let u=await this.fetch(this.buildUrl(n,"batch"),{method:"POST",body:c.body,headers:i,duplex:"half"});if(!u.ok){let d=await KA(u);XA(d,"send message batch")}let{results:l}=await u.json();if(l.length!==o.length)throw new XX(`Invalid batch response: expected ${o.length} results, received ${l.length}`);return l}catch(u){throw await c.cancel(u),u}},A)}buildMessageHeaders(t,r){let n=new Headers(this.customHeaders);n.delete("Authorization");for(let[o,s]of Object.entries(t.headers??{})){let i=o.toLowerCase();if(s!==void 0&&i!=="authorization"&&i!=="content-type"&&!i.startsWith("vqs-"))n.set(o,s)}if(n.set("Content-Type",r),t.idempotencyKey)n.set("Vqs-Idempotency-Key",t.idempotencyKey);if(t.retentionSeconds!==void 0)n.set("Vqs-Retention-Seconds",t.retentionSeconds.toString());if(t.delaySeconds!==void 0)n.set("Vqs-Delay-Seconds",t.delaySeconds.toString());return n}async*receiveMessages(t){let r=this.transport,{queueName:n,consumerGroup:o,visibilityTimeoutSeconds:s,limit:i,cursorFallback:a}=t;if(i!==void 0&&(i<1||i>10))throw new BWe(i);let c=new Headers({Authorization:`Bearer ${await this.getToken()}`,Accept:"multipart/mixed",...this.customHeaders});if(s!==void 0)c.set("Vqs-Visibility-Timeout-Seconds",s.toString());if(i!==void 0)c.set("Vqs-Max-Messages",i.toString());if(a!==void 0)c.set("Vqs-Cursor-Fallback",a);let A=this.getConsumeDeploymentId();if(A)c.set("Vqs-Deployment-Id",A);let u=await this.fetch(this.buildUrl(n,"consumer",o),{method:"POST",headers:c});if(u.status===204){await u.text();return}if(!u.ok)XA(await KA(u),"receive messages");for await(let l of Ub(u))try{let d=GX(l.headers);if(!d){console.warn("Missing required queue headers in multipart part"),await Jb(l.payload);continue}let f=await r.deserialize(l.payload);yield{...d,payload:f}}catch(d){console.warn("Failed to process multipart message:",d),await Jb(l.payload)}}async receiveMessageById(t){let r=this.transport,{queueName:n,consumerGroup:o,messageId:s,visibilityTimeoutSeconds:i}=t,a=new Headers({Authorization:`Bearer ${await this.getToken()}`,Accept:"multipart/mixed",...this.customHeaders});if(i!==void 0)a.set("Vqs-Visibility-Timeout-Seconds",i.toString());let c=this.getConsumeDeploymentId();if(c)a.set("Vqs-Deployment-Id",c);let A=await this.fetch(this.buildUrl(n,"consumer",o,"id",s),{method:"POST",headers:a});if(!A.ok){let u=await KA(A);if(A.status===404)throw new eu(s);if(A.status===409){if(u.originalMessageId)throw new tu(s,`This message was a duplicate - use originalMessageId: ${u.originalMessageId}`);throw new yWe(s,f6(A.headers.get("Retry-After")))}if(A.status===410)throw new e6(s);XA(u,"receive message by ID")}for await(let u of Ub(A)){let l=GX(u.headers);if(!l)throw await Jb(u.payload),new IWe(s,"Missing required queue headers in response");let d=await r.deserialize(u.payload);return{message:{...l,payload:d}}}throw new eu(s)}async acknowledgeMessage(t){let{messageId:r,queueName:n,consumerGroup:o,receiptHandle:s}=t,i=new Headers({Authorization:`Bearer ${await this.getToken()}`,...this.customHeaders}),a=this.getConsumeDeploymentId();if(a)i.set("Vqs-Deployment-Id",a);let c=await this.fetch(this.buildUrl(n,"consumer",o,"lease",s),{method:"DELETE",headers:i});if(!c.ok){let A=await KA(c);if(c.status===404)throw new eu(r);if(c.status===409)throw new tu(r,A.message||"Invalid receipt handle, message not in correct state, or already processed");XA(A,"acknowledge message","Missing or invalid receipt handle")}return await c.text(),{acknowledged:!0}}async changeVisibility(t){let{messageId:r,queueName:n,consumerGroup:o,receiptHandle:s,visibilityTimeoutSeconds:i}=t,a=new Headers({Authorization:`Bearer ${await this.getToken()}`,"Content-Type":"application/json",...this.customHeaders}),c=this.getConsumeDeploymentId();if(c)a.set("Vqs-Deployment-Id",c);let A=await this.fetch(this.buildUrl(n,"consumer",o,"lease",s),{method:"PATCH",headers:a,body:JSON.stringify({visibilityTimeoutSeconds:i})});if(!A.ok){let u=await KA(A);if(A.status===404)throw new eu(r);if(A.status===409)throw new tu(r,u.message||"Invalid receipt handle, message not in correct state, or already processed");XA(u,"change visibility","Missing receipt handle or invalid visibility timeout")}return await A.text(),{success:!0}}},tD=new WeakMap,h6=Symbol.for("@vercel/queue.apiClient");function hYe(e,t){tD.set(e,t),Object.defineProperty(e,h6,{value:t,writable:!1,enumerable:!1,configurable:!1})}function rs(e){let t=tD.get(e);if(t)return t;let r=e[h6];if(typeof r==="object"&&r!==null){let n=r;return tD.set(e,n),n}throw Error("QueueClient not initialized. This may happen when multiple bundled copies of @vercel/queue are loaded in local dev.")}function gYe(e){if("request"in e)return e.request;return e}function jX(e){if(e instanceof e6||e instanceof Error&&e.name==="MessageAlreadyProcessedError")return"already_processed";if(e instanceof tu||e instanceof Error&&e.name==="MessageNotAvailableError")return"not_available";return null}function WX(e,t){return console.debug(`Queue callback skipped (${e}) for message ${t??"<unknown>"}: the message was already handled or is no longer available to this consumer.`),{status:"skipped",reason:e,...t!==void 0?{messageId:t}:{}}}function g6(e){return rs(e)}var YX="iad1";function pYe(e){if(e)return e;let t=process.env.VERCEL_REGION;if(t)return t;if(!Jr())console.warn(`[QueueClient] Region not detected — defaulting to "${YX}". On Vercel this is set automatically via VERCEL_REGION. To silence this warning, pass region explicitly: new QueueClient({ region: "iad1" })`);return YX}var cD=class{constructor(e={}){let t=pYe(e.region);hYe(this,new fYe({...e,region:t}))}send=async(e,t,r)=>{let n=rs(this),o=await n.sendMessage({queueName:e,payload:t,idempotencyKey:r?.idempotencyKey,retentionSeconds:r?.retentionSeconds,delaySeconds:r?.delaySeconds,headers:r?.headers,telemetry:r?.telemetry});if(o.messageId&&Jr()&&!n.usesLocalBroker())Bm(e,o.messageId,n.getRegion(),r?.delaySeconds,r?.retentionSeconds);return{messageId:o.messageId}};experimental_sendBatch=async(e,t,r)=>{let n=rs(this),o=await n.sendBatch({queueName:e,messages:t,telemetry:r?.telemetry});if(!Jr()||n.usesLocalBroker())return o;let s=n.getRegion();for(let[i,a]of o.entries()){if(a.status!=="sent")continue;let c=t[i];mWe(c),Bm(e,a.messageId,s,c.delaySeconds,c.retentionSeconds)}return o};handleCallback=(e,t)=>{if(Jr()&&!rs(this).usesLocalBroker())Em(e,this,t);let r=wm(rs(this).getTelemetry?.());return async(n)=>{let o=gYe(n);if(Jr()&&!rs(this).usesLocalBroker()&&o.headers.get("x-vercel-queue-prime")==="1"){let i=o.headers.get("x-vercel-queue-prime-file");if(i)Em(e,this,t,i);return Response.json({status:"primed"})}let s;try{s=await kWe(o);let i=s;return await VX(o.headers,()=>Zb(e,i,{client:this,visibilityTimeoutSeconds:t?.visibilityTimeoutSeconds,retry:t?.retry}),r),Response.json({status:"success"})}catch(i){let a=jX(i);if(a)return Response.json(WX(a,s?.messageId));if(console.error("Queue callback error:",i),i instanceof Error&&(i.message.includes("Invalid content type")||i.message.includes("Invalid CloudEvent")||i.message.includes("Missing required CloudEvent")||i.message.includes("Failed to parse CloudEvent")||i.message.includes("Binary mode callback")))return Response.json({error:i.message},{status:400});return Response.json({error:"Failed to process queue message"},{status:500})}}};handleNodeCallback=(e,t)=>{if(Jr()&&!rs(this).usesLocalBroker())Em(e,this,t);let r=wm(rs(this).getTelemetry?.());return async(n,o)=>{if(n.method!=="POST"){o.status(200).end();return}let s=n.headers["x-vercel-queue-prime"];if(Jr()&&!rs(this).usesLocalBroker()&&s==="1"){let a=n.headers["x-vercel-queue-prime-file"],c=Array.isArray(a)?a[0]:a;if(c)Em(e,this,t,c);o.status(200).json({status:"primed"});return}let i;try{i=n6(n.body,n.headers);let a=i;await VX(n.headers,()=>Zb(e,a,{client:this,visibilityTimeoutSeconds:t?.visibilityTimeoutSeconds,retry:t?.retry}),r),o.status(200).json({status:"success"})}catch(a){let c=jX(a);if(c){o.status(200).json(WX(c,i?.messageId));return}if(console.error("Queue callback error:",a),a instanceof Error&&(a.message.includes("Invalid content type")||a.message.includes("Invalid CloudEvent")||a.message.includes("Missing required CloudEvent")||a.message.includes("Failed to parse CloudEvent")||a.message.includes("Binary mode callback"))){o.status(400).json({error:a.message});return}o.status(500).json({error:"Failed to process queue message"})}}}};No();Er();kl();XB();function yf(e){return`${e} requires VERCEL_DEPLOYMENT_ID, which Vercel sets in every deployment, so this process is not running inside one. The Vercel world is only selected automatically when `+"that variable is set, so it was requested explicitly here — most often by WORKFLOW_TARGET_WORLD=vercel "+"in a process that is not a deployment, such as a production server started locally or in CI. To use the local filesystem world instead, set WORKFLOW_TARGET_WORLD=local or unset it."}Eo();Nn();Dr();var x6=100;function OYe(){let e=process.env.VERCEL_QUEUE_TRACE_PROPAGATION?.toLowerCase();return e==="off"||e==="0"||e==="false"}function UYe(e){if(e===void 0)return{messageId:null,error:"Queue batch returned no result for this message",retryable:!0};if(e.status==="failed")return{messageId:null,error:e.error,retryable:e.retryable};return{messageId:e.messageId?cl.parse(e.messageId):null}}class U6{contentType="application/cbor";serialize(e){return Buffer.from(Ts(e))}async deserialize(e){let t=[],r=e.getReader();while(!0){let{done:n,value:o}=await r.read();if(n)break;if(o)t.push(o)}return Ir(Buffer.concat(t))}}class M6{contentType="application/json";serialize(e){return Buffer.from(JSON.stringify(e))}async deserialize(e){let t=[],r=e.getReader();while(!0){let{done:n,value:o}=await r.read();if(n)break;if(o)t.push(o)}return JSON.parse(Buffer.concat(t).toString())}}class F6{contentType="application/cbor";serialize(e){return Buffer.from(Ts(e))}async deserialize(e){let t=[],r=e.getReader();while(!0){let{done:o,value:s}=await r.read();if(o)break;if(s)t.push(s)}let n=Buffer.concat(t);try{return Ir(n)}catch{return JSON.parse(n.toString())}}}var Dm=new NYe,MYe="x-vercel-internal-workflow-step-ids",FYe=10;function L6(e){let t=Dm.getStore();if(t?.collectStepIds&&t.stepIds.size<FYe)t.stepIds.add(e)}function LYe(e,t){if(t.stepIds.size===0)return e;let r=new Headers(e.headers);return r.set(MYe,JSON.stringify(Array.from(t.stepIds))),new Response(e.body,{headers:r,status:e.status,statusText:e.statusText})}var PYe=j(H({payload:nw,queueName:ew,deploymentId:Q().optional()})),HYe=Number(process.env.VERCEL_QUEUE_MAX_DELAY_SECONDS||82800),gD=1,P6=900,VYe=0.25;function $Ye(e){if(typeof e!=="object"||e===null)return;let t=e.retryAfter;if(typeof t!=="number"||!Number.isFinite(t)||t<=0)return;return Math.min(Math.ceil(t),P6)}function GYe(e,t){let r=Math.min(Math.max(gD,2**(t-1)),P6),n=Math.floor(Math.random()*(Math.ceil(r*VYe)+1)),o=Math.max(gD,r-n);return Math.max(o,$Ye(e)??gD)}var jYe="iad1";function H6(e){if("runId"in e&&typeof e.runId==="string")return e.runId;return}function WYe(e){try{return tw(e).id}catch{return}}var YYe=(e,t,r)=>{let n;return{open(){if(!e||!Qm(t))return;n=Promise.resolve().then(() => (bm(),{})).then(({})=>hD(e,r,{workflowName:t})).catch(()=>{return})},async close(){(await n)?.()}}},N6="wrun_";function qYe(e){if(!e)return;let t=e.startsWith(N6)?e.slice(N6.length):e;try{let r=HA(t);if(!r.tagged)return;if(r.regionId===Fn.unknown)return;return r.region??void 0}catch{return}}function JYe(e,t){if(j0(t?.region))return t.region;let r=qYe(H6(e));if(r)return r;let n=process.env.VERCEL_REGION;if(j0(n))return n;return jYe}function zYe(e){let t={};if("runId"in e&&typeof e.runId==="string")t["x-vercel-workflow-run-id"]=e.runId;if("stepId"in e&&typeof e.stepId==="string")t["x-vercel-workflow-step-id"]=e.stepId;return Object.keys(t).length>0?t:void 0}var ZYe=/^__([a-z][a-z0-9]*_)?wkf_workflow_/,O6=Yt("@workflow/world-vercel//queueLogLatches",1,()=>({loggedSequentialReplays:!1}));function KYe(){return process.env.WORKFLOW_SEQUENTIAL_REPLAYS==="1"}function XYe(e,t){if(!KYe()||!ZYe.test(e))return e;if(!O6.loggedSequentialReplays)O6.loggedSequentialReplays=!0,console.warn("[workflow] WORKFLOW_SEQUENTIAL_REPLAYS=1: routing flow messages to per-run queue topics");if("__healthCheck"in t&&typeof t.correlationId==="string")return`${e}_${t.correlationId}`;if("runId"in t&&typeof t.runId==="string"){if("stepId"in t&&typeof t.stepId==="string")return`${e}_${t.runId}_${t.stepId}`;return`${e}_${t.runId}`}return e}function pD(e){let{baseUrl:t,usingProxy:r}=Un(e),n=L0(e,{usingProxy:r}),o=new U6,s=new M6,i=new F6,a={dispatcher:g8(e),transport:i,...r&&{resolveBaseUrl:()=>new URL(`${t}/queues-proxy`),token:e?.token},headers:Object.fromEntries(n.entries())},c=(g,p,I)=>{let m=I?.deploymentId??process.env.VERCEL_DEPLOYMENT_ID;if(!m)throw Error(`${yf("Enqueuing a workflow message")} Callers outside a deployment can instead pass an explicit deploymentId in options.`);let C=(I?.specVersion??Sg)>=lw,b=JYe(p,I),D=XYe(g,p).replace(/[^A-Za-z0-9-_]/g,"-");return{deploymentId:m,useCbor:C,region:b,topic:D,wrapper:{payload:p,queueName:g,deploymentId:I?.deploymentId},sendOptions:{idempotencyKey:I?.idempotencyKey,delaySeconds:I?.delaySeconds,headers:{...zYe(p),...I?.headers}}}},A=(g)=>new cD({...a,...r&&{headers:{...a.headers,"x-vercel-queue-region":g.region}},region:g.region,deploymentId:g.deploymentId,transport:g.useCbor?o:s}),u=async(g,p,I)=>{let m=c(g,p,I),C=A(m),{messageId:b}=await C.send(m.topic,m.wrapper,m.sendOptions);return{messageId:b?cl.parse(b):null}};return{queue:u,queueBatch:async(g,p)=>{let I=Array(p.length);if(p.length===0)return I;let m=OYe()?{}:await b0(),C=new Map;for(let[b,D]of p.entries()){let v=c(g,D.message,D.opts),P=`${v.region}\x00${v.deploymentId}\x00${v.useCbor}\x00${v.topic}`,T=C.get(P)??{route:v,entries:[]};T.entries.push({index:b,topic:v.topic,message:{payload:v.wrapper,...v.sendOptions,headers:{...v.sendOptions.headers,...m}}}),C.set(P,T)}return await Promise.all([...C.values()].map(async({route:b,entries:D})=>{let v=A(b);for(let P=0;P<D.length;P+=x6){let T=D.slice(P,P+x6),V=await v.experimental_sendBatch(T[0].topic,T.map((L)=>L.message));for(let[L,ee]of T.entries())I[ee.index]=UYe(V[L])}})),I},createQueueHandler:(g,p)=>{let m=new cD(a).handleCallback(async(C,b)=>{if(!C||!b)return;let D=Dm.getStore(),v=D?.requestId,{payload:P,queueName:T,deploymentId:V}=PYe.parse(C),L=YYe(H6(P),WYe(T),e),ee=!(("stepId"in P)&&typeof P.stepId==="string");L.open();try{let K=()=>p(P,{queueName:T,messageId:cl.parse(b.messageId),attempt:b.deliveryCount,requestId:v}),w=await(D?Dm.run({...D,collectStepIds:ee},K):K());if(!(("invoke"in P)&&P.invoke===!0)&&typeof w==="object"&&w!==null&&"timeoutSeconds"in w&&typeof w.timeoutSeconds==="number"){let F=w.timeoutSeconds>0?Math.min(w.timeoutSeconds,HYe):void 0;await u(T,P,{deploymentId:V,delaySeconds:F})}}finally{await L.close()}},{retry:(C,{messageId:b,deliveryCount:D})=>{let v=GYe(C,D);return console.error(`[workflow] Queue handler failed for message "${b}" on delivery attempt ${D}; retrying in ${v}s:`,C),{afterSeconds:v}}});return async(C)=>{let v={collectStepIds:!1,requestId:C.headers.get("x-vercel-id")?.trim()||void 0,stepIds:new Set},P=await Dm.run(v,()=>m(C));return LYe(P,v)}},getDeploymentId:async()=>{let g=process.env.VERCEL_DEPLOYMENT_ID;if(!g)throw Error(yf("Starting a workflow run"));return g},isDeploymentUnavailableError:(g)=>g instanceof rD}}at();var V6=Ke(Pc(),1);Eo();On();var eqe=j(H({id:Q()}));async function tqe(e){if(e?.token)return e.token;if(process.env.VERCEL==="1"){let t=await V6.getVercelOidcToken().catch(()=>null);if(t)return t}return VE(e)}function $6(e){return async function(){let r=process.env.VERCEL_DEPLOYMENT_ID;if(!r)throw Error(yf("Resolving the latest deployment for deploymentId: 'latest'"));let n=await tqe(e);if(!n)throw Error("Cannot resolve latest deployment: no OIDC token or VERCEL_TOKEN available");let o=e?.projectConfig?.teamId,s=o?`?${new URLSearchParams({teamId:o})}`:"",i=`https://api.vercel.com/v1/workflow/resolve-latest-deployment/${encodeURIComponent(r)}${s}`,c=await(await Kt({method:"GET",url:i,headers:new Headers({Authorization:`Bearer ${n}`}),dispatcher:po(e),peerService:"vercel-api",timeoutMs:null,buildError:async(u)=>{let l;try{l=await u.text()}catch{l="<unable to read response body>"}let d=u.status===404?". The deployment exists but was not visible to the identity this request authenticated as, which means the request resolved to a different team. Set the World's `projectConfig.teamId` to scope it explicitly.":"";return Error(`Failed to resolve latest deployment for ${r}: HTTP ${u.status} ${u.statusText}${l?` — ${l}`:""}${d}`)}})).json(),A=eqe.safeParse(c);if(!A.success)throw Error(`Invalid response from Vercel API: expected { id: string }. Zod error: ${A.error.message}`);return A.data.id}}Ur();Er();dg();Ur();class qa extends Error{error;constructor(e){super("Replay event observer failed",{cause:e});this.error=e,this.name="ReplayEventObserverError"}}class iu extends Error{error;constructor(e){super("Event log read after a committed write failed",{cause:e});this.error=e,this.name="AfterCommitError"}}var rqe=new Set(["step_completed","step_retrying"]);function nqe(e){return rqe.has(e)}var oqe={run_created:{retryable:!0,reason:"conditional create → 409 if exists"},step_created:{retryable:!0,reason:"conditional create → 409 if exists"},wait_created:{retryable:!0,reason:"conditional create → 409 if exists"},hook_created:{retryable:!0,reason:"transactional token uniqueness → 409 if exists"},run_started:{retryable:!0,reason:"early-returns if already running, no duplicate row"},run_completed:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},run_failed:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},run_cancelled:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},step_completed:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},step_failed:{retryable:!0,reason:"terminal-state guard → 409, no duplicate row"},wait_completed:{retryable:!0,reason:"waiting-state guard → 409, no duplicate row"},hook_disposed:{retryable:!0,reason:"conditional delete (exists) → 409, no duplicate row"},attr_set:{retryable:!0,reason:"correlationId constraint reuses eventId (idempotent replay)"},step_started:{retryable:!1,reason:"unconditional attempt increment → a retry double-counts attempts"},step_retrying:{retryable:!1,reason:"no duplicate guard → a retry appends a second event row"},hook_received:{retryable:!1,reason:"no server guard → a retry duplicates the row / re-delivers payload. "+"EXCEPTION: the atomic lazy-resume shape (resumeId + digest) is deduplicated server-side by the (runId, resumeId) claim, so those writes opt in via withEventPostRetry({ idempotentHookResume })"},hook_conflict:{retryable:!1,reason:"server-originated; never POSTed by the SDK"},noop:{retryable:!1,reason:"server-originated; never POSTed by the SDK"}},sqe=2,iqe=30000,aqe=15000,cqe=900000,Aqe=1,uqe=100,lqe=50,dqe=new Set(["ECONNRESET","ECONNREFUSED","ENOTFOUND","ENETDOWN","ENETUNREACH","EHOSTDOWN","EHOSTUNREACH","EPIPE","ETIMEDOUT","UND_ERR_SOCKET","UND_ERR_REQ_RETRY","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_BODY_TIMEOUT","TimeoutError","RequestRetryError"]);function Rm(e,t=0){if(t>5||e===null||typeof e!=="object")return[];let r=[],n=e;if(typeof n.code==="string")r.push(n.code);if(typeof n.name==="string")r.push(n.name);if(n.cause)r.push(...Rm(n.cause,t+1));return r}function fqe(e){if(e instanceof qa)return!1;if(Vi.is(e)||Oo.is(e)||$i.is(e)||Gi.is(e)||Dn.is(e))return!1;if(G.is(e)||gt.is(e)){if(e.code==="PARSE_ERROR")return!0;if(e.code==="TRANSPORT")return!0;if(typeof e.status==="number")return e.status>=500&&e.status<=599;if(e.code==="STREAM_ERROR")return!Rm(e).some((t)=>["AbortError","ABORT_ERR","UND_ERR_ABORTED","ERR_HTTP2_STREAM_CANCEL"].includes(t))}return Rm(e).some((t)=>dqe.has(t))}var j6=(e,t)=>new Promise((r,n)=>{if(t?.aborted){n(t.reason);return}let o=()=>{clearTimeout(s),n(t?.reason)},s=setTimeout(()=>{t?.removeEventListener("abort",o),r()},e);t?.addEventListener("abort",o,{once:!0})}),hqe=typeof process<"u"&&typeof process.env.DEBUG==="string"&&(process.env.DEBUG.includes("workflow:")||process.env.DEBUG==="*");function ED(e,t){if(!hqe)return;let r=Object.entries(t).map(([n,o])=>`${n}=${o}`).join(" ");console.debug(`[workflow:world-vercel:event-retry] ${e} ${r}`)}function G6(e){if(G.is(e))return e.code??(e.status!=null?`status_${e.status}`:e.name);return Rm(e)[0]??(e instanceof Error?e.name:"unknown")}async function gqe(){try{let t=(await dm())?.getTime();return t!==void 0&&Number.isFinite(t)?t:void 0}catch{return}}function wf(e,t){let r=0,n;return async(o,s)=>{let i=Math.max(1,typeof o.retryAfter==="number"?o.retryAfter:Aqe)*1000;if(n===void 0){let c=await gqe();n={budgetMs:t==="invocation"&&c!==void 0?cqe:iqe,deadlineMs:c}}let a=n.deadlineMs!==void 0&&Date.now()+i>n.deadlineMs-aqe;if(r+i>n.budgetMs||a)throw ED("throttle retry budget exhausted; surfacing to the queue",{target:e,budget:t,waitedMs:r,retryAfter:o.retryAfter,outlastsInvocation:a}),o;r+=i,console.warn(`[workflow] Throttled (429) ${e}; retrying in-process in ${i/1000}s`),await j6(i,s)}}function pqe(e,t){if(t?.batchIdempotent!==void 0)return"bounded";return t?.afterStepBody===!0||nqe(e)?"invocation":"bounded"}function Eqe(e,t){if(t?.inBand===!0)return!1;if(t?.batchIdempotent!==void 0)return t.batchIdempotent;return e==="hook_received"&&t?.idempotentHookResume===!0||(oqe[e]?.retryable??!1)}async function mD(e,t,r){let n=Eqe(t,r),o=wf(`writing ${t} event`,pqe(t,r));for(let s=0;;)try{return await e()}catch(i){if(i instanceof iu)throw i;if(Dn.is(i)){await o(i);continue}if(!n||!fqe(i))throw i;if(s>=sqe)throw ED("exhausted in-process retries; surfacing for queue redelivery",{eventType:t,attempts:s+1,error:G6(i)}),i;let a=uqe*2**s+Math.floor(Math.random()*lqe);s++,ED("retrying event POST after transient failure",{eventType:t,attempt:s,backoffMs:a,error:G6(i)}),await j6(a)}}Ur();No();Er();kl();at();import SD from"node:assert/strict";ou();Eo();On();Ur();var ID=4,mqe="devl",Iqe="encr",W6="gzip",yD="zstd",yqe=new TextDecoder,Cqe=new Set([mqe,Iqe,W6,yD]);function Bqe(){try{return globalThis.process?.getBuiltinModule?.("node:zlib")}catch{return}}function Y6(e){if(!(e instanceof Uint8Array)||e.byteLength<ID)return null;return yqe.decode(e.subarray(0,ID))}function q6(e){let t=Y6(e);return t!==null&&Cqe.has(t)}function wqe(e,t){let r=Bqe(),n=e===yD?r?.zstdDecompressSync:r?.gunzipSync;if(!n)throw new G(`Received ${e}-compressed workflow data, but this Node.js runtime does not support ${e} decompression. Use a compatible Node.js runtime or request unresolved data.`);return new Uint8Array(n(t))}function fi(e){let t=Y6(e);if(t!==yD&&t!==W6)return e;return wqe(t,e.subarray(ID))}function Qqe(e){try{return fi(e)}catch(t){if(G.is(t))throw t;throw new G("Stored dynamic workflow code could not be decompressed.",{code:"WORLD_CONTRACT_ERROR",cause:t})}}function CD(e){return{...e,input:fi(e.input),output:fi(e.output),error:fi(e.error),...e.dynamicWorkflowCode!==void 0?{dynamicWorkflowCode:Qqe(e.dynamicWorkflowCode)}:{}}}function BD(e){return{...e,input:fi(e.input),output:fi(e.output),error:fi(e.error)}}function J6(e){return{...e,metadata:fi(e.metadata)}}Er();at();Dr();var au=j(qB.omit({error:!0}).extend({error:vo([Se,Wt()]).optional(),errorRef:Wt().optional()})),z6=j(au.omit({input:!0,output:!0}).extend({inputRef:Wt().optional(),outputRef:Wt().optional(),input:_c(Uint8Array).optional(),output:_c(Uint8Array).optional()}));function Qf(e){let{error:t,errorRef:r,...n}=e,o={...n},s=t??r;if(s!==void 0&&s!==null)o.error=s;return o}function Z6(e,t){if(t==="none"){let{inputRef:r,outputRef:n,...o}=e;return{...BD(Qf(o)),input:void 0,output:void 0}}return BD(Qf(e))}async function K6(e,t){let{runId:r,pagination:n,resolveData:o=yn}=e,s=new URLSearchParams;if(n?.cursor)s.set("cursor",n.cursor);if(n?.limit)s.set("limit",n.limit.toString());if(n?.sortOrder)s.set("sortOrder",n.sortOrder);let i=o==="none"?"lazy":"resolve";s.set("remoteRefBehavior",i);let a=s.toString(),c=`/v2/runs/${encodeURIComponent(r)}/steps${a?`?${a}`:""}`,A=await Te({endpoint:c,options:{method:"GET"},config:t,schema:or(i==="lazy"?z6:au)});return{...A,data:A.data.map((u)=>Z6(u,o))}}async function X6(e,t,r,n){let o=r?.resolveData??yn,s=o==="none"?"lazy":"resolve",i=new URLSearchParams;i.set("remoteRefBehavior",s);let a=i.toString(),c=`/v2/runs/${encodeURIComponent(e)}/steps/${encodeURIComponent(t)}${a?`?${a}`:""}`,A=await Te({endpoint:c,options:{method:"GET"},config:n,schema:s==="lazy"?z6:au});return Z6(A,o)}Nn();Dr();async function km(e,t,r,n,o){let s=TE(r),i=await Kt({method:t.method,url:e,headers:t.headers,body:t.body,dispatcher:s,attributes:o,onTransportOutcome:(A)=>NA(s,A),deferTransportSuccessUntilBody:!0,timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:n,buildError:async(A)=>u7(A.status,LA(A.headers),new Uint8Array(await A.arrayBuffer()),n,e)});if(!i.body)return NA(s),i;let a=i.body.getReader(),c=new ReadableStream({async pull(A){try{let u=await a.read();if(u.done)NA(s),A.close();else A.enqueue(u.value)}catch(u){NA(s,u);let l=qd(u);A.error(l?new gt(`v4 ${n}: response stream transport failure (${l})`,{cause:u,url:e}):u)}},cancel(A){return NA(s),a.cancel(A)}});return new Response(c,{status:i.status,statusText:i.statusText,headers:i.headers})}var n7="x-wf-event-id",o7="x-wf-max-events";function s7(e,t,r){return`${e}/v4/runs/${encodeURIComponent(t)}/events/${encodeURIComponent(r)}`}var e7=Symbol("omitted event payload"),Ja=j(t2((e)=>{if(typeof e!=="object"||e===null||Array.isArray(e))return e;let t=e,r=typeof t.eventType==="string"?Bs(t.eventType):void 0,n=t.eventData;if(!r||typeof n!=="object"||n===null||Array.isArray(n)||Object.hasOwn(n,r))return e;return{...t,eventData:{...n,[r]:e7}}},$B).transform((e)=>{let t=Bs(e.eventType);if(!t||!("eventData"in e))return e;let r=e.eventData;if(typeof r!=="object"||r===null||Array.isArray(r)||r[t]!==e7)return e;let n={...r};return delete n[t],{...e,eventData:n}})),Tm=H({event:Ja,run:ol.optional(),step:au.transform(Qf).optional(),hook:ws.optional(),wait:zB.optional(),stepCreated:ue(!0).optional(),maxEvents:z().int().positive().optional(),allocated:z().int().nonnegative().optional()}),vm=vo([H({events:_n(Ja),cursor:Q().nullable(),hasMore:jt()}),H({events:Wn().optional(),cursor:Wn().optional(),hasMore:Wn().optional()})]),lr=Tm.and(vm),i7={run_created:Tm.extend({run:ol}).and(vm),run_started:Tm.extend({run:ol.and(H({startedAt:Ie.date()}))}).and(vm),step_started:Tm.extend({step:au.extend({startedAt:Ie.date()}).transform((e)=>({...Qf(e),startedAt:e.startedAt}))}).and(vm),run_completed:lr,run_failed:lr,run_cancelled:lr,attr_set:lr,step_created:lr,step_completed:lr,step_failed:lr,step_retrying:lr,hook_created:lr,hook_received:lr,hook_disposed:lr,hook_conflict:lr,wait_created:lr,wait_completed:lr,noop:lr},a7=j(Ie.number().int().positive()),c7=j(H({seq:z().int().nonnegative(),seqInBand:z().int().nonnegative()}).refine(({seq:e,seqInBand:t})=>t<=e)),_qe="x-wf-snapshot-seq",Sqe="x-wf-snapshot-seq-in-band",t7=/^\d+$/;function bqe(e){let t=e.get(_qe),r=e.get(Sqe);if(t===null||r===null||!t7.test(t)||!t7.test(r))return;let n=c7.safeParse({seq:Number(t),seqInBand:Number(r)});return n.success?n.data:void 0}function Dqe(e){if(e===void 0)return;let t=c7.safeParse(e);return t.success?t.data:void 0}var Rqe=j(H({_end:ue(1),next:Q().optional(),hasMore:jt(),snapshot:Ui().optional()})),Tqe=j(H({_error:ue(1),code:Q(),message:Q().optional()})),vqe="payload-missing",kqe=new Set(["run_failed","step_failed","step_retrying"]);function xqe(e){if(q6(e))return e;try{let t=sw.safeParse(Ir(e.slice()));return t.success?t.data:e}catch{return e}}function A7({meta:e,body:t}){let r=pr.parse(e.eventType);if(t.byteLength===0)return Ja.parse(e);let n=Bs(r);return SD(n,`Event type ${r} cannot carry a payload body`),SD(e.eventData&&typeof e.eventData==="object"),Ja.parse({...e,eventData:{...e.eventData,[n]:kqe.has(r)?xqe(t):t}})}function RD(e){let t={eventType:e.eventType,specVersion:e.specVersion};if(e.executorSpecVersion!==void 0)t.executorSpecVersion=e.executorSpecVersion;if(e.correlationId!==void 0)t.correlationId=e.correlationId;if(e.vercelId!==void 0)t.vercelId=e.vercelId;if(e.computeInstanceId!==void 0)t.computeInstanceId=e.computeInstanceId;if(e.occurredAt!==void 0)t.occurredAt=e.occurredAt;if(e.remoteRefBehavior!==void 0)t.remoteRefBehavior=e.remoteRefBehavior;if(e.eventsRemoteRefBehavior!==void 0)t.eventsRemoteRefBehavior=e.eventsRemoteRefBehavior;if(e.deploymentId!==void 0)t.deploymentId=e.deploymentId;if(e.workflowName!==void 0)t.workflowName=e.workflowName;if(e.stepName!==void 0)t.stepName=e.stepName;if(e.attempt!==void 0)t.attempt=e.attempt;if(e.resumeAt!==void 0)t.resumeAt=e.resumeAt;if(e.retryAfter!==void 0)t.retryAfter=e.retryAfter;if(e.hookToken!==void 0)t.hookToken=e.hookToken;if(e.hookTokenRetentionUntil!==void 0)t.hookTokenRetentionUntil=e.hookTokenRetentionUntil;if(e.hookIsWebhook!==void 0)t.hookIsWebhook=e.hookIsWebhook;if(e.hookIsSystem!==void 0)t.hookIsSystem=e.hookIsSystem;if(e.hookForce!==void 0)t.hookForce=e.hookForce;if(e.resumeId!==void 0)t.resumeId=e.resumeId;if(e.errorCode!==void 0)t.errorCode=e.errorCode;if(e.cancelReason!==void 0)t.cancelReason=e.cancelReason;if(e.ownerMessageId!==void 0)t.ownerMessageId=e.ownerMessageId;if(e.executionContext!==void 0)t.executionContext=e.executionContext;if(e.attributes!==void 0)t.attributes=e.attributes;if(e.changes!==void 0)t.changes=e.changes;if(e.writer!==void 0)t.writer=e.writer;if(e.allowReservedAttributes!==void 0)t.allowReservedAttributes=e.allowReservedAttributes;if(e.encryptionPublicKey!==void 0)t.encryptionPublicKey=e.encryptionPublicKey;if(e.dynamicWorkflowCode!==void 0)t.dynamicWorkflowCode=e.dynamicWorkflowCode;if(e.dynamicWorkflowCodeRef!==void 0)t.dynamicWorkflowCodeRef=e.dynamicWorkflowCodeRef;if(e.ttfs!==void 0)t.ttfs=e.ttfs;if(e.stso!==void 0)t.stso=e.stso;if(e.stepCount!==void 0)t.stepCount=e.stepCount;if(e.eventCount!==void 0)t.eventCount=e.eventCount;if(e.rsfs!==void 0)t.rsfs=e.rsfs;if(e.finalSchedulingReplay!==void 0)t.finalSchedulingReplay=e.finalSchedulingReplay;if(e.optimizations!==void 0)t.optimizations=e.optimizations;if(e.sinceCursor!==void 0)t.sinceCursor=e.sinceCursor;if(e.skipPreload)t.skipPreload=!0;if(e.maxSlot!==void 0)t.maxSlot=e.maxSlot;if(e.replayDivergenceCount!==void 0)t.replayDivergenceCount=e.replayDivergenceCount;if(e.resumePayloadDigest!==void 0)t.resumePayloadDigest=e.resumePayloadDigest;if(e.viaStepDispatch!==void 0)t.viaStepDispatch=e.viaStepDispatch;if(e.inBand!==void 0)t.inBand=e.inBand;if(e.expectedSeqInBand!==void 0)t.expectedSeqInBand=e.expectedSeqInBand;return t}function TD(e){return{...e.inBand!==void 0?R8(e.inBand):{},...e.expectedSeqInBand!==void 0?T8(e.expectedSeqInBand):{}}}function u7(e,t,r,n,o){let s=`v4 ${n} failed: HTTP ${e}`,i,a,{record:c,text:A}=Oqe(r,wD(t,"content-type"));if(c){if(typeof c.message==="string")s=c.message;if(typeof c.code==="string")i=c.code;else if(typeof c.error==="string")i=c.error;if(e===412)a=i===gl?Nqe(c):Uqe(c);if(e===409&&i==="hook-force-claimed")a={claimedBy:c.claimedBy}}else if(A)s+=` ${A}`;let u=Ha(wD(t,"retry-after"));return Va(e,s,{retryAfter:u,code:i,url:o,mitigated:wD(t,"x-vercel-mitigated"),...a!==void 0?{details:a}:{}})}function Nqe(e){let t=Yd(e.seq),r=Yd(e.seqInBand);return{...t!==void 0?{seq:t}:{},...r!==void 0?{seqInBand:r}:{}}}function Oqe(e,t){if(typeof e!=="string"&&t?.includes("application/cbor")){try{let n=Ir(e.slice());if(typeof n==="object"&&n!==null)return{record:n}}catch{}return{}}let r=typeof e==="string"?e:new TextDecoder().decode(e);try{let n=JSON.parse(r);if(typeof n==="object"&&n!==null)return{record:n}}catch{}return{text:r}}function Uqe(e){if(!Array.isArray(e.events)||e.events.length===0)return;let t=[];for(let r of e.events){if(typeof r!=="object"||r===null)return;let n=r;if(typeof n.eventId!=="string")return;if(Mqe(n))return;let o=Ja.safeParse(n);if(!o.success)return;t.push(o.data)}return{events:t,...typeof e.cursor==="string"?{cursor:e.cursor}:{}}}function Mqe(e){let t=e.eventType;if(typeof t!=="string")return!1;let r=Bs(t);if(!r)return!1;let n=e.eventData;if(typeof n!=="object"||n===null)return!1;let o=n[r];if(o===void 0)return!1;return!(o instanceof Uint8Array)}async function vD(e,t,r){let{baseUrl:n,headers:o}=await Ye(r),s=new Headers(o);if(s.set("Content-Type","application/octet-stream"),t==="event-stream")s.set("Accept",di);let i=zr(RD(e),e.payload??new Uint8Array(0)),a=s7(n,e.runId,e.eventType);return km(a,{method:"POST",headers:s,body:i},r,"createEvent",{...MA("http"),...D0(e.eventType),...R0(`@workflow/world-vercel/${ho}`),...TD(e),...e.eventType==="step_started"?{...LE(e.payload===void 0?e.ownerMessageId!==void 0?"single_owned_recovery":"single_bare":"single_lazy_create_claim"),...PE(e.ownerMessageId!==void 0)}:{},...e.stso!==void 0?T0(e.stso):{},...e.optimizations!==void 0?v0(e.optimizations):{}})}var Fqe=new Set(["step_completed"]);function Lqe(e){if(!m6()||!Cf())return;if(!Fqe.has(e))return;throw Error(`world-vercel: ${e} fell back to the HTTP events transport while the WS gate was on. WORKFLOW_INTERNAL_EVENTS_TRANSPORT_STRICT is set, so this is a failure rather than a silent demotion: no channel was resolvable for this run at write time.`)}async function l7(e,t){if(E6()){let o=await Wqe(e,t);if(o)return bD(o,e.eventType);Lqe(e.eventType)}let r=await vD(e,"materialized",t);if(r.headers.get("content-type")?.startsWith(di))throw new G("v4 createEvent: unexpected event page",{code:"SCHEMA_VALIDATION"});return bD(r,e.eventType)}var r7=new Map;function Pqe(e){return i7[e].refine(({event:t})=>t.eventType===e||e==="hook_created"&&t.eventType==="hook_conflict",{path:["event","eventType"]})}function Hqe(e){let t=r7.get(e);if(t)return t;let r=j(Pqe(e));return r7.set(e,r),r}async function bD(e,t){let r;try{r=new Uint8Array(await e.arrayBuffer())}catch(i){if(gt.is(i))throw i;throw new G("v4 createEvent: failed to read response body",{code:"TRANSPORT",cause:i})}if(r.byteLength===0)throw new G("v4 createEvent: empty response body",{code:"PARSE_ERROR"});let n=Hqe(t),o;try{o=Ir(r)}catch(i){throw new G("v4 createEvent: invalid CBOR response body",{code:"PARSE_ERROR",cause:i})}let s=n.safeParse(o);if(!s.success)throw new G("v4 createEvent: invalid response body",{code:"SCHEMA_VALIDATION",cause:s.error});return s.data}async function d7(e,t,r){let n=await vD({...e,eventType:"run_started"},"event-stream",t),o=await m7(n,e,t,r);if(!o.cursor)throw new G("v4 createEvent: event stream missing cursor",{code:"SCHEMA_VALIDATION"});let s=a7.safeParse(n.headers.get(o7));if(!s.success)throw new G("v4 createEvent: invalid max-events header",{code:"SCHEMA_VALIDATION",cause:s.error});return{...o,maxEvents:s.data}}var Vqe=j(H({status:z().int(),error:Q(),message:Q()}));async function f7(e,t){SD(e.events.length>0,"v4 createEventBatch: empty batch");let{baseUrl:r,headers:n}=await Ye(t),o=new Headers(n);o.set("Content-Type","application/octet-stream");let s=e.events.map((h)=>zr(RD(h),h.payload??new Uint8Array(0))),i=0;for(let h of s)i+=h.byteLength;let a=new Uint8Array(i),c=0;for(let h of s)a.set(h,c),c+=h.byteLength;let A=`${r}/v4/runs/${encodeURIComponent(e.runId)}/events/batch`,u=await km(A,{method:"POST",headers:o,body:a},t,"createEventBatch",{...MA("http"),"workflow.batch.bytes":a.byteLength,...TD(e.events[0]),...e.events.some((h)=>h.eventType==="step_started")?{...LE(e.events.some((h)=>h.eventType==="step_created")?"batch_create_claim":"batch_bare"),...PE(e.events.some((h)=>h.ownerMessageId!==void 0))}:{}}),l=new Uint8Array(await u.arrayBuffer()),d=l.byteLength>0?Ir(l):{};if(!Array.isArray(d.results)||d.results.length!==e.events.length)throw new G(`v4 createEventBatch: response \`results\` length (${Array.isArray(d.results)?d.results.length:"non-array"}) != ${e.events.length} submitted frames`,{code:"SCHEMA_VALIDATION"});return{results:d.results.map((h,g)=>{let p=Vqe.safeParse(h);if(p.success&&p.data.status!==200)return p.data;if(h?.status!==200)throw new G(`v4 createEventBatch: result at index ${g} is neither a success (status 200) nor a well-formed failure`,{code:"SCHEMA_VALIDATION"});let I=e.events[g].eventType,m=i7[I].safeParse(h);if(!m.success)throw new G(`v4 createEventBatch: invalid result body at index ${g} (${I})`,{code:"SCHEMA_VALIDATION",cause:m.error});if(m.data.event.eventType!==I)throw new G(`v4 createEventBatch: result at index ${g} carries a ${m.data.event.eventType} event, expected ${I}`,{code:"SCHEMA_VALIDATION"});return{status:200,...m.data}})}}function $qe(e){let t={};if(typeof e.eventId==="string")t[n7]=e.eventId;if(typeof e.retryAfter==="string")t["retry-after"]=e.retryAfter;if(typeof e.mitigated==="string")t["x-vercel-mitigated"]=e.mitigated;return t}function Gqe(e,t){let{replyParts:r=1}=t;if(r>1)e?.setAttributes({...O8(r)})}function jqe(e,t){let{status:r}=e.meta;if(typeof r!=="number")throw new G(`Failed to parse response body for POST ${t}: reply frame carried no numeric status (type: ${String(e.meta.type??"absent")}). Refusing to treat an `+"unrecognized reply as success — the write may or may not have been "+"applied.",{url:t,code:"PARSE_ERROR"});return r}async function Wqe(e,t){await Promise.resolve().then(() => bm());let{runId:n}=e,o=k6(n,t);if(!o)return;let{transport:s,wsUrl:i}=o,a=`${i}#runs/${encodeURIComponent(n)}/events`,c=s7(Un(t).baseUrl,n,e.eventType);return ri({method:"POST",url:c,attributes:{...MA("ws"),...D0(e.eventType),...R0(`@workflow/world-vercel/${ho}`),...TD(e),...e.stso!==void 0?T0(e.stso):{},...e.optimizations!==void 0?v0(e.optimizations):{},...e.eventType==="step_started"?{...LE(e.payload===void 0?e.ownerMessageId!==void 0?"single_owned_recovery":"single_bare":"single_lazy_create_claim"),...PE(e.ownerMessageId!==void 0)}:{},...NE("websocket"),...k8(i)}},async(A)=>{let u=Date.now(),l;try{l=await s.request((p)=>(A?.setAttributes({...x8(p)}),zr({reqId:p,type:"event",event:RD(e)},e.payload??new Uint8Array(0))),{onMessages:(p)=>{if(p>1)A?.setAttributes({...N8(p)})}})}catch(p){let I=new G(`POST ${a} transport failure: ${p instanceof Error?p.message:String(p)}`,{url:i,code:"TRANSPORT",cause:p});throw A?.setAttributes({...br("TRANSPORT")}),A?.recordException?.(I),I}let d=Date.now()-u;Gqe(A,l);let f=jqe(l,a),h=$qe(l.meta),g={get:(p)=>h[p.toLowerCase()]??null};if(Jd("POST","createEvent",{status:f,headers:g},d),M0(A,f),f<200||f>=300){let p=u7(f,h,new TextDecoder().decode(l.body),"createEvent",a);throw O0(A,p),A?.recordException?.(p),p}return{headers:g,arrayBuffer:async()=>l.body.slice().buffer}})}async function h7(e,t,r){let n=await vD({...e,eventType:"hook_received"},"event-stream",t);if(!n.headers.get("content-type")?.startsWith(di))return{kind:"materialized",result:await bD(n,"hook_received")};let s=await m7(n,e,t,r),i=a7.safeParse(n.headers.get(o7));return{kind:"stream",...s,canonicalEventId:n.headers.get(n7)??void 0,maxEvents:i.success?i.data:void 0}}function wD(e,t){let r=e[t];if(typeof r==="string")return r;if(Array.isArray(r)&&r.length>0)return r[0];return}async function g7(e,t,r,n){let{baseUrl:o,headers:s}=await Ye(n),i=`${o}/v4/runs/${encodeURIComponent(e)}/events/${encodeURIComponent(t)}?remoteRefBehavior=${r}`,a=await km(i,{method:"GET",headers:s},n,"getEvent"),c=a.headers.get("content-type");if(!c?.startsWith(di))throw Error(`v4 getEvent: expected ${di}, got ${c??"(none)"}`);let A=a.body;try{for await(let u of AD(A)){if(u.meta._error===1)throw p7(u.meta,"getEvent");if(Object.keys(u.meta).some((l)=>l.startsWith("_")))throw Error("v4 getEvent: unexpected control frame");return A7(u)}}catch(u){if(u instanceof ns&>.is(u.cause))throw u.cause;throw u}throw Error(`v4 getEvent: empty frame stream for ${t}`)}function p7(e,t){let r=Tqe.safeParse(e);if(!r.success)return new G(`v4 ${t}: malformed terminal error frame`,{code:"SCHEMA_VALIDATION",cause:r.error});let{code:n,message:o}=r.data,s=o??"(no detail)";if(n===vqe)return new vg(`the event log references a payload that no longer exists in storage: ${s}`);return new G(`v4 ${t}: stream ended with terminal error "${n}": ${s}`,{code:"WORLD_CONTRACT_ERROR"})}var Yqe=2;function QD(e,t){let r=e.at(-1)?.eventId;if(!r)throw t;return{kind:"partial",events:e,cursor:`eid:${r}`,hasMore:!0,error:t}}async function E7(e,t,r){let n=e.headers.get("content-type");if(!n?.startsWith(di))throw new G(`v4 ${t}: expected ${di}, got ${n??"(none)"}`,{code:"SCHEMA_VALIDATION"});if(!e.body)throw new G(`v4 ${t}: response body is missing`,{code:"TRANSPORT"});let o=[];try{for await(let s of AD(e.body)){if(s.meta._end===1){let a=Rqe.parse(s.meta),c=Dqe(a.snapshot)??bqe(e.headers);return{kind:"complete",events:o,cursor:a.next??null,hasMore:a.hasMore,...c?{snapshot:c}:{}}}if(s.meta._error===1)throw p7(s.meta,t);if(Object.keys(s.meta).some((a)=>a.startsWith("_")))throw Error(`v4 ${t}: unexpected control frame`);let i=A7(s);o.push(i);try{r?.(i)}catch(a){throw new qa(a)}}}catch(s){if(s instanceof qa||vg.is(s)||G.is(s))throw s;if(s instanceof ns&>.is(s.cause))return QD(o,s.cause);if(!(s instanceof ns))throw new G(`v4 ${t}: invalid event frame stream`,{code:"SCHEMA_VALIDATION",cause:s});return QD(o,new G(`v4 ${t}: incomplete event frame stream`,{code:"TRANSPORT",cause:s}))}return QD(o,new G(`v4 ${t}: frame stream ended without the end-of-stream sentinel (${o.length} events read)`,{code:"TRANSPORT"}))}async function m7(e,{runId:t,eventsRemoteRefBehavior:r},n,o){let s=await E7(e,"createEvent",o);if(!s.hasMore)return{events:s.events,cursor:s.cursor,hasMore:!1};if(!s.cursor)throw new G("v4 createEvent: partial event stream missing cursor",{code:"SCHEMA_VALIDATION"});let i;try{i=await kD(t,{cursor:s.cursor,remoteRefBehavior:r==="skip-step-inputs"?"skip-step-inputs":"resolve"},n,o)}catch(a){if(Dn.is(a))throw new iu(a);throw a}return{events:[...s.events,...i.events],cursor:i.cursor??s.cursor,hasMore:i.hasMore}}async function _D(e,t,r,n,o){let s=await km(e,{method:"GET",headers:t},r,n);return E7(s,n,o)}var DD=Yt("@workflow/world-vercel//skipStepInputsSupport",2,()=>({unsupportedSince:new Map})),qqe=600000;function Jqe(e){let t=DD.unsupportedSince.get(e);if(t===void 0)return!1;if(Date.now()-t<qqe)return!0;return DD.unsupportedSince.delete(e),!1}function zqe(e){return e instanceof G&&e.status===400&&e.code==="validation-error"}async function I7(e,t,r,n,o,s,i){if(t==="skip-step-inputs"&&!Jqe(e)){try{return await _D(r(t),n,o,s,i)}catch(c){if(!zqe(c))throw c}let a=await _D(r("resolve"),n,o,s,i);return DD.unsupportedSince.set(e,Date.now()),a}return _D(r(t==="skip-step-inputs"?"resolve":t),n,o,s,i)}function y7(e,t){if(t.cursor)e.set("cursor",t.cursor);if(t.limit!==void 0)e.set("limit",String(t.limit));if(t.sortOrder)e.set("sortOrder",t.sortOrder);if(t.remoteRefBehavior)e.set("remoteRefBehavior",t.remoteRefBehavior)}function Zqe(e){let t=new URLSearchParams;if(e.limit===void 0)t.set("returnAll","true");return y7(t,e),`?${t.toString()}`}async function kD(e,t={},r,n){let{baseUrl:o,headers:s}=await Ye(r),i=[],a=t.cursor??null,c=0,A,u=t.limit===void 0,l=wf("reading events","bounded");for(;;){let d=a??void 0;try{A=await I7(o,t.remoteRefBehavior,(h)=>`${o}/v4/runs/${encodeURIComponent(e)}/events`+Zqe({...t,remoteRefBehavior:h,cursor:d}),s,r,"listEvents",n)}catch(h){if(!u||!Dn.is(h))throw h;await l(h);continue}let f=!!A.cursor&&A.cursor!==a;if(A.kind==="partial"){if(t.limit!==void 0||!f||c===Yqe)throw A.error;c++,a=A.cursor}else if(!f&&(A.events.length>0||A.hasMore))throw new G("v4 listEvents: response did not advance cursor",{code:"SCHEMA_VALIDATION"});for(let h of A.events)i.push(h);if(A.kind!=="partial")break}return{events:i,cursor:A.cursor||(c>0?a:null),hasMore:A.hasMore,...A.kind==="complete"&&A.snapshot?{snapshot:A.snapshot}:{}}}async function C7(e,t,r={},n){let{baseUrl:o,headers:s}=await Ye(n),i=await I7(o,r.remoteRefBehavior,(a)=>{let c=new URLSearchParams;return c.set("correlationId",e),c.set("runId",t),y7(c,{...r,remoteRefBehavior:a}),`${o}/v4/events?${c.toString()}`},s,n,"listEventsByCorrelationId");if(i.kind==="partial")throw i.error;return{events:i.events,cursor:i.cursor,hasMore:i.hasMore}}Ur();No();Er();at();On();Dr();var w7=j(Li.omit({error:!0,errorCode:!0}).extend({error:vo([Se,Wt()]).optional(),errorCode:Q().optional(),blobStorageBytes:z().optional(),streamStorageBytes:z().optional()})),xm=j(w7),xD=j(w7.omit({input:!0,output:!0}).extend({inputRef:Wt().optional(),outputRef:Wt().optional(),input:vo([_c(Uint8Array),Wt()]).optional(),output:vo([_c(Uint8Array),Wt()]).optional(),dynamicWorkflowCode:Wt().optional()}));function ND(e,t){if(t==="none"){let{inputRef:r,outputRef:n,dynamicWorkflowCode:o,...s}=e;return{...CD(GE(s)),input:void 0,output:void 0}}return CD(GE(e))}async function Q7(e={},t){let{workflowName:r,status:n,pagination:o,resolveData:s=yn}=e,i=new URLSearchParams;if(r)i.set("workflowName",r);if(Array.isArray(n))throw new G("listWorkflowRuns: status does not support an array of statuses on world-vercel yet; pass a single status",{code:"INVALID_ARGUMENT",field:"status"});if(n)i.set("status",n);if(o?.limit)i.set("limit",o.limit.toString());if(o?.cursor)i.set("cursor",o.cursor);if(o?.sortOrder)i.set("sortOrder",o.sortOrder);let a=s==="none"?"lazy":"resolve";i.set("remoteRefBehavior",a);let c=i.toString(),A=`/v2/runs${c?`?${c}`:""}`,u=await Te({endpoint:A,options:{method:"GET"},config:t,schema:or(a==="lazy"?xD:xm)});return{...u,data:u.data.map((l)=>ND(l,s))}}async function _7(e,t){let r=await Te({endpoint:"/v1/runs/create",options:{method:"POST"},data:e,config:t,schema:xm});return GE(r)}async function _f(e,t,r){let n=t?.resolveData??yn;try{return await S7(e,{resolveData:n},r)}catch(o){if(o instanceof G&&o.status===404)throw new Uc(e);throw o}}async function S7(e,t,r){let{resolveData:n,waitMs:o,signal:s}=t,i=n==="none"?"lazy":"resolve",a=new URLSearchParams;if(a.set("remoteRefBehavior",i),o!==void 0)a.set("waitMs",String(o));let c=o===void 0?"":"/status",A=a.toString(),u=`/v2/runs/${encodeURIComponent(e)}${c}${A?`?${A}`:""}`,l=await Te({endpoint:u,options:{method:"GET",...s?{signal:s}:{}},config:r,retryConnectTimeout:!0,schema:i==="lazy"?xD:xm});return ND(l,n)}var Kqe=1e4,Xqe=300000,B7=Yt("@workflow/world-vercel//runStatusLongPollSupport",1,()=>({unsupportedUntilByBaseUrl:new Map}));function eJe(e){if(e.status===404||e.status===405||e.status===501)return!0;if(e.status===504)return!0;return e.status===void 0&&(e.code==="TIMEOUT"||e.code==="TRANSPORT")}async function b7(e,t,r){let n=t?.resolveData??yn,o=Math.max(0,Math.min(t?.timeoutMs??0,Zo()-Kqe)),{baseUrl:s}=Un(r),i=B7.unsupportedUntilByBaseUrl.get(s)??0;if(o===0||Date.now()<i)return _f(e,{resolveData:n},r);try{return await S7(e,{resolveData:n,waitMs:o,...t?.signal?{signal:t.signal}:{}},r)}catch(a){if(t?.signal?.aborted)throw a;if(!(a instanceof G)||!eJe(a))throw a;let c=await _f(e,{resolveData:n},r);return B7.unsupportedUntilByBaseUrl.set(s,Date.now()+Xqe),c}}async function D7(e,t,r){let n=[...new Set(e)],o=await Promise.all(n.map(async(i)=>{try{return await _f(i,t,r)}catch(a){if(a instanceof Uc)return null;throw a}})),s=new Map(n.map((i,a)=>[i,o[a]]));return e.map((i)=>s.get(i)??null)}async function R7(e,t,r){let n=t?.resolveData??yn,o=n==="none"?"lazy":"resolve",s=new URLSearchParams;s.set("remoteRefBehavior",o);let i=s.toString(),a=`/v1/runs/${encodeURIComponent(e)}/cancel${i?`?${i}`:""}`;try{let c=await Te({endpoint:a,options:{method:"PUT"},config:r,schema:o==="lazy"?xD:xm});return ND(c,n)}catch(c){if(c instanceof G&&c.status===404)throw new Uc(e);throw c}}async function T7(e,t){let{runIds:r,cancelReason:n}=jB.parse(e),o=await Te({endpoint:"/v4/runs/cancel",options:{method:"POST"},data:n!==void 0?{runIds:r,cancelReason:n}:{runIds:r},config:t,schema:WB}),s=new Map(o.results.map((c)=>[c.runId,c]));if(!(s.size===o.results.length&&o.results.length===r.length&&r.every((c)=>s.has(c))))throw new G(`Bulk cancel response did not contain exactly one result per requested run ID (requested ${r.length}, received ${o.results.length}).`);let a=r.map((c)=>s.get(c));return{summary:o.summary,results:a}}var tJe=j(H({attributes:Nr(Q(),Q())}));async function v7(e,t,r,n){try{return{attributes:(await Te({endpoint:`/v2/runs/${encodeURIComponent(e)}/attributes`,options:{method:"POST"},data:r?.allowReservedAttributes?{changes:t,allowReservedAttributes:!0}:{changes:t},config:n,schema:tJe})).attributes}}catch(o){if(o instanceof G&&o.status===404)throw new Uc(e);throw o}}Dr();function rJe(e){let t=e.startsWith("wrun_")?e.slice(5):e;try{return Dg(`wrun_${HA(t).ulid}`,"wrun_")}catch{return Dg(e,"wrun_")}}var nJe=new Set(["run_created","run_started","step_started"]);function oJe(){}oJe();function x7(e){if(e.eventType==="attr_set")try{OB(e.eventData)}catch(s){if(!(s instanceof ko))throw s;throw new G(s.message,{status:400})}let t=e.eventData??{},r=Bs(e.eventType),n={};if(typeof t.deploymentId==="string")n.deploymentId=t.deploymentId;if(typeof t.workflowName==="string")n.workflowName=t.workflowName;if(typeof t.stepName==="string")n.stepName=t.stepName;if(typeof t.attempt==="number")n.attempt=t.attempt;if(t.resumeAt instanceof Date)n.resumeAt=t.resumeAt;else if(typeof t.resumeAt==="string"){let s=new Date(t.resumeAt);if(!Number.isNaN(s.getTime()))n.resumeAt=s}if(t.retryAfter instanceof Date)n.retryAfter=t.retryAfter;else if(typeof t.retryAfter==="string"){let s=new Date(t.retryAfter);if(!Number.isNaN(s.getTime()))n.retryAfter=s}if(typeof t.token==="string")n.hookToken=t.token;if(t.tokenRetentionUntil instanceof Date)n.hookTokenRetentionUntil=t.tokenRetentionUntil;if(typeof t.isWebhook==="boolean")n.hookIsWebhook=t.isWebhook;if(typeof t.isSystem==="boolean")n.hookIsSystem=t.isSystem;if(t.force===!0)n.hookForce=!0;if(typeof t.errorCode==="string")n.errorCode=t.errorCode;if(typeof t.cancelReason==="string")n.cancelReason=t.cancelReason;if(typeof t.ownerMessageId==="string")n.ownerMessageId=t.ownerMessageId;if(t.executionContext!==void 0&&t.executionContext!==null&&typeof t.executionContext==="object")n.executionContext=t.executionContext;if(t.attributes!==void 0&&t.attributes!==null&&typeof t.attributes==="object")n.attributes=t.attributes;if(Array.isArray(t.changes))n.changes=t.changes;if(t.writer!==void 0&&t.writer!==null&&typeof t.writer==="object")n.writer=t.writer;if(typeof t.allowReservedAttributes==="boolean")n.allowReservedAttributes=t.allowReservedAttributes;if(typeof t.encryptionPublicKey==="string")n.encryptionPublicKey=t.encryptionPublicKey;if(t.dynamicWorkflowCode instanceof Uint8Array)n.dynamicWorkflowCode=t.dynamicWorkflowCode;if(typeof t.dynamicWorkflowCodeRef==="string")n.dynamicWorkflowCodeRef=t.dynamicWorkflowCodeRef;if(typeof t.ttfs==="number")n.ttfs=t.ttfs;if(typeof t.stso==="number")n.stso=t.stso;if(typeof t.stepCount==="number"&&Number.isSafeInteger(t.stepCount)&&t.stepCount>0)n.stepCount=t.stepCount;if(typeof t.eventCount==="number"&&Number.isSafeInteger(t.eventCount)&&t.eventCount>0)n.eventCount=t.eventCount;if(typeof t.rsfs==="number")n.rsfs=t.rsfs;if(typeof t.finalSchedulingReplay==="number")n.finalSchedulingReplay=t.finalSchedulingReplay;if(Array.isArray(t.optimizations)&&t.optimizations.every((s)=>typeof s==="string"))n.optimizations=t.optimizations;let o;if(r&&r in t){let s=t[r];if(s!==void 0){if(!(s instanceof Uint8Array))throw TypeError(`world-vercel v4: eventData.${r} for ${e.eventType} must be a Uint8Array (the runtime's dehydrated wire form); got ${typeof s==="object"?s===null?"null":s.constructor?.name??typeof s:typeof s}.`);o=s}}return{payload:o,meta:n}}async function N7(e,t,r,n){return g7(e,t,r?.resolveData==="none"?"lazy":"resolve",n)}async function OD(e,t){let{pagination:r,resolveData:n=yn}=e,o={...r,remoteRefBehavior:n==="none"?"lazy":n==="skip-step-inputs"?"skip-step-inputs":"resolve"},s=await("correlationId"in e?C7(e.correlationId,e.runId,o,t):kD(e.runId,o,t));return{data:"correlationId"in e?s.events.filter((i)=>i.runId===e.runId):s.events,cursor:s.cursor,hasMore:s.hasMore,...s.snapshot?{snapshot:s.snapshot}:{}}}async function O7(e,t,r,n){if(t.length===0)throw new G("world-vercel: createBatch requires at least one event",{status:400});if(t.some(({event:a})=>a.eventType==="hook_received"))throw new G("world-vercel: hook_received cannot be batched (it has no entity condition, so a batch retry would append the delivery twice); send it through the single-event path",{status:400});let o=t.map(({event:a,occurredAt:c,computeInstanceId:A})=>{let{payload:u,meta:l}=x7(a);return{runId:e,eventType:a.eventType,specVersion:a.specVersion??2,...a.correlationId?{correlationId:a.correlationId}:{},occurredAt:c??new Date,...A!==void 0?{computeInstanceId:A}:{},remoteRefBehavior:r?.resolveData==="all"?"resolve":"lazy",...r?.requestId?{vercelId:r.requestId}:{},payload:u,...l,...r?.inBand!==void 0?{inBand:r.inBand}:{},...r?.expectedSeqInBand!==void 0?{expectedSeqInBand:r.expectedSeqInBand}:{}}}),s=t.every(({event:a})=>a.eventType!=="step_started"&&a.eventType!=="step_retrying");return{results:(await mD(()=>f7({runId:e,events:o},n),t[0].event.eventType,{batchIdempotent:s,inBand:r?.inBand===!0})).results.map((a)=>{if(a.error!==void 0)return{status:a.status,error:a.error,message:a.message};return{status:200,event:a.event,...a.run?{run:a.run}:{},...a.step?{step:a.step}:{},...a.wait?{wait:a.wait}:{}}})}}async function U7(e,t,r,n){try{let o=await mD(()=>sJe(e,t,r,n),t.eventType,{idempotentHookResume:t.eventType==="hook_received"&&r?.resumeId!==void 0&&r?.resumePayloadDigest!==void 0,afterStepBody:r?.afterStepBody===!0,inBand:r?.inBand===!0});if(t.eventType==="run_created"&&!o.run)throw new G(`${t.eventType} response is missing the run entity`,{code:"SCHEMA_VALIDATION"});if(t.eventType==="run_started"&&!o.run?.startedAt)throw new G("run_started response is missing run.startedAt",{code:"SCHEMA_VALIDATION"});if(t.eventType==="step_started"&&!o.step?.startedAt)throw new G("step_started response is missing step.startedAt",{code:"SCHEMA_VALIDATION"});return o}catch(o){if(o instanceof qa)throw o.error;if(o instanceof iu)throw o.error;if(Oo.is(o)&&t.eventType==="hook_received"){let s=t.eventData?.token;throw new Oo(typeof s==="string"?s:o.token,o.claimedByRunId,o.claimedByHookId)}if(HB(t.eventType)&&G.is(o)&&o.status===404&&t.correlationId)throw new dl(t.correlationId);throw o}}async function sJe(e,t,r,n){if(r?.v1Compat){if(t.eventType==="run_cancelled"&&e)return{run:await R7(e,{...r,resolveData:ow(r.resolveData)},n)};if(t.eventType==="run_created")return{run:await _7(t.eventData,n)};if(e===null)throw new G(`world-vercel: v1Compat=true requires a runId for ${t.eventType}`,{status:400});return{event:await Te({endpoint:`/v1/runs/${encodeURIComponent(e)}/events`,options:{method:"POST"},data:t,config:n,schema:Ja})}}if(e===null)throw new G("world-vercel v4: createWorkflowRunEvent requires a client-generated runId for run_created (the runId is part of the payload storage ref key). Generate a wrun_ ULID before calling.",{status:400});if(t.eventType==="run_created"){let c=rJe(e);if(c)throw new G(c,{status:400})}let o=nJe.has(t.eventType)?"resolve":"lazy",{payload:s,meta:i}=x7(t),a={runId:e,specVersion:t.specVersion??2,...t.eventType==="run_started"?{executorSpecVersion:n?.mintedSpecVersion??Al()}:{},...t.correlationId?{correlationId:t.correlationId}:{},...r?.requestId?{vercelId:r.requestId}:{},...r?.computeInstanceId?{computeInstanceId:r.computeInstanceId}:{},...r?.eventCount!==void 0?{maxSlot:r.eventCount}:{},replayDivergenceCount:r?.replayDivergenceCount,...r?.inBand!==void 0?{inBand:r.inBand}:{},...r?.expectedSeqInBand!==void 0?{expectedSeqInBand:r.expectedSeqInBand}:{},occurredAt:r?.occurredAt??new Date,...r?.sinceCursor?{sinceCursor:r.sinceCursor}:{},...r?.resumeId?{resumeId:r.resumeId}:{},...r?.resumePayloadDigest?{resumePayloadDigest:r.resumePayloadDigest}:{},...r?.viaStepDispatch?{viaStepDispatch:!0}:{},...r?.resolveData==="skip-step-inputs"?{eventsRemoteRefBehavior:"skip-step-inputs"}:{},remoteRefBehavior:o,payload:s,...i};if(t.eventType==="run_started"&&!r?.skipPreload){let c=await d7(a,n,r?.replayEventObserver),A=k7(c.events);if(!A)throw new G("v4 createEvent: run_started stream is missing lifecycle events",{code:"SCHEMA_VALIDATION"});return{event:A.event,run:A.run,events:c.events,cursor:c.cursor,hasMore:c.hasMore,maxEvents:c.maxEvents}}if(t.eventType==="hook_received"&&r?.preloadEvents===!0&&r.resumeId!==void 0&&r.resumePayloadDigest!==void 0){let c=await h7({...a,remoteRefBehavior:"lazy"},n,r.replayEventObserver);if(c.kind==="materialized")return c.result;let{canonicalEventId:A,maxEvents:u,events:l,cursor:d,hasMore:f}=c,h=l.find((p)=>p.eventId===A),g=k7(l);return{...h?{event:h}:{},...g?{run:g.run}:{},events:l,cursor:d,hasMore:f,...u!==void 0?{maxEvents:u}:{}}}return l7(t.eventType==="run_started"?{...a,eventType:"run_started",skipPreload:!0}:{...a,eventType:t.eventType},n)}function k7(e){let t=e.find((s)=>s.eventType==="run_created"),r=e.find((s)=>s.eventType==="run_started");if(!t||!r)return;let n=t.eventData.attributes??{},o=r.createdAt;for(let s of e)if(s.eventType==="attr_set")n=UB(n,s.eventData.changes),o=s.createdAt;return{event:r,run:{runId:t.runId,status:"running",deploymentId:t.eventData.deploymentId,workflowName:t.eventData.workflowName,specVersion:t.specVersion,executionContext:t.eventData.executionContext,input:t.eventData.input,attributes:n,encryptionPublicKey:t.eventData.encryptionPublicKey,startedAt:r.createdAt,createdAt:t.createdAt,updatedAt:o}}}Ur();Er();at();Dr();function M7(e,t){if(t==="none"){let{metadataRef:r,...n}=e;return n}return J6(e)}var iJe=j(ws.omit({metadata:!0}).extend({metadataRef:Wt().optional()}));async function F7(e,t){let{runId:r,pagination:n,resolveData:o=yn}=e,s=new URLSearchParams;if(n?.limit)s.set("limit",n.limit.toString());if(n?.cursor)s.set("cursor",n.cursor);if(n?.sortOrder)s.set("sortOrder",n.sortOrder);let i=o==="none"?"lazy":"resolve";if(s.set("remoteRefBehavior",i),r)s.set("runId",r);let a=s.toString(),c=`/v2/hooks${a?`?${a}`:""}`,A=await Te({endpoint:c,options:{method:"GET"},config:t,schema:or(i==="lazy"?iJe:ws)});return{...A,data:A.data.map((u)=>M7(u,o))}}async function L7(e,t,r){let n=t?.resolveData||"all",o=`/v2/hooks/${encodeURIComponent(e)}`,s=await Te({endpoint:o,options:{method:"GET"},config:r,schema:ws});return M7(s,n)}async function P7(e,t){try{return await Te({endpoint:`/v2/hooks/by-token?token=${encodeURIComponent(e)}`,options:{method:"GET"},config:t,schema:ws})}catch(r){if(G.is(r)&&r.status===404)throw new dl(e);throw r}}Ur();Er();Q0();Eo();On();Nn();Dr();function aJe(e){let t={};for(let[r,n]of e)t[r]=n;return t}function Nm(e){if(!FA)return;console.debug("[workflow:world-vercel:http] WORLD_SNAPSHOT_DIAG",e)}var H7=67108864;function V7(e){return{async save(t,r,n){let o=performance.now(),{baseUrl:s,headers:i}=await Ye(e),a=`${s}/v2/runs/${encodeURIComponent(t)}/snapshot`,c=Aw(n,r);if(c.byteLength>H7)throw Nm({op:"save",runId:t,outcome:"too_large",wireBytes:c.byteLength}),new G(`Snapshot for run ${t} is ${c.byteLength} bytes, over the ${H7}-byte limit; not uploading`,{url:a});i.set("Content-Type","application/octet-stream"),i.set("X-Snapshot-Events-Cursor",n.eventsCursor??""),i.set("X-Snapshot-Created-At",n.createdAt.toISOString()),await In(i);let A=performance.now(),u=await w0(a,{method:"PUT",body:c,headers:aJe(i),dispatcher:po(e)}),l=Math.round(performance.now()-A);if(u.statusCode<200||u.statusCode>=300){let d=await u.body.text().catch(()=>"");throw new G(`PUT /v2/runs/${t}/snapshot -> HTTP ${u.statusCode}: ${d}`,{url:a,status:u.statusCode})}await u.body.text(),Nm({op:"save",runId:t,wireBytes:c.byteLength,putDurationMs:l,totalDurationMs:Math.round(performance.now()-o)})},async load(t){let r=performance.now(),{baseUrl:n,headers:o}=await Ye(e),s=`${n}/v2/runs/${encodeURIComponent(t)}/snapshot`;o.set("Accept","application/octet-stream"),await In(o);let i=performance.now(),a=await fetch(s,{method:"GET",headers:o,dispatcher:po(e)}),c=Math.round(performance.now()-i);if(a.status===404)return await a.text().catch(()=>{}),Nm({op:"load",runId:t,outcome:"not_found",getDurationMs:c,totalDurationMs:Math.round(performance.now()-r)}),null;if(!a.ok){let d=await a.text().catch(()=>"");throw new G(`GET /v2/runs/${t}/snapshot -> HTTP ${a.status}: ${d}`,{url:s,status:a.status})}let A=await a.arrayBuffer(),u=new Uint8Array(A),l=uw(u);return Nm({op:"load",runId:t,outcome:l?"ok":"undecodable_envelope",wireBytes:u.byteLength,getDurationMs:c,totalDurationMs:Math.round(performance.now()-r)}),l},async delete(t){let{baseUrl:r,headers:n}=await Ye(e),o=`${r}/v2/runs/${encodeURIComponent(t)}/snapshot`;await In(n);let s=await fetch(o,{method:"DELETE",headers:n,dispatcher:po(e)});if(!s.ok&&s.status!==404){let i=await s.text().catch(()=>"");throw new G(`DELETE /v2/runs/${t}/snapshot -> HTTP ${s.status}: ${i}`,{url:o,status:s.status})}await s.text()}}}function UD(e){let t=V7(e),r={runs:{get:(n,o)=>_f(n,o,e),waitForTerminalStatus:(n,o)=>b7(n,o,e),getMany:(n,o)=>D7(n,o,e),list:(n)=>Q7(n,e),experimentalSetAttributes:(n,o,s)=>v7(n,o,s,e),cancelMany:(n)=>T7(n,e)},steps:{get:(n,o,s)=>X6(n,o,s,e),list:(n)=>K6(n,e)},events:{create:(n,o,s)=>U7(n,o,s,e),createBatch:(n,o,s)=>O7(n,o,s,e),get:(n,o,s)=>N7(n,o,s,e),list:(n)=>OD(n,e),listByCorrelationId:(n)=>OD(n,e)},hooks:{get:(n,o)=>L7(n,o,e),getByToken:(n)=>P7(n,e),list:(n)=>F7(n,e)},experimental_snapshots:t};return{runs:Ai("world.runs",r.runs),steps:Ai("world.steps",r.steps),events:Ai("world.events",r.events),hooks:Ai("world.hooks",r.hooks),experimental_snapshots:Ai("world.experimental_snapshots",t)}}Ur();Er();at();Eo();On();var Sf=1000;function bf(e){let t=new TextEncoder;return e.map((r)=>typeof r==="string"?t.encode(r):r)}function Om(e){return MD(bf(e))}function MD(e){let t=0;for(let s of e)if(t+=4+s.length,t>4294967295)throw RangeError(`encoded stream chunks exceed the u32 body-length limit: ${t} bytes`);let r=new Uint8Array(t),n=new DataView(r.buffer),o=0;for(let s of e)n.setUint32(o,s.length,!1),o+=4,r.set(s,o),o+=s.length;return r}Nn();Dr();var nee=Ke(Pc(),1);ou();On();at();ou();var j7=Sf,$7=10485760,cJe=128,G7=4,FD=z().int().nonnegative(),Df=FD,LD=Q().regex(/^wrtr_[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$/),W7=H({type:ue("write"),reqId:Df,chunkSeq:FD,numChunks:z().int().positive().max(j7)}),Y7=H({type:ue("close"),reqId:Df}),Bst=Mi("type",[W7,Y7]),AJe=H({type:ue("write_ack"),reqId:Df}),uJe=H({type:ue("close_ack"),reqId:Df}),lJe=H({type:ue("error"),reqId:Df.optional(),status:z().int(),message:Q().optional(),retryAfter:Q().optional()}),dJe=H({type:ue("drain"),reason:Cs(["auth_expiry","max_duration"]),graceMs:FD}),fJe=Mi("type",[AJe,uJe,lJe,dJe]);function q7(e,t,r,n){let o=LD.parse(n),s=new URL(e);return s.protocol=s.protocol==="https:"?"wss:":"ws:",s.pathname=`${s.pathname.replace(/\/$/,"")}/websockets/v1/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(r)}`,s.search=new URLSearchParams({writerId:o}).toString(),s}function J7(e,t){let r=W7.parse(e);if(r.numChunks!==t.length)throw Error(`stream WebSocket write declares ${r.numChunks} chunks but received ${t.length}`);let n=bf(t);for(let o of n){let s=o.byteLength;if(s>$7)throw Error(`stream WebSocket chunk is ${s} bytes; maximum is ${$7}`)}return zr(r,MD(n))}function z7(e,t,r){let n=Math.min(e.length,t+j7),o=cJe+G7+e[t].byteLength,s=t+1;while(s<n){if(o+=G7+e[s].byteLength,o>r)break;s++}return s}function Z7(e){return zr(Y7.parse(e),new Uint8Array)}function K7(e,t){if(t.byteLength!==0)throw Error("stream WebSocket reply body must be empty");return fJe.parse(e)}Nn();Dr();fD();Nn();var X7=1e4,eee=250,hJe=250;function PD(e,t){if(e.readyState===3)return;let r=!1,n=new Promise((s)=>{let i=!1,a=()=>{if(i)return;i=!0,clearTimeout(c),s()},c=setTimeout(()=>{r=!0,a()},hJe);c.unref?.(),e.once("close",a)}),o=mo("workflow.stream.ws.close.cleanup",async(s)=>{await n,s?.setAttribute("workflow.stream.ws.close_cleanup_timeout",r)});Promise.resolve().then(() => Ke(Nb(),1)).then(({waitUntil:s})=>s(o)).catch(()=>{}),o.catch(()=>{}),e.close(1000,t)}var tee=3;function ss(){return performance.now()}function gJe(e,t,r){if(!e)return{};return{"workflow.stream.ws.session_first_write":e.sessionFirstWrite,"workflow.stream.ws.connection_first_write":t?.firstWriteSent===!1,"workflow.stream.ws.connection_attempt":t?.attempt??0,"workflow.stream.ws.session_to_write_ms":e.startedAt-r}}function pJe(e,t,r){if(r)r.firstWriteSent=!0;let n=r?.openedAt,o=r?.socketStartedAt,s=r?.configFinishedAt;e?.setAttributes({"workflow.stream.ws.write_wait_for_open_ms":n?Math.max(0,n-t.startedAt):0,...o&&s?{"workflow.stream.ws.connect_setup_ms":o-s}:{},...o&&n?{"workflow.stream.ws.connect_ms":n-o}:{},...s&&r?{"workflow.stream.ws.config_token_ms":s-r.configStartedAt}:{}})}function EJe(e,t,r,n){let o=ss();n.sentAt=o,e?.setAttributes({"workflow.stream.ws.write_to_send_ms":o-t.startedAt,...r?.openedAt?{"workflow.stream.ws.open_to_send_ms":Math.max(0,o-r.openedAt)}:{}})}function mJe(e,t,r){if(r?.sentAt===void 0||r.replyReceivedAt===void 0)return;let n=ss();e?.setAttributes({"workflow.stream.ws.send_to_reply_ms":r.replyReceivedAt-r.sentAt,"workflow.stream.ws.reply_processing_ms":n-r.replyReceivedAt,"workflow.stream.ws.write_total_ms":n-t.startedAt})}var IJe=86400000;function ree(e){return e.get("authorization")}class za extends Error{constructor(e){super(e instanceof Error?e.message:String(e),{cause:e});this.name="StreamWsRequestNotSentError"}}class HD extends Error{retryAfter;constructor(e,t){super(e);this.retryAfter=t,this.name="StreamWsThrottledError"}}class VD extends Error{constructor(e){super(e);this.name="StreamWsCloseRetriableError"}}function yJe(e){if(e instanceof Uint8Array)return e;if(typeof e==="string")return new TextEncoder().encode(e);return new Uint8Array(e)}class oee{runId;name;writerId;config;writeHttp;closeHttp;connectAfterFirstWrite;mode="connecting";socket;connect=Promise.resolve();transportDecision=Promise.resolve();tail=Promise.resolve();inbound=Promise.resolve();nextReqId=1;pending;poisonError;throttledSocket;terminated=new AbortController;wsUrl;closeAcknowledged=!1;idleReconnects=0;drainReason;drainTimer;releaseDrainWait;lastAuthorization=null;sessionCreatedAt=ss();sessionHasWrite=!1;connectionAttempt=0;connectionTiming;constructor(e,t,r,n,o,s,i){if(this.runId=e,this.name=t,this.writerId=r,this.config=n,this.writeHttp=o,this.closeHttp=s,this.connectAfterFirstWrite=i,i)this.mode="deferred";else this.startInitialConnect()}write(e,t){let r={startedAt:ss(),sessionFirstWrite:!this.sessionHasWrite};return this.sessionHasWrite=!0,this.enqueue(()=>this.writeInternal(e,t,r))}async writeInternal(e,t,r){if(this.assertUsable(),this.mode==="deferred"){await this.writeFirstGroup(t,r);return}if(this.mode==="waiting_to_connect"){await this.writeSecondGroupAndStartConnect(t,r);return}if(this.shouldWriteHttpWhileConnecting()){await this.writeWhileInitialConnectRuns(t,r);return}if(await this.transportDecision,this.assertUsable(),this.mode==="http"){await this.writeHttpOrFail(t);return}let n=Bf(),o=bf(t);for(let s=0;s<t.length;){let i=z7(o,s,n),a=o.slice(s,i),c;try{c=await this.requestRetryingThrottle("write",(A)=>J7({type:"write",reqId:A,chunkSeq:e+s,numChunks:a.length},a),s===0?r:void 0,{chunkSeq:e+s,numChunks:a.length},n)}catch(A){if(!(A instanceof za))throw A;this.fallbackToHttpBeforeSend(),await this.writeHttpOrFail(t.slice(s));return}if(c.type!=="write_ack")throw this.poison(Error(`stream WebSocket write received ${c.type}`));s=i}}async writeHttpOrFail(e){try{await this.writeHttp(e)}catch(t){throw this.failUnknown(t),this.poisonError}}shouldWriteHttpWhileConnecting(){return this.mode==="connecting"&&this.connectionAttempt===1}async writeWhileInitialConnectRuns(e,t){try{await this.writeHttp(e,{"workflow.stream.ws.session_first_write":t.sessionFirstWrite,"workflow.stream.ws.connection_attempt":this.connectionAttempt,"workflow.stream.ws.connecting_at_write":!0,"workflow.stream.ws.session_to_write_ms":t.startedAt-this.sessionCreatedAt})}catch(r){throw this.failUnknown(r),this.poisonError}}async writeSecondGroupAndStartConnect(e,t){try{await this.writeHttp(e,{"workflow.stream.ws.session_first_write":t.sessionFirstWrite,"workflow.stream.ws.connection_attempt":0,"workflow.stream.ws.connecting_at_write":!1,"workflow.stream.ws.connect_after_http_group":2,"workflow.stream.ws.session_to_write_ms":t.startedAt-this.sessionCreatedAt},()=>{if(this.mode!=="waiting_to_connect")return;this.startInitialConnect()})}catch(r){throw this.failUnknown(r),this.poisonError}}async writeFirstGroup(e,t){try{await this.writeHttp(e,{"workflow.stream.ws.session_first_write":t.sessionFirstWrite,"workflow.stream.ws.connection_attempt":0,"workflow.stream.ws.connecting_at_write":!1,"workflow.stream.ws.connect_deferred_at_write":!0,"workflow.stream.ws.http_group_ordinal":1,"workflow.stream.ws.session_to_write_ms":t.startedAt-this.sessionCreatedAt})}catch(r){throw this.failUnknown(r),this.poisonError}if(this.mode==="deferred")this.mode="waiting_to_connect"}release(){return this.enqueue(async()=>{if(this.mode==="closed"||this.mode==="poisoned")return;this.fallbackToHttpBeforeSend("stream writer released")})}dispose(){if(this.mode==="closed")return;this.mode="closed",this.terminated.abort(),this.finishDrainWait();let e=this.pending;if(this.pending=void 0,e)clearTimeout(e.timer),e.reject(Error("stream writer transport disposed"));this.socket?.close(1000,"stream writer disposed")}close(){return this.enqueue(async()=>{if(this.assertUsable(),this.mode==="deferred"||this.mode==="waiting_to_connect"||this.connectAfterFirstWrite&&this.mode==="connecting"&&this.connectionAttempt===1){await this.closeHttp(),this.mode="closed",this.socket?.close(1000,"stream closed over HTTP");return}if(await this.transportDecision,this.assertUsable(),this.mode==="http"){await this.closeHttp(),this.mode="closed";return}await this.closeOverWs()})}async closeOverWs(){let e;try{e=await this.requestRetryingThrottle("close",(t)=>Z7({type:"close",reqId:t}))}catch(t){if(!(t instanceof za||t instanceof VD))throw t;this.fallbackToHttpBeforeSend(),await this.closeHttp(),this.mode="closed";return}if(e.type!=="close_ack")throw this.poison(Error(`stream WebSocket close received ${e.type}`));if(this.mode="closed",this.socket)PD(this.socket,"stream closed")}enqueue(e){let t=this.tail.then(e);return this.tail=t.catch(()=>{}),t}assertUsable(){if(this.mode==="poisoned")throw this.poisonError;if(this.mode==="closed")throw Error("stream writer is closed")}startInitialConnect(){this.mode="connecting",this.connect=this.startConnect(),this.transportDecision=this.makeTransportDecision(!1)}makeTransportDecision(e){return new Promise((t)=>{let r=!1,n=()=>{if(r)return;r=!0,clearTimeout(o),t()},o=setTimeout(()=>{if(this.mode==="connecting")this.mode="http",this.socket?.close(1000,"connect budget expired");n()},e?eee:X7);o.unref?.(),this.connect.then(n)})}startConnect(e=!1){let t=ss(),r={attempt:++this.connectionAttempt,configStartedAt:t,firstWriteSent:!1};return this.connectionTiming=r,this.connectSocket(e,r).catch(()=>{if(this.mode==="connecting")this.mode="http"})}async connectSocket(e,t){if(!_m()){this.mode="http";return}if(e)await nee.getVercelOidcToken({expirationBufferMs:IJe}).catch(()=>{return});let r=Ye(this.config).then((i)=>(t.configFinishedAt=ss(),i)),[{WebSocket:n},o]=await Promise.all([Promise.resolve().then(() => (um(),vb)),r]);if(this.mode!=="connecting")return;if(e&&ree(o.headers)===this.lastAuthorization){this.mode="http";return}if(this.lastAuthorization=ree(o.headers),o.usingProxy){this.mode="http";return}if(this.mode!=="connecting")return;let s=q7(o.baseUrl,this.runId,this.name,this.writerId);this.wsUrl=s.toString(),await ri({method:"GET",url:this.wsUrl,spanName:"workflow.stream.ws.connect",attributes:{"workflow.stream.transport":"ws"}},async()=>{if(await In(o.headers),this.mode!=="connecting")return;t.socketStartedAt=ss();let i=new n(s,{headers:LA(o.headers)});this.socket=i,i.binaryType="nodebuffer",await new Promise((a)=>{let c=!1,A=()=>{if(c)return;if(this.mode==="connecting")this.mode="http";a()};i.once("open",()=>{if(c=!0,t.openedAt=ss(),this.mode!=="connecting"){i.close(1000,"HTTP fallback selected"),a();return}this.mode="ws",a()}),i.once("unexpected-response",(u,l)=>{let d=l;d.resume?.(),d.destroy?.(),i.close(1000,"upgrade declined"),A()}),i.once("error",(u)=>{if(!c){A();return}this.inbound.then(()=>{if(i!==this.socket)return;if(this.isIdleThrottledSocket(i)){this.leaveThrottledSocketForHttp();return}this.failUnknown(u)})}),i.once("close",(u)=>{if(!c){A();return}this.inbound.then(()=>this.handleSocketClose(Number(u),i))}),i.on("message",(u)=>{let l=ss();this.inbound=this.inbound.then(()=>this.handleMessage(yJe(u),l))})})})}async handleMessage(e,t){try{let r=nu(e),n=K7(r.meta,r.body);if(n.type==="drain"){this.handleDrain(n.reason,n.graceMs);return}let o=this.pending;if(!o||n.reqId===void 0||n.reqId!==o.reqId){if(n.type==="error")throw Error(`stream WebSocket connection failed (${n.status}): ${n.message??"unknown error"}`);throw Error("stream WebSocket reply cannot be correlated")}if(this.pending=void 0,o.replyReceivedAt=t,clearTimeout(o.timer),n.type==="close_ack")this.closeAcknowledged=!0;if(n.type==="error")o.reject(this.requestError(o,n));else{if(n.type==="write_ack")this.idleReconnects=0;o.resolve(n)}}catch(r){this.failUnknown(r)}}handleDrain(e,t){if(this.mode==="draining"){if(e==="auth_expiry")this.drainReason=e;return}if(this.mode!=="ws")return;this.mode="draining",this.drainReason=e,this.transportDecision=new Promise((n)=>{this.releaseDrainWait=n});let r=this.socket;this.drainTimer=setTimeout(()=>{if(this.drainTimer=void 0,this.mode!=="draining"||r!==this.socket)return;if(this.pending){this.failUnknown(Error("stream WebSocket drain expired before request reply"));return}r?.close(1001,"stream drain grace expired"),this.handleSocketClose(1001,r)},Math.min(t,2147483647)),this.drainTimer.unref?.()}handleSocketClose(e,t=this.socket){if(t!==this.socket)return;if(this.drainTimer)clearTimeout(this.drainTimer),this.drainTimer=void 0;if(this.mode==="closed"||this.mode==="http"||this.mode==="poisoned"||this.closeAcknowledged)return;if(this.pending){this.failUnknown(Error("stream WebSocket closed before reply"));return}if(t&&this.isIdleThrottledSocket(t)&&this.mode==="ws"){this.leaveThrottledSocketForHttp();return}if(this.mode==="draining"&&e!==1001){this.drainReason=void 0,this.mode="http",this.socket=void 0,this.finishDrainWait();return}if(this.mode==="draining"){let r=this.drainReason==="auth_expiry";if(this.drainReason=void 0,this.idleReconnects>=tee){this.mode="http",this.socket=void 0,this.finishDrainWait();return}this.idleReconnects++,this.mode="connecting",this.socket=void 0,this.connect=this.startConnect(r);let n=this.makeTransportDecision(!0);this.transportDecision=n,n.then(()=>this.finishDrainWait());return}if(this.idleReconnects>=tee){this.mode="http",this.socket=void 0;return}this.idleReconnects++,this.mode="connecting",this.socket=void 0,this.connect=this.startConnect(),this.transportDecision=this.makeTransportDecision(!0)}async request(e,t,r,n,o=Bf()){this.assertUsable();let s=this.socket;if(this.mode!=="ws"||!s||s.readyState!==1)throw new za(Error("stream WebSocket is not open before send"));let i=this.nextReqId++,a;try{a=t(i)}catch(l){throw new za(l)}if(a.byteLength>o)throw new za(Error(`stream WebSocket message is ${a.byteLength} bytes; maximum is ${o}`));let c=this.connectionTiming,A=c?.firstWriteSent===!1,u=r&&(r.sessionFirstWrite||A)?r:void 0;return ri({method:"POST",url:this.wsUrl??"ws://unknown",spanName:"workflow.stream.write",attributes:{"workflow.stream.transport":"ws","workflow.stream.ws.req_id":i,...n?{"workflow.stream.ws.chunk_seq":n.chunkSeq,"workflow.stream.ws.num_chunks":n.numChunks}:{},...gJe(u,c,this.sessionCreatedAt)}},async(l)=>{if(u)pJe(l,u,c);let d,f=new Promise((h,g)=>{let p=setTimeout(()=>{this.failUnknown(Error(`stream WebSocket request ${i} timed out with no reply`))},Zo());p.unref?.(),d={reqId:i,operation:e,resolve:h,reject:g,timer:p},this.pending=d;try{if(u)EJe(l,u,c,d);s.send(a,(I)=>{if(!I)return;this.failUnknown(I)})}catch(I){this.failUnknown(I)}});try{return await f}finally{if(u)mJe(l,u,d)}})}finishDrainWait(){if(this.drainTimer)clearTimeout(this.drainTimer),this.drainTimer=void 0;let e=this.releaseDrainWait;this.releaseDrainWait=void 0,e?.()}fallbackToHttpBeforeSend(e="HTTP fallback before send"){this.mode="http",this.drainReason=void 0;let t=this.socket;if(this.socket=void 0,this.transportDecision=Promise.resolve(),this.finishDrainWait(),t)PD(t,e)}requestError(e,t){let r=`(${t.status}): ${t.message??"unknown error"}`;if(t.status===429)return this.throttledSocket=this.socket,new HD(`stream WebSocket ${e.operation} throttled ${r}`,Ha(t.retryAfter));if(e.operation==="close"&&t.status>=500&&t.status<=599)return this.fallbackToHttpBeforeSend("stream close retried over HTTP"),new VD(`stream WebSocket close failed ${r}`);let n=this.poison(Error(`stream WebSocket request failed ${r}`));return this.socket?.close(1011,"stream request failed"),n}async requestRetryingThrottle(e,t,r,n,o){let s=wf(e==="write"?"writing stream chunks":"writing stream close","bounded");for(let i=0;;i++)try{return await this.request(e,t,i===0?r:void 0,n,o)}catch(a){if(!(a instanceof HD))throw a;await this.waitOutThrottle(s,a)}}async waitOutThrottle(e,t){try{await e(t,this.terminated.signal)}catch{throw this.assertUsable(),this.fallbackToHttpBeforeSend("stream request throttled"),new za(t)}finally{this.throttledSocket=void 0}await this.transportDecision,this.assertUsable()}isIdleThrottledSocket(e){return!this.pending&&e===this.throttledSocket&&e===this.socket}leaveThrottledSocketForHttp(){this.drainReason=void 0,this.mode="http",this.socket=void 0,this.finishDrainWait()}failUnknown(e){let t=this.poison(e);this.finishDrainWait();let r=this.pending;if(this.pending=void 0,r)clearTimeout(r.timer),r.reject(t);this.socket?.close(1011,"unknown stream write outcome")}poison(e){if(this.mode!=="poisoned")this.mode="poisoned",this.poisonError=e,this.terminated.abort();return this.poisonError}}function see(e,t,r,n,o,s,i=!0){return new oee(e,t,LD.parse(r),n,o,s,i)}var CJe=Sf,iee=()=>Yn("WORKFLOW_MAX_CHUNKS_PER_REQUEST",CJe,{integer:!0,min:1});function Rf(e,t,r){return new URL(`${r.baseUrl}/v2/runs/${encodeURIComponent(t)}/stream/${encodeURIComponent(e)}`)}function BJe(e,t,r){return new URL(`${r.baseUrl}/v3/runs/${encodeURIComponent(t)}/stream/${encodeURIComponent(e)}`)}function cu(e){return{...Wd(e.runId),...S8(e.name),...b8(e.operation),...typeof e.startIndex==="number"?D8(e.startIndex):{}}}async function wJe(e){let t=`Failed to fetch stream: ${e.status}`;if(e.status!==410)return new gt(t,{status:e.status});try{let r=await e.json();return Va(e.status,typeof r.message==="string"?r.message:t,{code:r.error,details:r.details})}catch{return new gt(t,{status:e.status})}}function $D(e,t){if(G.is(t)||Vi.is(t)||$i.is(t)||gt.is(t)||fl.is(t)||Gi.is(t)||Dn.is(t)||hl.is(t))return t;return new gt(e,{cause:t})}function Tf(e,t,r,n){let o=[`PUT ${t.origin}${t.pathname}`,...HE(r.headers)];return new gt(`Stream ${e} failed: HTTP ${r.status} (${o.join("; ")}): ${n}`,{url:t.toString(),status:r.status})}var QJe=j(H({tailIndex:z(),done:jt()})),_Je=j(H({data:_n(H({index:z(),data:_c(Uint8Array)})),cursor:Q().nullable(),hasMore:jt(),done:jt()}));async function SJe(e,t,r,n,o,s){let i=await Ye(n);i.headers.set("X-Stream-Multi","true");let a=Math.min(iee(),Sf);for(let c=0;c<r.length;c+=a){let A=Rf(t,e,i);await(await Kt({method:"PUT",url:A.toString(),body:Om(r.slice(c,c+a)),headers:i.headers,dispatcher:vE(n),timeoutMs:null,logLabel:A.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",onRequestDispatched:c===0?s:void 0,attributes:{...cu({runId:e,name:t,operation:"write_multi"}),...c===0?o:void 0},buildError:async(l)=>Tf("write",A,l,await l.text())})).text()}}async function bJe(e,t,r){let n=await Ye(r);n.headers.set("X-Stream-Done","true");let o=Rf(t,e,n);await(await Kt({method:"PUT",url:o.toString(),headers:n.headers,dispatcher:S0(r),timeoutMs:null,logLabel:o.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",attributes:cu({runId:e,name:t,operation:"close"}),buildError:async(i)=>Tf("close",o,i,await i.text())})).text()}function GD(e){return{streams:{..._m()&&!Un(e).usingProxy?{createWriteSession(t,r,{writerId:n}){return see(t,r,n,e,(o,s,i)=>SJe(t,r,o,e,s,i),()=>bJe(t,r,e))}}:{},async write(t,r,n){let o=await t,s=await Ye(e),i=Rf(r,o,s);await(await Kt({method:"PUT",url:i.toString(),body:n,headers:s.headers,dispatcher:vE(e),timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:i.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",attributes:cu({runId:o,name:r,operation:"write"}),buildError:async(c)=>Tf("write",i,c,await c.text())})).text()},async writeMulti(t,r,n){if(n.length===0)return;let o=await t,s=await Ye(e);s.headers.set("X-Stream-Multi","true");let i=iee();for(let a=0;a<n.length;a+=i){let c=n.slice(a,a+i),A=Om(c),u=Rf(r,o,s);await(await Kt({method:"PUT",url:u.toString(),body:A,headers:s.headers,dispatcher:vE(e),timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:u.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",attributes:cu({runId:o,name:r,operation:"write_multi"}),buildError:async(d)=>Tf("write",u,d,await d.text())})).text()}},async close(t,r){let n=await t,o=await Ye(e);o.headers.set("X-Stream-Done","true");let s=Rf(r,n,o);await(await Kt({method:"PUT",url:s.toString(),headers:o.headers,dispatcher:S0(e),timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:s.pathname,spanName:"workflow.stream.write",durationAttribute:"workflow.stream.write.chunk_rtt",attributes:cu({runId:n,name:r,operation:"close"}),buildError:async(a)=>Tf("close",s,a,await a.text())})).text()},async get(t,r,n){let o=await Ye(e);o.headers.set("Accept","application/json");let s=BJe(r,t,o);if(typeof n==="number")s.searchParams.set("startIndex",String(n));let i=await Kt({method:"GET",url:s.toString(),headers:o.headers,dispatcher:void 0,timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:s.pathname,spanName:"workflow.stream.read.connect",attributes:cu({runId:t,name:r,operation:"read",startIndex:n}),buildError:wJe});if(!i.body)throw new gt("No response body for stream",{url:s.toString()});return i.body},async getChunks(t,r,n){let o=new URLSearchParams;if(n?.limit!=null)o.set("limit",String(n.limit));if(n?.cursor)o.set("cursor",n.cursor);let s=o.toString(),i=`/v2/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(r)}/chunks${s?`?${s}`:""}`;try{return await Te({endpoint:i,config:e,schema:_Je})}catch(a){throw $D(`Failed to read stream chunks for ${r}`,a)}},async getInfo(t,r){let n=`/v2/runs/${encodeURIComponent(t)}/streams/${encodeURIComponent(r)}/info`;try{return await Te({endpoint:n,config:e,schema:QJe})}catch(o){throw $D(`Failed to read stream info for ${r}`,o)}},async list(t){let r=await Ye(e),n=new URL(`${r.baseUrl}/v2/runs/${encodeURIComponent(t)}/streams`),o=await Kt({method:"GET",url:n.toString(),headers:r.headers,dispatcher:void 0,timeoutMs:null,transportErrorCode:"STREAM_ERROR",logLabel:n.pathname,buildError:(s)=>new gt(`Failed to list streams: ${s.status}`,{url:n.toString(),status:s.status})});try{return await o.json()}catch(s){throw $D("Failed to parse stream list response",s)}}}}}Dr();bm();function aee(e){let t=e?.projectConfig?.projectId||process.env.VERCEL_PROJECT_ID,r=Al();return e={...e,mintedSpecVersion:r},{specVersion:r,capabilities:{hookRetention:{active:!0},maxConcurrency:!0,deploymentAffinity:!0,inBandFence:!0,hookForceClaim:!0,dynamicWorkflowCode:!0},validateRunExecutionContext:X0,getRuntimeDeadline:dm,...pD(e),...UD(e),analytics:process.env.WORKFLOW_DISABLE_ANALYTICS_READS==="1"?void 0:P0(e),...Ai("world.streams",GD(e)),createRunId:Y0,describeRun:q0,getEnvironment:()=>F0(e),uploadDynamicWorkflowCode:(n,o)=>J0(n,o,e),getEncryptionKeyForRun:Z0(t,e?.projectConfig?.teamId,e?.token,e?.dispatcher),resolveLatestDeploymentId:$6(e),telemetry:{recordStepExecution:L6}}}var DJe=Symbol.for("libfx.durability");function cee(e,t={}){let r=typeof e==="function";if(!r&&!(e&&typeof e==="object"))throw TypeError("world() takes a World or a function that creates one");if(!t||typeof t!=="object"||Array.isArray(t))throw TypeError("world() options must be an object");let{name:n="world",store:o=n,livenessKnown:s=!1,queueLeases:i=!1,runInRequest:a=i,waitUntil:c,queueDurable:A=!1,pollMs:u,leaseMs:l,maxDurationMs:d,reserveMs:f,alive:h,holderInfo:g,gatewayKey:p}=t;if(typeof n!=="string"||n.length===0)throw TypeError("world() name must be a non-empty string");if(typeof o!=="string"||o.length===0)throw TypeError(`${n}() store must be a non-empty string`);for(let[I,m]of Object.entries({livenessKnown:s,queueLeases:i,runInRequest:a,queueDurable:A}))if(typeof m!=="boolean")throw TypeError(`${n}() ${I} must be a boolean`);if(u!==void 0&&!(Number.isSafeInteger(u)&&u>0))throw TypeError(`${n}() pollMs must be a positive integer`);if(l!==void 0&&!(Number.isSafeInteger(l)&&l>=1000))throw TypeError(`${n}() leaseMs must be an integer of at least 1000`);for(let[I,m]of Object.entries({maxDurationMs:d,reserveMs:f}))if(m!==void 0&&!(Number.isSafeInteger(m)&&m>=0))throw TypeError(`${n}() ${I} must be a non-negative integer`);for(let[I,m]of Object.entries({alive:h,holderInfo:g,gatewayKey:p,waitUntil:c}))if(m!==void 0&&typeof m!=="function")throw TypeError(`${n}() ${I} must be a function`);if(s&&!h)throw TypeError(`${n}() livenessKnown needs alive()`);if(a&&!i)throw TypeError(`${n}() runInRequest needs queueLeases`);return{[DJe]:!0,name:n,store:o,world:r?e:()=>e,owned:r,livenessKnown:s,queueLeases:i,runInRequest:a,queueDurable:A,...u===void 0?{}:{pollMs:u},...l===void 0?{}:{leaseMs:l},...d===void 0?{}:{maxDurationMs:d},...f===void 0?{}:{reserveMs:f},...h===void 0?{}:{alive:h},...g===void 0?{}:{holderInfo:g},...p===void 0?{}:{gatewayKey:p},...c===void 0?{}:{waitUntil:c}}}function Cit({reserveMs:e,leaseMs:t}={}){return cee(()=>aee(),{name:"vercel",gatewayKey:()=>Aee.getVercelOidcToken(),livenessKnown:!1,queueLeases:t===void 0,waitUntil:(r)=>globalThis[Symbol.for("@vercel/request-context")]?.get?.()?.waitUntil?.(r),queueDurable:!0,pollMs:1000,reserveMs:e,leaseMs:t})}export{Cit as vercel};
|
package/durable/world.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var c=Symbol.for("libfx.durability");function T(r,f={}){let u=typeof r==="function";if(!u&&!(r&&typeof r==="object"))throw TypeError("world() takes a World or a function that creates one");if(!f||typeof f!=="object"||Array.isArray(f))throw TypeError("world() options must be an object");let{name:e="world",store:d=e,livenessKnown:l=!1,queueLeases:s=!1,runInRequest:w=s,waitUntil:y,queueDurable:h=!1,pollMs:t,leaseMs:o,maxDurationMs:b,reserveMs:p,alive:a,holderInfo:m,gatewayKey:g}=f;if(typeof e!=="string"||e.length===0)throw TypeError("world() name must be a non-empty string");if(typeof d!=="string"||d.length===0)throw TypeError(`${e}() store must be a non-empty string`);for(let[i,n]of Object.entries({livenessKnown:l,queueLeases:s,runInRequest:w,queueDurable:h}))if(typeof n!=="boolean")throw TypeError(`${e}() ${i} must be a boolean`);if(t!==void 0&&!(Number.isSafeInteger(t)&&t>0))throw TypeError(`${e}() pollMs must be a positive integer`);if(o!==void 0&&!(Number.isSafeInteger(o)&&o>=1000))throw TypeError(`${e}() leaseMs must be an integer of at least 1000`);for(let[i,n]of Object.entries({maxDurationMs:b,reserveMs:p}))if(n!==void 0&&!(Number.isSafeInteger(n)&&n>=0))throw TypeError(`${e}() ${i} must be a non-negative integer`);for(let[i,n]of Object.entries({alive:a,holderInfo:m,gatewayKey:g,waitUntil:y}))if(n!==void 0&&typeof n!=="function")throw TypeError(`${e}() ${i} must be a function`);if(l&&!a)throw TypeError(`${e}() livenessKnown needs alive()`);if(w&&!s)throw TypeError(`${e}() runInRequest needs queueLeases`);return{[c]:!0,name:e,store:d,world:u?r:()=>r,owned:u,livenessKnown:l,queueLeases:s,runInRequest:w,queueDurable:h,...t===void 0?{}:{pollMs:t},...o===void 0?{}:{leaseMs:o},...b===void 0?{}:{maxDurationMs:b},...p===void 0?{}:{reserveMs:p},...a===void 0?{}:{alive:a},...m===void 0?{}:{holderInfo:m},...g===void 0?{}:{gatewayKey:g},...y===void 0?{}:{waitUntil:y}}}export{T as world};
|