@lunora/queue 1.0.0-alpha.62 → 1.0.0-alpha.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -208,7 +208,25 @@ interface CapturedQueueMessage {
208
208
  attempts: number;
209
209
  /** The message body (JSON-encoded + capped by the catcher). */
210
210
  body: unknown;
211
- /** `true` when this failed delivery was the message's last (its retries are exhausted) AND the queue declares a `deadLetterQueue` for it to land in. Stays `false` for a queue with no DLQ, where the broker drops the exhausted message instead — `attempts > maxRetries` with `outcome !== "ack"` is what identifies that case. */
211
+ /**
212
+ * `true` when this failed delivery was the message's last (its retries are
213
+ * exhausted) AND the queue declares a `deadLetterQueue` for it to land in.
214
+ * Stays `false` for a queue with no DLQ, where the broker drops the
215
+ * exhausted message instead — `attempts > maxRetries` with
216
+ * `outcome !== "ack"` is what identifies that case.
217
+ *
218
+ * Read from the `defineQueue` DECLARATION, because a consumer has no
219
+ * runtime API that exposes its deployed `queues.consumers[]` settings. It is
220
+ * true of the deployed broker only as far as Lunora's binding reconcile (run
221
+ * by `lunora dev`, `deploy` and `prepare`) keeps the two in step: it writes
222
+ * every declared tuning field onto the consumer, including onto one that
223
+ * already exists. It does NOT remove a field taken out of `defineQueue` —
224
+ * dropping `deadLetterQueue` leaves the deployed DLQ in place, so this then
225
+ * reads `false` for messages that were in fact dead-lettered — and it never
226
+ * writes wrangler's `env.<name>` blocks, so a `--env` deploy uses whatever
227
+ * that block says. A bare `wrangler deploy` over a hand-edited consumer can
228
+ * disagree too, and nothing on this side can see any of it.
229
+ */
212
230
  deadLettered: boolean;
213
231
  /** Handler error message when `outcome` is `error`; absent otherwise. */
214
232
  error?: string;
package/dist/index.d.ts CHANGED
@@ -208,7 +208,25 @@ interface CapturedQueueMessage {
208
208
  attempts: number;
209
209
  /** The message body (JSON-encoded + capped by the catcher). */
210
210
  body: unknown;
211
- /** `true` when this failed delivery was the message's last (its retries are exhausted) AND the queue declares a `deadLetterQueue` for it to land in. Stays `false` for a queue with no DLQ, where the broker drops the exhausted message instead — `attempts > maxRetries` with `outcome !== "ack"` is what identifies that case. */
211
+ /**
212
+ * `true` when this failed delivery was the message's last (its retries are
213
+ * exhausted) AND the queue declares a `deadLetterQueue` for it to land in.
214
+ * Stays `false` for a queue with no DLQ, where the broker drops the
215
+ * exhausted message instead — `attempts > maxRetries` with
216
+ * `outcome !== "ack"` is what identifies that case.
217
+ *
218
+ * Read from the `defineQueue` DECLARATION, because a consumer has no
219
+ * runtime API that exposes its deployed `queues.consumers[]` settings. It is
220
+ * true of the deployed broker only as far as Lunora's binding reconcile (run
221
+ * by `lunora dev`, `deploy` and `prepare`) keeps the two in step: it writes
222
+ * every declared tuning field onto the consumer, including onto one that
223
+ * already exists. It does NOT remove a field taken out of `defineQueue` —
224
+ * dropping `deadLetterQueue` leaves the deployed DLQ in place, so this then
225
+ * reads `false` for messages that were in fact dead-lettered — and it never
226
+ * writes wrangler's `env.<name>` blocks, so a `--env` deploy uses whatever
227
+ * that block says. A bare `wrangler deploy` over a hand-edited consumer can
228
+ * disagree too, and nothing on this side can see any of it.
229
+ */
212
230
  deadLettered: boolean;
213
231
  /** Handler error message when `outcome` is `error`; absent otherwise. */
214
232
  error?: string;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{createQueueCaptureSink as t,shouldCaptureQueue as r}from"./packem_shared/createQueueCaptureSink-CSOPftvj.mjs";import{createQueueContext as a}from"./packem_shared/createQueueContext-BszRoc-a.mjs";import{default as i}from"./packem_shared/createQueues-CMitFS1K.mjs";import{defineQueue as p,isQueueDefinition as m,queueBindingName as x,queueDefaultName as Q}from"./packem_shared/defineQueue-TY4-i3nG.mjs";import{dispatchQueueBatch as s}from"./packem_shared/dispatchQueueBatch-DKAdSIjq.mjs";import{c as C}from"./packem_shared/run-context-D3vstU6K.mjs";export{t as createQueueCaptureSink,a as createQueueContext,C as createQueueRunContext,i as createQueues,p as defineQueue,s as dispatchQueueBatch,m as isQueueDefinition,x as queueBindingName,Q as queueDefaultName,r as shouldCaptureQueue};
1
+ import{createQueueCaptureSink as t,shouldCaptureQueue as r}from"./packem_shared/createQueueCaptureSink-CSOPftvj.mjs";import{createQueueContext as a}from"./packem_shared/createQueueContext-BszRoc-a.mjs";import{default as i}from"./packem_shared/createQueues-CMitFS1K.mjs";import{defineQueue as p,isQueueDefinition as m,queueBindingName as x,queueDefaultName as Q}from"./packem_shared/defineQueue-TY4-i3nG.mjs";import{dispatchQueueBatch as s}from"./packem_shared/dispatchQueueBatch-CgThRuXz.mjs";import{c as C}from"./packem_shared/run-context-DbF7bpEy.mjs";export{t as createQueueCaptureSink,a as createQueueContext,C as createQueueRunContext,i as createQueues,p as defineQueue,s as dispatchQueueBatch,m as isQueueDefinition,x as queueBindingName,Q as queueDefaultName,r as shouldCaptureQueue};
@@ -0,0 +1 @@
1
+ import{c as o}from"./run-context-DbF7bpEy.mjs";export{o as createQueueRunContext};
@@ -0,0 +1 @@
1
+ import{c as v,u as x,f as y,a as w,d as q,o as g}from"./run-context-DbF7bpEy.mjs";import{LunoraError as $,toErrorBody as k}from"@lunora/errors";const h=e=>typeof e.definition.maxRetries=="number"?e.definition.maxRetries:g,N=e=>{if(e instanceof Date)return e.getTime();const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:0},b=(e,r)=>{let t=0;return(i,n,s)=>(t+=1,e(i,n,{...s,dedupId:`${r}#${String(t)}`,messageId:r}))},R=(e,r,t)=>{const i=b(t,e.id);return new Proxy(e,{get:(n,s)=>s==="ack"?()=>{r.set(n,"ack"),n.ack()}:s==="retry"?u=>{r.set(n,"retry"),n.retry(u)}:s==="run"?i:Reflect.get(n,s,n)})},M=(e,r,t)=>new Proxy(e,{get:(i,n)=>n==="ackAll"?()=>{t("ack"),i.ackAll()}:n==="retryAll"?s=>{t("retry"),i.retryAll(s)}:n==="messages"?r:Reflect.get(i,n,i)}),A=(e,r)=>{const t=new Map,i=e.messages,n=i.map(o=>R(o,t,r)),u=M(e,n,o=>{for(const c of i)t.has(c)||t.set(c,o)});return{dispositions:t,originals:i,wrappedBatch:u}},B=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e!==null&&typeof e=="object")try{return JSON.stringify(e)}catch{return"[unserializable thrown value]"}return String(e)},I=(e,r,t,i,n,s)=>{const u=i?B(n):void 0,o=h(r),c=i?"error":"ack",f=typeof r.definition.deadLetterQueue=="string"&&r.definition.deadLetterQueue.length>0;return e.originals.map(d=>{const p=d===s,a=e.dispositions.get(d),l=p?"error":a??c,m=typeof d.attempts=="number"?d.attempts:1;return{attempts:m,body:d.body,deadLettered:f&&!p&&l!=="ack"&&m>o,error:l==="error"?u:void 0,exportName:r.exportName,messageId:d.id,outcome:l,queue:t,timestamp:N(d.timestamp)}})},T=(e,r,t)=>{if(!r||!y(t))return;const i=w(t);if(i===void 0)return;const n=e.originals.find(s=>s.id===i);if(!(n===void 0||e.dispositions.has(n)))return n},L=(e,r)=>{r.ack();for(const t of e.originals)t!==r&&!e.dispositions.has(t)&&(e.dispositions.set(t,"retry"),t.retry())},O=(e,r,t,i)=>{const n=w(r),s=e.originals.find(o=>o.id===n&&!e.dispositions.has(o)),u=`@lunora/queue: queue "${i}" (${t.exportName})`;for(const o of e.originals)if(!e.dispositions.has(o)){if(e.dispositions.set(o,"retry"),s!==void 0&&o!==s){o.retry();continue}q(o,{maxRetries:h(t),where:u})}},S=async(e,r,t)=>{const i=Object.hasOwn(r,e.queue)?r[e.queue]:void 0;if(i===void 0){const a=Object.keys(r),l=a.length===0?"no push queues are declared":`known push queues: ${a.join(", ")}`;throw new $("INTERNAL",`@lunora/queue: received a batch for queue "${e.queue}" but no push handler is registered (${l})`)}const{handler:n}=i.definition;if(typeof n!="function")throw new TypeError(`@lunora/queue: queue "${e.queue}" (${i.exportName}) has no push handler — it is declared as a pull consumer`);const s=v({env:t.env,exportName:i.exportName,fetchImpl:t.fetchImpl,...t.traceparent===void 0?{}:{traceparent:t.traceparent}}),u=A(e,s.run);let o=!1,c;try{await n(s,u.wrappedBatch)}catch(a){o=!0,c=a}const f=T(u,o,c);if(f!==void 0){L(u,f);const{body:a,status:l}=k(c,{redactedMessage:"internal error"});console.error(`@lunora/queue: dropped message ${f.id} on queue "${e.queue}" (${i.exportName}) — a dispatch it made failed with a deterministic ${String(l)} (${a.code}: ${a.message}), so it was acked, not retried. Its retries are NOT exhausted and it is not dead-lettered — it will never be redelivered.`)}const d=o&&x(c);d&&O(u,c,i,e.queue);const p=o&&f===void 0&&!d;if(t.capture!==void 0)try{await t.capture(I(u,i,e.queue,o,c,f))}catch(a){console.warn("@lunora/queue: capture sink failed (delivery unaffected):",a)}if(p)throw c};export{S as dispatchQueueBatch};
@@ -0,0 +1 @@
1
+ import{LunoraError as b,isLunoraError as j}from"@lunora/errors";const J=r=>({debug:(t,...o)=>{console.debug(r,t,...o)},error:(t,...o)=>{console.error(r,t,...o)},info:(t,...o)=>{console.info(r,t,...o)},warn:(t,...o)=>{console.warn(r,t,...o)}}),K=9e5,_="DISPATCH_IN_PROGRESS",q="x-lunora-dispatch-declined",H=(r,t,o)=>{if(t===void 0)return{dispose:()=>{},signal:r};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},t);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},A=r=>{let t="";for(let o=0;o<r.length;o+=32768)t+=String.fromCharCode(...r.subarray(o,o+32768));return btoa(t)},W=r=>{const t=atob(r),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",L=r=>{let t="",o=0;const a=r.length-2;for(;o<a;o+=3){const e=r[o]<<16|r[o+1]<<8|r[o+2];t+=p.charAt(e>>18&63)+p.charAt(e>>12&63)+p.charAt(e>>6&63)+p.charAt(e&63)}const n=r.length-o;if(n===1){const e=r[o]<<16;t+=p.charAt(e>>18&63)+p.charAt(e>>12&63)}else if(n===2){const e=r[o]<<16|r[o+1]<<8;t+=p.charAt(e>>18&63)+p.charAt(e>>12&63)+p.charAt(e>>6&63)}return t};new TextDecoder;const U=new TextEncoder,S="=",F=r=>{for(let t=0;t<r.length;t+=1)if(r.charCodeAt(t)>255)return!1;return!0},G=r=>L(U.encode(JSON.stringify(r))),Q=r=>!r.startsWith(S)&&F(r)?r:`${S}${L(U.encode(r))}`,u="$lunora.wire$",v=64,T=1024,E="__proto__",I={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},R={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},z=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},h=(r,t=0)=>{if(t>v)throw new RangeError(`wire-codec: value nesting exceeds the ${v}-level limit`);if(r===void 0)return[u,"undefined"];if(r===null)return null;const o=typeof r;if(o==="bigint")return[u,"bigint",r.toString()];if(o==="number"){const e=r;return Number.isNaN(e)?[u,"nan"]:e===1/0?[u,"inf"]:e===-1/0?[u,"-inf"]:e}if(o!=="object")return r;if(r instanceof Date)return[u,"date",h(r.getTime(),t+1)];if(r instanceof Error){const e=r,s={};for(const c of Object.keys(e)){if(e[c]===void 0)continue;const l=h(e[c],t+1);c===E?Object.defineProperty(s,c,{configurable:!0,enumerable:!0,value:l,writable:!0}):s[c]=l}const i=[u,"error",String(e.name),String(e.message),s];return e.cause!==void 0&&i.push(h(e.cause,t+1)),i}if(r instanceof URL)return[u,"url",r.href];if(r instanceof Map)return[u,"map",[...r.entries()].map(([e,s])=>[h(e,t+1),h(s,t+1)])];if(r instanceof Set)return[u,"set",[...r].map(e=>h(e,t+1))];if(r instanceof ArrayBuffer)return[u,"bytes",A(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,s=e.constructor.name,i=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return s==="Uint8Array"?[u,"bytes",A(i)]:[u,"bytes",A(i),s]}if(Array.isArray(r)){const e=r.map(s=>h(s,t+1));return e.length>0&&e[0]===u?[u,"arr",e]:e}if(!z(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=r,n={};for(const e of Object.keys(a)){const s=a[e];if(s===void 0)continue;const i=h(s,t+1);e===E?Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):n[e]=i}return n},f=(r,t=0)=>{if(t>v)throw new RangeError(`wire-codec: value nesting exceeds the ${v}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===u)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(n=>f(n,t+1));case"bigint":{const n=r[2];if(typeof n!="string"||n.length>T||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${T} digits)`);return BigInt(n)}case"date":{const n=f(r[2],t+1);if(typeof n!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(n)}case"map":{const n=r[2];return new Map(n.map(e=>{if(!Array.isArray(e)||e.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[f(e[0],t+1),f(e[1],t+1)]}))}case"set":return new Set(r[2].map(n=>f(n,t+1)));case"url":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(n)}case"error":{const n=r[2],e=r[3];if(typeof n!="string"||typeof e!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(R,n)?R[n]:void 0)??Error,i=new s(e);i.name!==n&&Object.defineProperty(i,"name",{configurable:!0,value:n,writable:!0});const c=f(r[4],t+1);if(c===null||typeof c!="object"||Array.isArray(c))throw new TypeError("wire-codec: malformed error — props must be an object");for(const l of Object.keys(c))l===E?Object.defineProperty(i,l,{configurable:!0,enumerable:!0,value:c[l],writable:!0}):i[l]=c[l];return r.length>5&&Object.defineProperty(i,"cause",{configurable:!0,value:f(r[5],t+1),writable:!0}),i}case"bytes":{const n=r[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const e=W(n);if(A(e)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=r[3]??"Uint8Array";if(s==="ArrayBuffer")return e.buffer.byteLength===e.byteLength?e.buffer:e.slice().buffer;const i=Object.hasOwn(I,s)?I[s]:void 0;return i?new i(e.slice().buffer):e}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(n=>f(n,t+1))}return r.map(n=>f(n,t+1))}const o=r,a={};for(const n of Object.keys(o)){const e=f(o[n],t+1);n===E?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:e,writable:!0}):a[n]=e}return a},V=(r,t,o)=>{try{return h(o)}catch(a){throw new TypeError(`${r}: cannot encode args for '${t}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},X="/_lunora/scheduler/dispatch",Y=3e4,Z=r=>{let t=r.length;for(;t>0&&r[t-1]==="/";)t-=1;return r.slice(0,t)},x=Symbol("lunoraDispatchFailure"),P=Symbol("lunoraDispatchDecline"),D=Symbol("lunoraDispatchMessageId"),k=(r,t)=>(t!==void 0&&Object.defineProperty(r,D,{value:t}),r),rr=(r,t)=>(Object.defineProperty(r,x,{value:!0}),k(r,t)),ur=r=>j(r)?r[D]:void 0,tr=(r,t,o,a)=>{const{status:n}=t;try{const e=JSON.parse(o)?.error;if(typeof e=="object"&&e!==null&&typeof e.code=="string"){const{code:s,data:i,message:c}=e,l=rr(new b(s,typeof c=="string"?c:void 0,{data:i,status:n}),a);return t.headers.get(q)==="1"&&Object.defineProperty(l,P,{value:!0}),l}}catch{}return k(new b("INTERNAL",`${r}: function dispatch failed (${String(n)}): ${o}`,{status:n}),a)},er=new Set([400,403,404,422]),nr=new Set([_,"DISPATCH_UNAUTHENTICATED"]),B=r=>j(r)&&r[x]===!0,lr=r=>B(r)&&er.has(r.status)&&!nr.has(r.code),fr=r=>B(r)&&r[P]===!0,or=K/1e3,ar=3,dr=(r,t)=>{const o=t.maxRetries??ar;r.retry({delaySeconds:or}),typeof r.attempts=="number"&&r.attempts>o&&console.error(`${t.where}: message ${r.id} was declined (${_}) on its last delivery (attempt ${String(r.attempts)} of ${String(o+1)}) — its earlier delivery is still running the call. It is retried anyway, but its retries are exhausted, so it will be dead-lettered if the queue has a deadLetterQueue and dropped if not. Raise max_retries so a slow call cannot exhaust it.`)},sr=(r,t,o)=>new b("INTERNAL",`${r}: function dispatch to "${t}" timed out after ${String(o)}ms`,{status:503}),ir=r=>{const{label:t}=r,o=globalThis.fetch,a=r.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,e,s={})=>{if(typeof a!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const i=()=>r.argsAlreadyEncoded===!0?e??{}:V(t,n.__lunoraRef,e??{}),c=r.env.LUNORA_ORIGIN_URL;if(typeof c!="string"||c.length===0)throw new b("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const l=r.env.LUNORA_ADMIN_TOKEN;if(typeof l!="string"||l.length===0)throw new b("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const C=`${Z(c)}${X}`,w={authorization:`Bearer ${l}`,"content-type":"application/json"};r.traceparent!==void 0&&r.traceparent.length>0&&(w.traceparent=r.traceparent),r.identity?.userId!==void 0&&(w["x-lunora-userid"]=Q(r.identity.userId)),r.identity?.claims!==void 0&&(w["x-lunora-identity"]=G(r.identity.claims));const N=s.timeoutMs??Y,$=H(void 0,N,()=>new DOMException(`dispatch timed out after ${String(N)}ms`,"TimeoutError")),O=y=>{throw y instanceof Error&&y.name==="TimeoutError"?sr(t,n.__lunoraRef,N):y};let d;try{try{d=await a(C,{body:JSON.stringify({args:i(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:w,method:"POST",signal:$.signal})}catch(m){return O(m)}if(!d.ok){let m;try{m=await d.text()}catch(M){return O(M)}throw tr(t,d,m,s.messageId)}let y;try{y=await d.text()}catch(m){return O(m)}if(y.length===0)return;let g;try{g=JSON.parse(y)}catch{throw new b("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(d.status)}): ${y}`,{status:d.status})}if(g===null||typeof g!="object"||Array.isArray(g)||!("result"in g))throw new b("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(d.status)}): ${y}`,{status:d.status});return f(g.result)}finally{$.dispose()}}},yr=r=>({env:r.env,log:J(`[queue:${r.exportName}]`),run:ir({env:r.env,fetchImpl:r.fetchImpl,label:"@lunora/queue",...r.traceparent===void 0?{}:{traceparent:r.traceparent}})});export{ur as a,yr as c,dr as d,lr as f,ar as o,fr as u};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/queue",
3
- "version": "1.0.0-alpha.62",
3
+ "version": "1.0.0-alpha.64",
4
4
  "description": "Cloudflare Queues for Lunora: defineQueue producers + consumers, the ctx.queues surface, and the generated queue() worker handler",
5
5
  "keywords": [
6
6
  "background-jobs",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@lunora/errors": "1.0.0-alpha.41",
48
- "@lunora/platform": "1.0.0-alpha.33"
48
+ "@lunora/platform": "1.0.0-alpha.35"
49
49
  },
50
50
  "engines": {
51
51
  "node": "^22.15.0 || >=24.11.0"
@@ -1 +0,0 @@
1
- import{c as o}from"./run-context-D3vstU6K.mjs";export{o as createQueueRunContext};
@@ -1 +0,0 @@
1
- import{c as w,e as h,r as v}from"./run-context-D3vstU6K.mjs";import{LunoraError as y,toErrorBody as x}from"@lunora/errors";const g=3,q=e=>{if(e instanceof Date)return e.getTime();const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:0},b=(e,r)=>{let t=0;return(n,i,o)=>(t+=1,e(n,i,{...o,dedupId:`${r}#${String(t)}`,messageId:r}))},k=(e,r,t)=>{const n=b(t,e.id);return new Proxy(e,{get:(i,o)=>o==="ack"?()=>{r.set(i,"ack"),i.ack()}:o==="retry"?u=>{r.set(i,"retry"),i.retry(u)}:o==="run"?n:Reflect.get(i,o,i)})},N=(e,r,t)=>new Proxy(e,{get:(n,i)=>i==="ackAll"?()=>{t("ack"),n.ackAll()}:i==="retryAll"?o=>{t("retry"),n.retryAll(o)}:i==="messages"?r:Reflect.get(n,i,n)}),$=(e,r)=>{const t=new Map,n=e.messages,i=n.map(a=>k(a,t,r)),u=N(e,i,a=>{for(const c of n)t.has(c)||t.set(c,a)});return{dispositions:t,originals:n,wrappedBatch:u}},R=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e!==null&&typeof e=="object")try{return JSON.stringify(e)}catch{return"[unserializable thrown value]"}return String(e)},A=(e,r,t,n,i,o)=>{const u=n?R(i):void 0,a=typeof r.definition.maxRetries=="number"?r.definition.maxRetries:g,c=n?"error":"ack",f=typeof r.definition.deadLetterQueue=="string"&&r.definition.deadLetterQueue.length>0;return e.originals.map(d=>{const s=d===o,l=e.dispositions.get(d),p=s?"error":l??c,m=typeof d.attempts=="number"?d.attempts:1;return{attempts:m,body:d.body,deadLettered:f&&!s&&p!=="ack"&&m>a,error:p==="error"?u:void 0,exportName:r.exportName,messageId:d.id,outcome:p,queue:t,timestamp:q(d.timestamp)}})},M=(e,r,t)=>{if(!r||!h(t))return;const n=v(t);if(n===void 0)return;const i=e.originals.find(o=>o.id===n);if(!(i===void 0||e.dispositions.has(i)))return i},T=(e,r)=>{r.ack();for(const t of e.originals)t!==r&&!e.dispositions.has(t)&&(e.dispositions.set(t,"retry"),t.retry())},L=async(e,r,t)=>{const n=Object.hasOwn(r,e.queue)?r[e.queue]:void 0;if(n===void 0){const s=Object.keys(r),l=s.length===0?"no push queues are declared":`known push queues: ${s.join(", ")}`;throw new y("INTERNAL",`@lunora/queue: received a batch for queue "${e.queue}" but no push handler is registered (${l})`)}const{handler:i}=n.definition;if(typeof i!="function")throw new TypeError(`@lunora/queue: queue "${e.queue}" (${n.exportName}) has no push handler — it is declared as a pull consumer`);const o=w({env:t.env,exportName:n.exportName,fetchImpl:t.fetchImpl,...t.traceparent===void 0?{}:{traceparent:t.traceparent}}),u=$(e,o.run);let a=!1,c;try{await i(o,u.wrappedBatch)}catch(s){a=!0,c=s}const f=M(u,a,c);if(f!==void 0){T(u,f);const{body:s,status:l}=x(c,{redactedMessage:"internal error"});console.error(`@lunora/queue: dropped message ${f.id} on queue "${e.queue}" (${n.exportName}) — a dispatch it made failed with a deterministic ${String(l)} (${s.code}: ${s.message}), so it was acked, not retried. Its retries are NOT exhausted and it is not dead-lettered — it will never be redelivered.`)}const d=a&&f===void 0;if(t.capture!==void 0)try{await t.capture(A(u,n,e.queue,a,c,f))}catch(s){console.warn("@lunora/queue: capture sink failed (delivery unaffected):",s)}if(d)throw c};export{L as dispatchQueueBatch};
@@ -1 +0,0 @@
1
- import{LunoraError as b,isLunoraError as j}from"@lunora/errors";const B=e=>({debug:(t,...o)=>{console.debug(e,t,...o)},error:(t,...o)=>{console.error(e,t,...o)},info:(t,...o)=>{console.info(e,t,...o)},warn:(t,...o)=>{console.warn(e,t,...o)}}),C=(e,t,o)=>{if(t===void 0)return{dispose:()=>{},signal:e};const a=new AbortController,n=setTimeout(()=>{a.abort(o())},t);return{dispose:()=>{clearTimeout(n)},signal:a.signal}},A=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},M=e=>{const t=atob(e),o=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)o[a]=t.codePointAt(a)??0;return o},p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",L=e=>{let t="",o=0;const a=e.length-2;for(;o<a;o+=3){const r=e[o]<<16|e[o+1]<<8|e[o+2];t+=p.charAt(r>>18&63)+p.charAt(r>>12&63)+p.charAt(r>>6&63)+p.charAt(r&63)}const n=e.length-o;if(n===1){const r=e[o]<<16;t+=p.charAt(r>>18&63)+p.charAt(r>>12&63)}else if(n===2){const r=e[o]<<16|e[o+1]<<8;t+=p.charAt(r>>18&63)+p.charAt(r>>12&63)+p.charAt(r>>6&63)}return t};new TextDecoder;const U=new TextEncoder,$="=",J=e=>{for(let t=0;t<e.length;t+=1)if(e.charCodeAt(t)>255)return!1;return!0},K=e=>L(U.encode(JSON.stringify(e))),F=e=>!e.startsWith($)&&J(e)?e:`${$}${L(U.encode(e))}`,u="$lunora.wire$",v=64,I=1024,E="__proto__",R={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},S={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},W=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},h=(e,t=0)=>{if(t>v)throw new RangeError(`wire-codec: value nesting exceeds the ${v}-level limit`);if(e===void 0)return[u,"undefined"];if(e===null)return null;const o=typeof e;if(o==="bigint")return[u,"bigint",e.toString()];if(o==="number"){const r=e;return Number.isNaN(r)?[u,"nan"]:r===1/0?[u,"inf"]:r===-1/0?[u,"-inf"]:r}if(o!=="object")return e;if(e instanceof Date)return[u,"date",h(e.getTime(),t+1)];if(e instanceof Error){const r=e,s={};for(const i of Object.keys(r)){if(r[i]===void 0)continue;const f=h(r[i],t+1);i===E?Object.defineProperty(s,i,{configurable:!0,enumerable:!0,value:f,writable:!0}):s[i]=f}const c=[u,"error",String(r.name),String(r.message),s];return r.cause!==void 0&&c.push(h(r.cause,t+1)),c}if(e instanceof URL)return[u,"url",e.href];if(e instanceof Map)return[u,"map",[...e.entries()].map(([r,s])=>[h(r,t+1),h(s,t+1)])];if(e instanceof Set)return[u,"set",[...e].map(r=>h(r,t+1))];if(e instanceof ArrayBuffer)return[u,"bytes",A(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,s=r.constructor.name,c=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return s==="Uint8Array"?[u,"bytes",A(c)]:[u,"bytes",A(c),s]}if(Array.isArray(e)){const r=e.map(s=>h(s,t+1));return r.length>0&&r[0]===u?[u,"arr",r]:r}if(!W(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const a=e,n={};for(const r of Object.keys(a)){const s=a[r];if(s===void 0)continue;const c=h(s,t+1);r===E?Object.defineProperty(n,r,{configurable:!0,enumerable:!0,value:c,writable:!0}):n[r]=c}return n},l=(e,t=0)=>{if(t>v)throw new RangeError(`wire-codec: value nesting exceeds the ${v}-level limit`);if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===u)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(n=>l(n,t+1));case"bigint":{const n=e[2];if(typeof n!="string"||n.length>I||!/^-?\d+$/.test(n))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${I} digits)`);return BigInt(n)}case"date":{const n=l(e[2],t+1);if(typeof n!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(n)}case"map":{const n=e[2];return new Map(n.map(r=>{if(!Array.isArray(r)||r.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[l(r[0],t+1),l(r[1],t+1)]}))}case"set":return new Set(e[2].map(n=>l(n,t+1)));case"url":{const n=e[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(n)}case"error":{const n=e[2],r=e[3];if(typeof n!="string"||typeof r!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(S,n)?S[n]:void 0)??Error,c=new s(r);c.name!==n&&Object.defineProperty(c,"name",{configurable:!0,value:n,writable:!0});const i=l(e[4],t+1);if(i===null||typeof i!="object"||Array.isArray(i))throw new TypeError("wire-codec: malformed error — props must be an object");for(const f of Object.keys(i))f===E?Object.defineProperty(c,f,{configurable:!0,enumerable:!0,value:i[f],writable:!0}):c[f]=i[f];return e.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:l(e[5],t+1),writable:!0}),c}case"bytes":{const n=e[2];if(typeof n!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const r=M(n);if(A(r)!==n)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return r.buffer.byteLength===r.byteLength?r.buffer:r.slice().buffer;const c=Object.hasOwn(R,s)?R[s]:void 0;return c?new c(r.slice().buffer):r}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(n=>l(n,t+1))}return e.map(n=>l(n,t+1))}const o=e,a={};for(const n of Object.keys(o)){const r=l(o[n],t+1);n===E?Object.defineProperty(a,n,{configurable:!0,enumerable:!0,value:r,writable:!0}):a[n]=r}return a},q=(e,t,o)=>{try{return h(o)}catch(a){throw new TypeError(`${e}: cannot encode args for '${t}' — ${a instanceof Error?a.message:String(a)}`,a instanceof Error?{cause:a}:void 0)}},G="/_lunora/scheduler/dispatch",H=3e4,z=e=>{let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)},_=Symbol("lunoraDispatchFailure"),x=Symbol("lunoraDispatchMessageId"),P=(e,t)=>(t!==void 0&&Object.defineProperty(e,x,{value:t}),e),Q=(e,t)=>(Object.defineProperty(e,_,{value:!0}),P(e,t)),re=e=>j(e)?e[x]:void 0,V=(e,t,o,a)=>{try{const n=JSON.parse(o)?.error;if(typeof n=="object"&&n!==null&&typeof n.code=="string"){const{code:r,data:s,message:c}=n;return Q(new b(r,typeof c=="string"?c:void 0,{data:s,status:t}),a)}}catch{}return P(new b("INTERNAL",`${e}: function dispatch failed (${String(t)}): ${o}`,{status:t}),a)},X=new Set([400,403,404,422]),Y=new Set(["DISPATCH_UNAUTHENTICATED"]),ne=e=>j(e)&&e[_]===!0&&X.has(e.status)&&!Y.has(e.code),Z=(e,t,o)=>new b("INTERNAL",`${e}: function dispatch to "${t}" timed out after ${String(o)}ms`,{status:503}),ee=e=>{const{label:t}=e,o=globalThis.fetch,a=e.fetchImpl??(typeof o=="function"?o.bind(globalThis):void 0);return async(n,r,s={})=>{if(typeof a!="function")throw new TypeError(`${t}: no fetch implementation available — pass fetchImpl or run on a platform with global fetch`);const c=()=>e.argsAlreadyEncoded===!0?r??{}:q(t,n.__lunoraRef,r??{}),i=e.env.LUNORA_ORIGIN_URL;if(typeof i!="string"||i.length===0)throw new b("INTERNAL",`${t}: \`LUNORA_ORIGIN_URL\` must be set on the Worker env so a handler can call back into Lunora functions`);const f=e.env.LUNORA_ADMIN_TOKEN;if(typeof f!="string"||f.length===0)throw new b("INTERNAL",`${t}: \`LUNORA_ADMIN_TOKEN\` must be set on the Worker env to authenticate function dispatch`);const D=`${z(i)}${G}`,m={authorization:`Bearer ${f}`,"content-type":"application/json"};e.traceparent!==void 0&&e.traceparent.length>0&&(m.traceparent=e.traceparent),e.identity?.userId!==void 0&&(m["x-lunora-userid"]=F(e.identity.userId)),e.identity?.claims!==void 0&&(m["x-lunora-identity"]=K(e.identity.claims));const N=s.timeoutMs??H,T=C(void 0,N,()=>new DOMException(`dispatch timed out after ${String(N)}ms`,"TimeoutError")),O=y=>{throw y instanceof Error&&y.name==="TimeoutError"?Z(t,n.__lunoraRef,N):y};let d;try{try{d=await a(D,{body:JSON.stringify({args:c(),functionPath:n.__lunoraRef,id:s.dedupId,shardKey:s.shardKey}),headers:m,method:"POST",signal:T.signal})}catch(w){return O(w)}if(!d.ok){let w;try{w=await d.text()}catch(k){return O(k)}throw V(t,d.status,w,s.messageId)}let y;try{y=await d.text()}catch(w){return O(w)}if(y.length===0)return;let g;try{g=JSON.parse(y)}catch{throw new b("INTERNAL",`${t}: function dispatch returned a non-JSON body (${String(d.status)}): ${y}`,{status:d.status})}if(g===null||typeof g!="object"||Array.isArray(g)||!("result"in g))throw new b("INTERNAL",`${t}: function dispatch returned a JSON body that is not a { result } envelope (${String(d.status)}): ${y}`,{status:d.status});return l(g.result)}finally{T.dispose()}}},oe=e=>({env:e.env,log:B(`[queue:${e.exportName}]`),run:ee({env:e.env,fetchImpl:e.fetchImpl,label:"@lunora/queue",...e.traceparent===void 0?{}:{traceparent:e.traceparent}})});export{oe as c,ne as e,re as r};