@void/platform 0.26.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- var Fr=Object.create;var Be=Object.defineProperty;var Hr=Object.getOwnPropertyDescriptor;var Br=Object.getOwnPropertyNames;var Gr=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var l=(e,t)=>Be(e,"name",{value:t,configurable:!0});var le=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Vr=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var qr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Br(t))!zr.call(e,s)&&s!==r&&Be(e,s,{get:()=>t[s],enumerable:!(n=Hr(t,s))||n.enumerable});return e};var Wr=(e,t,r)=>(r=e!=null?Fr(Gr(e)):{},qr(t||!e||!e.__esModule?Be(r,"default",{value:e,enumerable:!0}):r,e));function B(e){return new Error(`[unenv] ${e} is not implemented yet!`)}var Rt=le(()=>{g();l(B,"createNotImplementedError")});var Ge,ze,Xr,G,Ve,Y,J,ce,V,de,K,At=le(()=>{g();Rt();Ge=globalThis.performance?.timeOrigin??Date.now(),ze=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-Ge,Xr={name:"node",entryType:"node",startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},G=class{static{l(this,"PerformanceEntry")}__unenv__=!0;detail;entryType="event";name;startTime;constructor(t,r){this.name=t,this.startTime=r?.startTime||ze(),this.detail=r?.detail}get duration(){return ze()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},Ve=class extends G{static{l(this,"PerformanceMark")}entryType="mark";constructor(){super(...arguments)}get duration(){return 0}},Y=class extends G{static{l(this,"PerformanceMeasure")}entryType="measure"},J=class extends G{static{l(this,"PerformanceResourceTiming")}entryType="resource";serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType="";name="";nextHopProtocol="";redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},ce=class{static{l(this,"PerformanceObserverEntryList")}__unenv__=!0;getEntries(){return[]}getEntriesByName(t,r){return[]}getEntriesByType(t){return[]}},V=class{static{l(this,"Performance")}__unenv__=!0;timeOrigin=Ge;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(t,r){throw B("Performance.timerify")}get nodeTiming(){return Xr}eventLoopUtilization(){return{}}markResourceTiming(){return new J("")}onresourcetimingbufferfull=null;now(){return this.timeOrigin===Ge?ze():Date.now()-this.timeOrigin}clearMarks(t){this._entries=t?this._entries.filter(r=>r.name!==t):this._entries.filter(r=>r.entryType!=="mark")}clearMeasures(t){this._entries=t?this._entries.filter(r=>r.name!==t):this._entries.filter(r=>r.entryType!=="measure")}clearResourceTimings(){this._entries=this._entries.filter(t=>t.entryType!=="resource"||t.entryType!=="navigation")}getEntries(){return this._entries}getEntriesByName(t,r){return this._entries.filter(n=>n.name===t&&(!r||n.entryType===r))}getEntriesByType(t){return this._entries.filter(r=>r.entryType===t)}mark(t,r){let n=new Ve(t,r);return this._entries.push(n),n}measure(t,r,n){let s,o;typeof r=="string"?(s=this.getEntriesByName(r,"mark")[0]?.startTime,o=this.getEntriesByName(n,"mark")[0]?.startTime):(s=Number.parseFloat(r?.start)||this.now(),o=Number.parseFloat(r?.end)||this.now());let i=new Y(t,{startTime:s,detail:{start:s,end:o}});return this._entries.push(i),i}setResourceTimingBufferSize(t){this._resourceTimingBufferSize=t}addEventListener(t,r,n){throw B("Performance.addEventListener")}removeEventListener(t,r,n){throw B("Performance.removeEventListener")}dispatchEvent(t){throw B("Performance.dispatchEvent")}toJSON(){return this}},de=class{static{l(this,"PerformanceObserver")}__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(t){this._callback=t}takeRecords(){return[]}disconnect(){throw B("PerformanceObserver.disconnect")}observe(t){throw B("PerformanceObserver.observe")}bind(t){return t}runInAsyncScope(t,r,...n){return t.call(r,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},K=globalThis.performance&&"addEventListener"in globalThis.performance?globalThis.performance:new V});var _t=le(()=>{g();At()});var g=le(()=>{_t();if(!("__unenv__"in K)){let e=V.prototype;for(let t of Object.getOwnPropertyNames(e))if(t!=="constructor"&&!(t in K)){let r=Object.getOwnPropertyDescriptor(e,t);r&&Object.defineProperty(K,t,r)}}globalThis.performance=K;globalThis.Performance=V;globalThis.PerformanceEntry=G;globalThis.PerformanceMark=Ve;globalThis.PerformanceMeasure=Y;globalThis.PerformanceObserver=de;globalThis.PerformanceObserverEntryList=ce;globalThis.PerformanceResourceTiming=J});var kt=Vr(Nt=>{"use strict";g();var nn=/^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;Nt.validate=function(e){if(!e||e.length>254)return!1;var t=nn.test(e);if(!t)return!1;var r=e.split("@");if(r[0].length>64)return!1;var n=r[1].split(".");return!n.some(function(s){return s.length>63})}});g();g();var q=new TextEncoder,ue=new TextDecoder,Yr=5e3,fe=15e3,vt=15e3,Jr=65536;async function Kr(e,t){if(!t)throw new Error("Email signing key is not configured");let r=await crypto.subtle.importKey("raw",q.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,q.encode(e)));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}l(Kr,"sign");async function W(e,t,r,n=Yr){let s=new AbortController,o=Date.now()+n,i=l(async f=>{let y=o-Date.now();if(y<=0)throw s.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let h=f(),b;try{return await Promise.race([h,new Promise((R,E)=>{b=setTimeout(()=>{s.abort(),E(new Error("EMAIL_ADMISSION_TIMEOUT"))},y)})])}finally{b!==void 0&&clearTimeout(b)}},"beforeDeadline"),a=JSON.stringify(r),c=await Kr(a,e.EMAIL_SIGNING_SECRET),d=await i(()=>e.API.fetch(`https://api/internal/email/actions${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":c},body:a,signal:s.signal}));if(!d.ok)throw d.body?.cancel().catch(()=>{}),d.status===409?new Error("IDEMPOTENCY_CONFLICT"):new Error(`EMAIL_ADMISSION_${d.status}`);let u=d.body?.getReader();if(!u)throw new Error("EMAIL_ADMISSION_EMPTY_RESPONSE");let m=new Uint8Array(Jr),p=0;try{for(;;){let f=await i(()=>u.read());if(f.done)break;if(p+f.value.byteLength>m.length)throw new Error("EMAIL_ADMISSION_RESPONSE_TOO_LARGE");m.set(f.value,p),p+=f.value.byteLength}return JSON.parse(ue.decode(m.subarray(0,p)))}finally{u.cancel().catch(()=>{});try{u.releaseLock()}catch{}}}l(W,"call");function St(e,t){return W(e,"/receipts/claim",t)}l(St,"claimRelayedReceipt");function Mt(e,t,r){return W(e,"/receipts/complete",{receiptId:t.receiptId,projectId:t.projectId,payloadDigest:t.payloadDigest,reject:r})}l(Mt,"completeRelayedReceipt");function Qr(e){if(Zr(e)===-1)return e;let t=new Map,r=[],n=0,s=0,o=!1,i=!0,a=!0,c=l(f=>{f.byteLength!==0&&(r.push(f),n+=f.byteLength)},"append"),d=l((f,y,h)=>{c(e.subarray(s,f)),c(h),s=y,o=!0},"replace"),u=0;for(;u<e.byteLength;){let f=en(e,u),y=f===e.byteLength?e.byteLength:f+2;if(i){if(f===u)i=!1,a=!1;else if(a&&(me(e,u,f,"Date: ")||me(e,u,f,"Message-ID: ")))d(u,y,new Uint8Array);else if(tn(e,u,f)){let h=ue.decode(e.subarray(u,f)),b=h.replace(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(R,E)=>{let _=t.get(E);return _||(_=`<void-boundary-${t.size}>`,t.set(E,_)),`boundary="${_}"`});b!==h&&d(u,f,q.encode(b))}}else if(e[u]===45&&e[u+1]===45){let h=u+2,b=It(e,h,f)?ue.decode(e.subarray(h,f)):void 0,R=b===void 0?void 0:t.get(b);if(R!==void 0)d(u,f,q.encode(`--${R}`)),i=!0;else if(f-h>=2&&e[f-2]===45&&e[f-1]===45&&It(e,h,f-2)){let E=ue.decode(e.subarray(h,f-2)),_=t.get(E);_!==void 0&&d(u,f,q.encode(`--${_}--`))}}u=y}if(!o)return e;c(e.subarray(s));let m=new Uint8Array(n),p=0;for(let f of r)m.set(f,p),p+=f.byteLength;return m}l(Qr,"canonicalizeVoidMime");function Zr(e){for(let t=0;t+3<e.byteLength;t++)if(e[t]===13&&e[t+1]===10&&e[t+2]===13&&e[t+3]===10)return t;return-1}l(Zr,"findCrlfCrlf");function en(e,t){let r=t;for(;r<e.byteLength;){let n=e.indexOf(13,r);if(n===-1)return e.byteLength;if(e[n+1]===10)return n;r=n+1}return e.byteLength}l(en,"findCrlf");function me(e,t,r,n){if(r-t<n.length)return!1;for(let s=0;s<n.length;s++){let o=e[t+s],i=n.charCodeAt(s);if((o>=65&&o<=90?o+32:o)!==(i|32))return!1}return!0}l(me,"asciiPrefixEquals");function tn(e,t,r){let n="Content-Type:";if(!me(e,t,r,n))return!1;let s=t+n.length;for(;s<r&&(e[s]===32||e[s]===9||e[s]===11||e[s]===12);)s++;return me(e,s,r,"multipart/")}l(tn,"isMultipartContentType");function It(e,t,r){if(r<=t)return!1;for(let n=t;n<r;n++){let s=e[n];if(!(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===95||s===45||s===61))return!1}return!0}l(It,"isBoundaryToken");async function Q(e,t,r,n){let s=Qr(n),o=q.encode(JSON.stringify({kind:e,from:t.toLowerCase(),recipients:[...new Set(r.map(a=>a.toLowerCase()))].sort()})),i=new Uint8Array(o.length+1+s.length);return i.set(o),i[o.length]=0,i.set(s,o.length+1),[...new Uint8Array(await crypto.subtle.digest("SHA-256",i))].map(a=>a.toString(16).padStart(2,"0")).join("")}l(Q,"emailPayloadDigest");function Z(e,t,r=vt){return W(e,"/admit",t,Math.min(r,vt))}l(Z,"admitEmail");function ee(e,t,r,n=fe){return W(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Math.min(n,fe))}l(ee,"startEmailAttempt");function O(e,t,r,n,s={},o=fe){return W(e,`/${encodeURIComponent(t)}/finish`,{recipients:r,state:n,...s},Math.min(o,fe))}l(O,"finishEmailAttempt");function z(e,t,r,n,s){return W(e,"/receipts",{receiptId:t,projectId:r,status:n,...s?{route:s}:{}})}l(z,"recordEmailReceipt");g();g();var rn=new Set(["abuse","bounce","noreply","postmaster","security"]);function Tt(e){return rn.has(e)}l(Tt,"isReservedEmailSlug");var Tr=Wr(kt(),1);import{EmailMessage as Mr}from"cloudflare:email";g();g();var xt="/__void/email/receipt/v1";var qe=new TextEncoder,sn=new TextDecoder("utf-8",{fatal:!0});function on(e,t,r){let n=0,s=0,o=!1,i=!1;for(let a of e)if(o)i?i=!1:a===92?i=!0:a===34&&(o=!1);else if(a===34)o=!0;else if(a===123||a===91){if(++n>t)throw new Error("email metadata too deep")}else if(a===125||a===93){if(--n<0)throw new Error("invalid email metadata")}else if(a===58&&++s>r)throw new Error("too many email metadata fields");if(o||n!==0)throw new Error("invalid email metadata")}l(on,"assertFlatJson");function Pt(e){let t=qe.encode(JSON.stringify({from:e.from,to:e.to,headers:e.headers,rawSize:e.rawSize,...e.viaDomain?{viaDomain:e.viaDomain}:{}}));if(t.byteLength>131072||e.raw.byteLength>10485760)throw new Error("email envelope too large");let r=new Uint8Array(4+t.byteLength+e.raw.byteLength);return new DataView(r.buffer).setUint32(0,t.byteLength),r.set(t,4),r.set(e.raw,4+t.byteLength),r}l(Pt,"encodeEmailEnvelope");function Ot(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}l(Ot,"base64url");async function an(e,t){if(!e)throw new Error("Email signing key is not configured");return crypto.subtle.importKey("raw",qe.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t])}l(an,"receiptKey");async function Lt(e,t){let r=qe.encode(JSON.stringify(e)),n=new Uint8Array(await crypto.subtle.sign("HMAC",await an(t,"sign"),r));return`${Ot(r)}.${Ot(n)}`}l(Lt,"signEmailReceipt");async function Dt(e,t=15e3){let r=e.getReader(),n=[],s=new Uint8Array(0),o=0,i=Date.now()+t;async function a(){let d=i-Date.now();if(d<=0)throw new Error("email response timeout");let u;return Promise.race([r.read(),new Promise((m,p)=>{u=setTimeout(()=>p(new Error("email response timeout")),d)})]).finally(()=>{u!==void 0&&clearTimeout(u)})}l(a,"readChunk");async function c(d){let u=new Uint8Array(d),m=0;for(;m<d;){if(s.byteLength===0){let f=await a();if(f.done)throw new Error("truncated email response");if(o+=f.value.byteLength,o>8388608)throw new Error("email response too large");s=f.value}let p=Math.min(s.byteLength,d-m);u.set(s.subarray(0,p),m),s=s.subarray(p),m+=p}return u}l(c,"exact");try{for(;;){let d=await c(5),u=new DataView(d.buffer).getUint32(0),m=d[4];if(m===0){if(u!==0||s.byteLength!==0)throw new Error("invalid email response tail");if(!(await a()).done)throw new Error("invalid email response tail");if(n.some(h=>h.type==="reject")&&n.length!==1)throw new Error("email reject cannot accompany delivery actions");return n}if(m!==1||u>8192||n.length>=100)throw new Error("invalid email action frame");let p=await c(u);on(p,2,40);let f=JSON.parse(sn.decode(p));if(!f||typeof f!="object"||Array.isArray(f))throw new Error("invalid email action");let y=f;if(y.type==="reply"){if(typeof y.from!="string"||typeof y.to!="string"||Object.keys(y).length!==3)throw new Error("invalid email reply");let h=await c(5),b=new DataView(h.buffer).getUint32(0);if(h[4]!==2||b>5242880)throw new Error("invalid email reply frame");n.push({type:"reply",from:y.from,to:y.to,raw:await c(b)})}else if(y.type==="forward"){if(typeof y.to!="string"||Object.keys(y).length>3||y.headers!==void 0&&(typeof y.headers!="object"||y.headers===null||Array.isArray(y.headers)))throw new Error("invalid email forward");let h=y.headers;if(h&&(Object.keys(h).length>32||Object.values(h).some(b=>typeof b!="string")))throw new Error("invalid email headers");n.push({type:"forward",to:y.to,...h?{headers:h}:{}})}else if(y.type==="reject"){if(typeof y.reason!="string"||Object.keys(y).length!==2)throw new Error("invalid email reject");n.push({type:"reject",reason:y.reason})}else throw new Error("unknown email action")}}catch(d){throw r.cancel().catch(()=>{}),d}finally{try{r.releaseLock()}catch{}}}l(Dt,"readEmailActions");var ln=8,cn=2e4,dn=15e3,te=new Map;async function We(e,t,r){if(!r.deploymentId||!r.projectId)throw new Error("email deployment identity missing");let n=r.receiptId;if(!/^[a-f0-9-]{16,64}$/.test(n))throw new Error("invalid email receipt ID");let s=te.get(r.projectId)??0;if(s>=ln)throw new Error("email project concurrency exceeded");te.set(r.projectId,s+1);let o=Date.now()+cn,i=new AbortController,a;try{let c=await Lt({version:1,receiptId:n,projectId:r.projectId,deploymentId:r.deploymentId,recipient:r.envelope.to,expiresAt:Date.now()+3e4},t.EMAIL_SIGNING_SECRET),d=o-Date.now();if(d<=0)throw new Error("email tenant request timeout");let u;try{a=await Promise.race([e.fetch(`https://worker${xt}`,{method:"POST",headers:{"content-type":"application/vnd.void.email-envelope; version=1","x-void-email-receipt":c,"x-void-email-recipient":r.envelope.to},body:Pt(r.envelope),signal:i.signal}),new Promise((f,y)=>{u=setTimeout(()=>{i.abort(),y(new Error("email tenant request timeout"))},d)})])}finally{u!==void 0&&clearTimeout(u)}if(!a.ok||a.headers.get("content-encoding")||a.headers.get("content-type")!==`application/vnd.void.email-actions; version=${1}`||!a.body)throw new Error(`invalid email tenant response (${a.status})`);let m=Math.min(dn,o-Date.now());if(m<=0)throw new Error("email tenant request timeout");return{actions:await Dt(a.body,m),receiptId:n}}finally{i.abort(),a?.body?.cancel().catch(()=>{});let c=(te.get(r.projectId)??1)-1;c===0?te.delete(r.projectId):te.set(r.projectId,c)}}l(We,"dispatchBoundedEmailToTenant");g();function ge(e){return e.token}l(ge,"leaseBearer");async function ye(e,t,r,n=5e3){if(!e.EMAIL_SIGNING_SECRET)return null;let s=new AbortController,o=Date.now()+Math.min(n,5e3),i=l(async p=>{let f=o-Date.now();if(f<=0)throw s.abort(),new Error("email credential lease timed out");let y=p(),h;try{return await Promise.race([y,new Promise((b,R)=>{h=setTimeout(()=>{s.abort(),R(new Error("email credential lease timed out"))},f)})])}finally{h!==void 0&&clearTimeout(h)}},"beforeDeadline"),a;try{let p=await mn(`email-lease-v1
1
+ var Vr=Object.create;var He=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Wr=Object.getOwnPropertyNames;var Xr=Object.getPrototypeOf,Jr=Object.prototype.hasOwnProperty;var c=(e,t)=>He(e,"name",{value:t,configurable:!0});var oe=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Yr=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Kr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Wr(t))!Jr.call(e,s)&&s!==r&&He(e,s,{get:()=>t[s],enumerable:!(n=qr(t,s))||n.enumerable});return e};var Qr=(e,t,r)=>(r=e!=null?Vr(Xr(e)):{},Kr(t||!e||!e.__esModule?He(r,"default",{value:e,enumerable:!0}):r,e));function H(e){return new Error(`[unenv] ${e} is not implemented yet!`)}var _t=oe(()=>{g();c(H,"createNotImplementedError")});var Be,Ge,Zr,B,ze,X,J,ae,V,ce,Y,vt=oe(()=>{g();_t();Be=globalThis.performance?.timeOrigin??Date.now(),Ge=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-Be,Zr={name:"node",entryType:"node",startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},B=class{static{c(this,"PerformanceEntry")}__unenv__=!0;detail;entryType="event";name;startTime;constructor(t,r){this.name=t,this.startTime=r?.startTime||Ge(),this.detail=r?.detail}get duration(){return Ge()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},ze=class extends B{static{c(this,"PerformanceMark")}entryType="mark";constructor(){super(...arguments)}get duration(){return 0}},X=class extends B{static{c(this,"PerformanceMeasure")}entryType="measure"},J=class extends B{static{c(this,"PerformanceResourceTiming")}entryType="resource";serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType="";name="";nextHopProtocol="";redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},ae=class{static{c(this,"PerformanceObserverEntryList")}__unenv__=!0;getEntries(){return[]}getEntriesByName(t,r){return[]}getEntriesByType(t){return[]}},V=class{static{c(this,"Performance")}__unenv__=!0;timeOrigin=Be;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(t,r){throw H("Performance.timerify")}get nodeTiming(){return Zr}eventLoopUtilization(){return{}}markResourceTiming(){return new J("")}onresourcetimingbufferfull=null;now(){return this.timeOrigin===Be?Ge():Date.now()-this.timeOrigin}clearMarks(t){this._entries=t?this._entries.filter(r=>r.name!==t):this._entries.filter(r=>r.entryType!=="mark")}clearMeasures(t){this._entries=t?this._entries.filter(r=>r.name!==t):this._entries.filter(r=>r.entryType!=="measure")}clearResourceTimings(){this._entries=this._entries.filter(t=>t.entryType!=="resource"||t.entryType!=="navigation")}getEntries(){return this._entries}getEntriesByName(t,r){return this._entries.filter(n=>n.name===t&&(!r||n.entryType===r))}getEntriesByType(t){return this._entries.filter(r=>r.entryType===t)}mark(t,r){let n=new ze(t,r);return this._entries.push(n),n}measure(t,r,n){let s,o;typeof r=="string"?(s=this.getEntriesByName(r,"mark")[0]?.startTime,o=this.getEntriesByName(n,"mark")[0]?.startTime):(s=Number.parseFloat(r?.start)||this.now(),o=Number.parseFloat(r?.end)||this.now());let i=new X(t,{startTime:s,detail:{start:s,end:o}});return this._entries.push(i),i}setResourceTimingBufferSize(t){this._resourceTimingBufferSize=t}addEventListener(t,r,n){throw H("Performance.addEventListener")}removeEventListener(t,r,n){throw H("Performance.removeEventListener")}dispatchEvent(t){throw H("Performance.dispatchEvent")}toJSON(){return this}},ce=class{static{c(this,"PerformanceObserver")}__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(t){this._callback=t}takeRecords(){return[]}disconnect(){throw H("PerformanceObserver.disconnect")}observe(t){throw H("PerformanceObserver.observe")}bind(t){return t}runInAsyncScope(t,r,...n){return t.call(r,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},Y=globalThis.performance&&"addEventListener"in globalThis.performance?globalThis.performance:new V});var It=oe(()=>{g();vt()});var g=oe(()=>{It();if(!("__unenv__"in Y)){let e=V.prototype;for(let t of Object.getOwnPropertyNames(e))if(t!=="constructor"&&!(t in Y)){let r=Object.getOwnPropertyDescriptor(e,t);r&&Object.defineProperty(Y,t,r)}}globalThis.performance=Y;globalThis.Performance=V;globalThis.PerformanceEntry=B;globalThis.PerformanceMark=ze;globalThis.PerformanceMeasure=X;globalThis.PerformanceObserver=ce;globalThis.PerformanceObserverEntryList=ae;globalThis.PerformanceResourceTiming=J});var Lt=Yr(Pt=>{"use strict";g();var dn=/^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;Pt.validate=function(e){if(!e||e.length>254)return!1;var t=dn.test(e);if(!t)return!1;var r=e.split("@");if(r[0].length>64)return!1;var n=r[1].split(".");return!n.some(function(s){return s.length>63})}});g();g();g();var Mt=new TextEncoder,le,St;async function en(e){return le&&St===e||(le=await crypto.subtle.importKey("raw",Mt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),St=e),le}c(en,"getSignKey");async function de(e,t){let r=await en(t),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,Mt.encode(e)));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(de,"hmacSign");var ue=new TextEncoder,fe=new TextDecoder,tn=5e3,me=15e3,Tt=15e3,rn=65536;async function nn(e,t){if(!t)throw new Error("Email signing key is not configured");return de(e,t)}c(nn,"sign");async function q(e,t,r,n=tn){let s=new AbortController,o=Date.now()+n,i=c(async f=>{let h=o-Date.now();if(h<=0)throw s.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let y=f(),w;try{return await Promise.race([y,new Promise((R,E)=>{w=setTimeout(()=>{s.abort(),E(new Error("EMAIL_ADMISSION_TIMEOUT"))},h)})])}finally{w!==void 0&&clearTimeout(w)}},"beforeDeadline"),a=JSON.stringify(r),l=await nn(a,e.EMAIL_SIGNING_SECRET),d=await i(()=>e.API.fetch(`https://api/internal/email/actions${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":l},body:a,signal:s.signal}));if(!d.ok)throw d.body?.cancel().catch(()=>{}),d.status===409?new Error("IDEMPOTENCY_CONFLICT"):new Error(`EMAIL_ADMISSION_${d.status}`);let u=d.body?.getReader();if(!u)throw new Error("EMAIL_ADMISSION_EMPTY_RESPONSE");let m=new Uint8Array(rn),p=0;try{for(;;){let f=await i(()=>u.read());if(f.done)break;if(p+f.value.byteLength>m.length)throw new Error("EMAIL_ADMISSION_RESPONSE_TOO_LARGE");m.set(f.value,p),p+=f.value.byteLength}return JSON.parse(fe.decode(m.subarray(0,p)))}finally{u.cancel().catch(()=>{});try{u.releaseLock()}catch{}}}c(q,"call");function xt(e,t){return q(e,"/receipts/claim",t)}c(xt,"claimRelayedReceipt");function Ot(e,t,r){return q(e,"/receipts/complete",{receiptId:t.receiptId,projectId:t.projectId,payloadDigest:t.payloadDigest,reject:r})}c(Ot,"completeRelayedReceipt");function sn(e){if(on(e)===-1)return e;let t=new Map,r=[],n=0,s=0,o=!1,i=!0,a=!0,l=c(f=>{f.byteLength!==0&&(r.push(f),n+=f.byteLength)},"append"),d=c((f,h,y)=>{l(e.subarray(s,f)),l(y),s=h,o=!0},"replace"),u=0;for(;u<e.byteLength;){let f=an(e,u),h=f===e.byteLength?e.byteLength:f+2;if(i){if(f===u)i=!1,a=!1;else if(a&&(pe(e,u,f,"Date: ")||pe(e,u,f,"Message-ID: ")))d(u,h,new Uint8Array);else if(cn(e,u,f)){let y=fe.decode(e.subarray(u,f)),w=y.replace(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(R,E)=>{let A=t.get(E);return A||(A=`<void-boundary-${t.size}>`,t.set(E,A)),`boundary="${A}"`});w!==y&&d(u,f,ue.encode(w))}}else if(e[u]===45&&e[u+1]===45){let y=u+2,w=Nt(e,y,f)?fe.decode(e.subarray(y,f)):void 0,R=w===void 0?void 0:t.get(w);if(R!==void 0)d(u,f,ue.encode(`--${R}`)),i=!0;else if(f-y>=2&&e[f-2]===45&&e[f-1]===45&&Nt(e,y,f-2)){let E=fe.decode(e.subarray(y,f-2)),A=t.get(E);A!==void 0&&d(u,f,ue.encode(`--${A}--`))}}u=h}if(!o)return e;l(e.subarray(s));let m=new Uint8Array(n),p=0;for(let f of r)m.set(f,p),p+=f.byteLength;return m}c(sn,"canonicalizeVoidMime");function on(e){for(let t=0;t+3<e.byteLength;t++)if(e[t]===13&&e[t+1]===10&&e[t+2]===13&&e[t+3]===10)return t;return-1}c(on,"findCrlfCrlf");function an(e,t){let r=t;for(;r<e.byteLength;){let n=e.indexOf(13,r);if(n===-1)return e.byteLength;if(e[n+1]===10)return n;r=n+1}return e.byteLength}c(an,"findCrlf");function pe(e,t,r,n){if(r-t<n.length)return!1;for(let s=0;s<n.length;s++){let o=e[t+s],i=n.charCodeAt(s);if((o>=65&&o<=90?o+32:o)!==(i|32))return!1}return!0}c(pe,"asciiPrefixEquals");function cn(e,t,r){let n="Content-Type:";if(!pe(e,t,r,n))return!1;let s=t+n.length;for(;s<r&&(e[s]===32||e[s]===9||e[s]===11||e[s]===12);)s++;return pe(e,s,r,"multipart/")}c(cn,"isMultipartContentType");function Nt(e,t,r){if(r<=t)return!1;for(let n=t;n<r;n++){let s=e[n];if(!(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===95||s===45||s===61))return!1}return!0}c(Nt,"isBoundaryToken");async function ge(e,t,r,n){let s=sn(n),o=ue.encode(JSON.stringify({kind:e,from:t.toLowerCase(),recipients:[...new Set(r.map(a=>a.toLowerCase()))].sort()})),i=new Uint8Array(o.length+1+s.length);return i.set(o),i[o.length]=0,i.set(s,o.length+1),[...new Uint8Array(await crypto.subtle.digest("SHA-256",i))].map(a=>a.toString(16).padStart(2,"0")).join("")}c(ge,"emailPayloadDigest");function he(e,t,r=Tt){return q(e,"/admit",t,Math.min(r,Tt))}c(he,"admitEmail");function K(e,t,r,n=me){return q(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Math.min(n,me))}c(K,"startEmailAttempt");function k(e,t,r,n,s={},o=me){return q(e,`/${encodeURIComponent(t)}/finish`,{recipients:r,state:n,...s},Math.min(o,me))}c(k,"finishEmailAttempt");function G(e,t,r,n,s){return q(e,"/receipts",{receiptId:t,projectId:r,status:n,...s?{route:s}:{}})}c(G,"recordEmailReceipt");g();g();var ln=new Set(["abuse","bounce","noreply","postmaster","security"]);function kt(e){return ln.has(e)}c(kt,"isReservedEmailSlug");var Lr=Qr(Lt(),1);import{EmailMessage as Pr}from"cloudflare:email";g();g();var Ct="/__void/email/receipt/v1";var Ve=new TextEncoder,un=new TextDecoder("utf-8",{fatal:!0});function fn(e,t,r){let n=0,s=0,o=!1,i=!1;for(let a of e)if(o)i?i=!1:a===92?i=!0:a===34&&(o=!1);else if(a===34)o=!0;else if(a===123||a===91){if(++n>t)throw new Error("email metadata too deep")}else if(a===125||a===93){if(--n<0)throw new Error("invalid email metadata")}else if(a===58&&++s>r)throw new Error("too many email metadata fields");if(o||n!==0)throw new Error("invalid email metadata")}c(fn,"assertFlatJson");function jt(e){let t=Ve.encode(JSON.stringify({from:e.from,to:e.to,headers:e.headers,rawSize:e.rawSize,...e.viaDomain?{viaDomain:e.viaDomain}:{}}));if(t.byteLength>131072||e.raw.byteLength>10485760)throw new Error("email envelope too large");let r=new Uint8Array(4+t.byteLength+e.raw.byteLength);return new DataView(r.buffer).setUint32(0,t.byteLength),r.set(t,4),r.set(e.raw,4+t.byteLength),r}c(jt,"encodeEmailEnvelope");function Dt(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}c(Dt,"base64url");async function mn(e,t){if(!e)throw new Error("Email signing key is not configured");return crypto.subtle.importKey("raw",Ve.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t])}c(mn,"receiptKey");async function $t(e,t){let r=Ve.encode(JSON.stringify(e)),n=new Uint8Array(await crypto.subtle.sign("HMAC",await mn(t,"sign"),r));return`${Dt(r)}.${Dt(n)}`}c($t,"signEmailReceipt");async function Ut(e,t=15e3){return gn(e,async r=>{let n=[],s=new Uint8Array(0),o=0,i=Date.now()+t,a=c(()=>pn(r,i,"email response timeout"),"readChunk");async function l(d){let u=new Uint8Array(d),m=0;for(;m<d;){if(s.byteLength===0){let f=await a();if(f.done)throw new Error("truncated email response");if(o+=f.value.byteLength,o>8388608)throw new Error("email response too large");s=f.value}let p=Math.min(s.byteLength,d-m);u.set(s.subarray(0,p),m),s=s.subarray(p),m+=p}return u}for(c(l,"exact");;){let d=await l(5),u=new DataView(d.buffer).getUint32(0),m=d[4];if(m===0){if(u!==0||s.byteLength!==0)throw new Error("invalid email response tail");if(!(await a()).done)throw new Error("invalid email response tail");if(n.some(y=>y.type==="reject")&&n.length!==1)throw new Error("email reject cannot accompany delivery actions");return n}if(m!==1||u>8192||n.length>=100)throw new Error("invalid email action frame");let p=await l(u);fn(p,2,40);let f=JSON.parse(un.decode(p));if(!f||typeof f!="object"||Array.isArray(f))throw new Error("invalid email action");let h=f;if(h.type==="reply"){if(typeof h.from!="string"||typeof h.to!="string"||Object.keys(h).length!==3)throw new Error("invalid email reply");let y=await l(5),w=new DataView(y.buffer).getUint32(0);if(y[4]!==2||w>5242880)throw new Error("invalid email reply frame");n.push({type:"reply",from:h.from,to:h.to,raw:await l(w)})}else if(h.type==="forward"){if(typeof h.to!="string"||Object.keys(h).length>3||h.headers!==void 0&&(typeof h.headers!="object"||h.headers===null||Array.isArray(h.headers)))throw new Error("invalid email forward");let y=h.headers;if(y&&(Object.keys(y).length>32||Object.values(y).some(w=>typeof w!="string")))throw new Error("invalid email headers");n.push({type:"forward",to:h.to,...y?{headers:y}:{}})}else if(h.type==="reject"){if(typeof h.reason!="string"||Object.keys(h).length!==2)throw new Error("invalid email reject");n.push({type:"reject",reason:h.reason})}else throw new Error("unknown email action")}})}c(Ut,"readEmailActions");async function pn(e,t,r){let n=t-Date.now();if(n<=0)throw new Error(r);let s;return Promise.race([e.read(),new Promise((o,i)=>{s=setTimeout(()=>i(new Error(r)),n)})]).finally(()=>{s!==void 0&&clearTimeout(s)})}c(pn,"readBeforeDeadline");async function gn(e,t){let r=e.getReader();try{return await t(r)}catch(n){throw r.cancel().catch(()=>{}),n}finally{try{r.releaseLock()}catch{}}}c(gn,"withReader");var hn=8,yn=2e4,wn=15e3,Q=new Map;async function qe(e,t,r){if(!r.deploymentId||!r.projectId)throw new Error("email deployment identity missing");let n=r.receiptId;if(!/^[a-f0-9-]{16,64}$/.test(n))throw new Error("invalid email receipt ID");let s=Q.get(r.projectId)??0;if(s>=hn)throw new Error("email project concurrency exceeded");Q.set(r.projectId,s+1);let o=Date.now()+yn,i=new AbortController,a;try{let l=await $t({version:1,receiptId:n,projectId:r.projectId,deploymentId:r.deploymentId,recipient:r.envelope.to,expiresAt:Date.now()+3e4},t.EMAIL_SIGNING_SECRET),d=o-Date.now();if(d<=0)throw new Error("email tenant request timeout");let u;try{a=await Promise.race([e.fetch(`https://worker${Ct}`,{method:"POST",headers:{"content-type":"application/vnd.void.email-envelope; version=1","x-void-email-receipt":l,"x-void-email-recipient":r.envelope.to},body:jt(r.envelope),signal:i.signal}),new Promise((f,h)=>{u=setTimeout(()=>{i.abort(),h(new Error("email tenant request timeout"))},d)})])}finally{u!==void 0&&clearTimeout(u)}if(!a.ok||a.headers.get("content-encoding")||a.headers.get("content-type")!==`application/vnd.void.email-actions; version=${1}`||!a.body)throw new Error(`invalid email tenant response (${a.status})`);let m=Math.min(wn,o-Date.now());if(m<=0)throw new Error("email tenant request timeout");return{actions:await Ut(a.body,m),receiptId:n}}finally{i.abort(),a?.body?.cancel().catch(()=>{});let l=(Q.get(r.projectId)??1)-1;l===0?Q.delete(r.projectId):Q.set(r.projectId,l)}}c(qe,"dispatchBoundedEmailToTenant");g();var Ht=5e3,Bt=4*1024;function ye(e){return e.token}c(ye,"leaseBearer");async function we(e,t,r,n=Ht){if(!e.EMAIL_SIGNING_SECRET)return null;let s=new AbortController,o=Date.now()+Math.min(n,Ht),i=c(async p=>{let f=o-Date.now();if(f<=0)throw s.abort(),new Error("email credential lease timed out");let h=p(),y;try{return await Promise.race([h,new Promise((w,R)=>{y=setTimeout(()=>{s.abort(),R(new Error("email credential lease timed out"))},f)})])}finally{y!==void 0&&clearTimeout(y)}},"beforeDeadline"),a;try{let p=await de(`email-lease-v1
2
2
  ${r}
3
- ${t.toLowerCase()}`,e.EMAIL_SIGNING_SECRET);a=await i(()=>e.API.fetch("https://api/internal/email/domain-credential",{method:"POST",headers:{"content-type":"application/json","x-void-internal":p},body:JSON.stringify({domain:t,projectId:r}),signal:s.signal}))}catch{return null}if(!a.ok)return a.body?.cancel().catch(()=>{}),null;let c=a.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>4096))return a.body?.cancel().catch(()=>{}),null;let d=a.body?.getReader();if(!d)return null;let u=new Uint8Array(4096),m=0;try{for(;;){let f=await i(()=>d.read());if(f.done)break;if(m+f.value.byteLength>u.byteLength)throw new Error("email credential lease response too large");u.set(f.value,m),m+=f.value.byteLength}if(c!==null&&m!==Number(c))return null;let p=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,m)));return un(p)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}l(ye,"leaseEmailDomainCredential");function un(e){if(typeof e!="object"||e===null)return null;let t=e.kind,r=e.accountId;if(typeof r!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(r))return null;if(t==="api_token"){let n=e.token;return typeof n=="string"&&n.length>0?{kind:t,token:n,accountId:r}:null}return null}l(un,"parseLease");var Ut=new TextEncoder,pe,jt;async function fn(e){return pe&&jt===e||(pe=await crypto.subtle.importKey("raw",Ut.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),jt=e),pe}l(fn,"getSignKey");async function mn(e,t){let r=await fn(t),n=await crypto.subtle.sign("HMAC",r,Ut.encode(e)),s=String.fromCharCode(...new Uint8Array(n));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}l(mn,"hmacSign");g();var he=class extends Error{static{l(this,"EmailProviderTimeoutError")}constructor(){super("email provider outcome unknown after timeout"),this.name="EmailProviderTimeoutError"}};function we(e=6e4){let t=Date.now()+e;return{remainingMs(r=0){return Math.max(0,t-Date.now()-r)},expired(r=0){return Date.now()>=t-r},async run(r,n=0){let s=Math.min(3e4,t-Date.now()-n);if(s<=0)throw new he;let o=r(),i;try{return await Promise.race([o,new Promise((a,c)=>{i=setTimeout(()=>c(new he),s)})])}finally{i!==void 0&&clearTimeout(i)}}}}l(we,"createEmailProviderDeadline");g();import{EmailMessage as kn}from"cloudflare:email";g();g();g();g();g();var $t=Symbol();g();g();g();var Ft=l((e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData(),"bufferToFormData");var pn=1e4,be=l(e=>"headers"in e,"isRawRequest"),Gt=l(async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(be(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return s==="multipart/form-data"||s==="application/x-www-form-urlencoded"?gn(e,{all:r,dot:n}):{}},"parseBody");async function gn(e,t){if(!be(e)&&e.bodyCache.formData)return Ht(await e.bodyCache.formData,t);let r=be(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),s=Ft(n,r.get("Content-Type")||"");be(e)||(e.bodyCache.formData=s);let o=await s;return o?Ht(o,t):{}}l(gn,"parseFormData");function Ht(e,t){let r=Object.create(null),n={count:0};return e.forEach((s,o)=>{t.all||o.endsWith("[]")?yn(r,o,s):r[o]=s}),t.dot&&Object.entries(r).forEach(([s,o])=>{s.includes(".")&&(hn(r,s,o,n),delete r[s])}),r}l(Ht,"convertFormDataToBodyData");var yn=l((e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},"handleParsingAllValues"),hn=l((e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let s=e,o=t.split(".",34);o.length>33&&Bt(),o.forEach((i,a)=>{a===o.length-1?s[i]=r:((!s[i]||typeof s[i]!="object"||Array.isArray(s[i])||s[i]instanceof File)&&(n.count++>=pn&&Bt(),s[i]=Object.create(null)),s=s[i])})},"handleParsingNestedValues"),Bt=l(()=>{throw new Error("Nesting limit exceeded")},"throwNestingLimitExceeded");g();var Ye=l(e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},"splitPath"),zt=l(e=>{let{groups:t,path:r}=wn(e),n=Ye(r);return bn(n,t)},"splitRoutingPath"),wn=l(e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},"extractGroupsFromPath"),bn=l((e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let s=e.length-1;s>=0;s--)if(e[s].includes(n)){e[s]=e[s].replace(n,t[r][1]);break}}return e},"replaceGroupMarks"),Ee={},Vt=l((e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Ee[n]||(r[2]?Ee[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Ee[n]=[e,r[1],!0]),Ee[n]}return null},"getPattern"),qt=l((e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},"tryDecode"),En=l(e=>qt(e,decodeURI),"tryDecodeURI"),Je=l(e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let s=t.charCodeAt(n);if(s===37){let o=t.indexOf("?",n),i=t.indexOf("#",n),a=o===-1?i===-1?void 0:i:i===-1?o:Math.min(o,i),c=t.slice(r,a);return En(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(s===63||s===35)break}return t.slice(r,n)},"getPath");var Wt=l(e=>{let t=Je(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},"getPathNoStrict"),L=l((e,t,...r)=>(r.length&&(t=L(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),"mergePath"),Re=l(e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(s.charCodeAt(s.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let o=s.slice(0,-1);n+="/"+o,r.push(n)}else n+="/"+s}),r.filter((s,o,i)=>i.indexOf(s)===o)},"checkOptionalParameter"),Ae=l(e=>e.indexOf("%")!==-1?qt(e,Rn):e,"tryDecodeURIComponent"),Xe=l(e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Ae(e)),"_decodeURI"),Xt=l((e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let s;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;for(e.startsWith(t,a+1)||(a=e.indexOf(`&${t}`,a+1));a!==-1;){let c=e.charCodeAt(a+t.length+1);if(c===61){let d=a+t.length+2,u=e.indexOf("&",d);return Xe(e.slice(d,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(s=/[%+]/.test(e),!s)return}let o=Object.create(null);s??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let a=e.indexOf("&",i+1),c=e.indexOf("=",i);c>a&&a!==-1&&(c=-1);let d=e.slice(i+1,c===-1?a===-1?void 0:a:c);if(s&&(d=Xe(d)),i=a,d==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),s&&(u=Xe(u))),r?(o[d]&&Array.isArray(o[d])||(o[d]=[]),o[d].push(u)):o[d]??=u}return t?o[t]:o},"_getQueryParam"),Yt=Xt,Jt=l((e,t)=>Xt(e,t,!0),"getQueryParams"),Rn=decodeURIComponent;var Kt=class{static{l(this,"HonoRequest")}raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#i()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#n(t);return r&&Ae(r)}#i(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=Ae(n))}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Yt(this.url,e)}queries(e){return Jt(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Gt(this,e)}#s=l(e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let s in t)return t[s].then(o=>{s==="json"&&(o=JSON.stringify(o));let i=s==="formData"?void 0:r.headers.get("content-type");return new Response(o,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=r[e]()},"#cachedBody");json(){return this.#s("text").then(e=>JSON.parse(e))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}bytes(){return this.#s("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[$t](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};g();var Qt={Stringify:1,BeforeStream:2,Stream:3},An=l((e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},"raw");var Ke=l(async(e,t,r,n,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let i=Promise.all(o.map(a=>a({phase:t,buffer:s,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>Ke(c,t,!1,n,s))).then(()=>s[0]));return r?An(await i,o):i},"resolveCallback");var _n="text/plain; charset=UTF-8",Qe=l((e,t)=>({"Content-Type":e,...t}),"setDefaultContentType"),re=l((e,t)=>new Response(e,t),"createResponseInstance"),Ze=class{static{l(this,"Context")}#t;#e;env={};#r;finalized=!1;error;#i;#n;#s;#d;#l;#c;#a;#u;#f;constructor(e,t){this.#t=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new Kt(this.#t,this.#f,this.#u),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=re(null,{headers:this.#a??=new Headers})}set res(e){if(this.#s&&e){e=re(e.body,e);for(let[t,r]of this.#s.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#s.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of n)e.headers.append("set-cookie",s)}else e.headers.set(t,r)}this.#s=e,this.finalized=!0}render=l((...e)=>(this.#l??=t=>this.html(t),this.#l(...e)),"render");setLayout=l(e=>this.#d=e,"setLayout");getLayout=l(()=>this.#d,"getLayout");setRenderer=l(e=>{this.#l=e},"setRenderer");header=l((e,t,r)=>{this.finalized&&(this.#s=re(this.#s.body,this.#s));let n=this.#s?this.#s.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)},"header");status=l(e=>{this.#i=e},"status");set=l((e,t)=>{this.#r??=new Map,this.#r.set(e,t)},"set");get=l(e=>this.#r?this.#r.get(e):void 0,"get");get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(e,t,r){let n=this.#s?new Headers(this.#s.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[o,i]of new Headers(t.headers))o==="set-cookie"?n.append(o,i):n.set(o,i)}if(r){if(!n){let o=0;for(let i in r)if(++o>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let o in r){let i=r[o];if(typeof i=="string")n.set(o,i);else{n.delete(o);for(let a of i)n.append(o,a)}}}let s=typeof t=="number"?t:t?.status??this.#i;return re(e,{status:s,headers:n??r})}newResponse=l((...e)=>this.#o(...e),"newResponse");body=l((e,t,r)=>this.#o(e,t,r),"body");text=l((e,t,r)=>!this.#a&&!this.#i&&!t&&!r&&!this.finalized?new Response(e):this.#o(e,t,Qe(_n,r)),"text");json=l((e,t,r)=>this.#o(JSON.stringify(e),t,Qe("application/json",r)),"json");html=l((e,t,r)=>{let n=l(s=>this.#o(s,t,Qe("text/html; charset=UTF-8",r)),"res");return typeof e=="object"?Ke(e,Qt.Stringify,!1,{}).then(n):n(e)},"html");redirect=l((e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)},"redirect");notFound=l(()=>(this.#c??=()=>re(),this.#c(this)),"notFound")};g();g();g();var et=l((e,t,r)=>(n,s)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let c,d=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{c=await u(n,()=>i(a+1))}catch(m){if(m instanceof Error&&t)n.error=m,c=await t(m,n),d=!0;else throw m}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||d)&&(n.res=c),n}},"compose");g();var Zt=["get","post","put","delete","options","patch","query"],_e="Can not add a route since the matcher is already built.",ve=class extends Error{static{l(this,"UnsupportedPathError")}};g();var er="__COMPOSED_HANDLER";var vn=l(e=>e.text("404 Not Found",404),"notFoundHandler"),tr=l((e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},"errorHandler"),rr=class nr{static{l(this,"Hono")}get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Zt,"all"].forEach(s=>{this[s]=(o,...i)=>{let a=s.toUpperCase();return typeof o=="string"?this.#t=o:this.#i(a,this.#t,o),i.forEach(c=>{this.#i(a,this.#t,c)}),this}}),this.on=(s,o,...i)=>{for(let a of[o].flat()){this.#t=a;for(let c of[s].flat()){let d=c.toUpperCase();for(let u of i)this.#i(d,this.#t,u)}}return this},this.use=(s,...o)=>(typeof s=="string"?this.#t=s:(this.#t="*",o.unshift(s)),o.forEach(i=>{this.#i("ALL",this.#t,i)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??Je:Wt}#e(){let t=new nr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=vn;errorHandler=tr;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let o;r.errorHandler===tr?o=s.handler:(o=l(async(i,a)=>(await et([],r.errorHandler)(i,()=>s.handler(i,a))).res,"handler"),o[er]=s.handler),n.#i(s.method,s.path,o,s.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=L(this._basePath,t),r}onError=l(t=>(this.errorHandler=t,this),"onError");notFound=l(t=>(this.#r=t,this),"notFound");mount(t,r,n){let s,o;n&&(typeof n=="function"?o=n:(o=n.optionHandler,n.replaceRequest===!1?s=l(c=>c,"replaceRequest"):s=n.replaceRequest));let i=o?c=>{let d=o(c);return Array.isArray(d)?d:[d]}:c=>{let d;try{d=c.executionCtx}catch{}return[c.env,d]};s||=(()=>{let c=L(this._basePath,t),d=c==="/"?0:c.length;return u=>{let m=new URL(u.url);return m.pathname=this.getPath(u).slice(d)||"/",new Request(m,u)}})();let a=l(async(c,d)=>{let u=await r(s(c.req.raw),...i(c));if(u)return u;await d()},"handler");return this.#i("ALL",L(t,"*"),a),this}#i(t,r,n,s){r=L(this._basePath,r);let o={basePath:s!==void 0?L(this._basePath,s):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,o]),this.routes.push(o)}#n(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#s(t,r,n,s){if(s==="HEAD")return(async()=>new Response(null,await this.#s(t,r,n,"GET")))();let o=this.getPath(t,{env:n}),i=this.router.match(s,o),a=new Ze(t,{path:o,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let d;try{d=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#n(u,a)}return d instanceof Promise?d.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#n(u,a)):d??this.#r(a)}let c=et(i[0],this.errorHandler,this.#r);return(async()=>{try{let d=await c(a);if(!d.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return d.res}catch(d){return this.#n(d,a)}})()}fetch=l((t,...r)=>this.#s(t,r[1],r[0],t.method),"fetch");request=l((t,r,n,s)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${L("/",t)}`,r),n,s)),"request");fire=l(()=>{addEventListener("fetch",t=>{t.respondWith(this.#s(t.request,t,void 0,t.request.method))})},"fire")};g();g();var M=l(()=>Object.create(null),"createNullObject");g();var Ie=[];function tt(e,t){let r=this.buildAllMatchers(),n=l(((s,o)=>{let i=r[s]||r.ALL,a=i[2][o];if(a)return a;let c=o.match(i[0]);if(!c)return[[],Ie];let d=c.indexOf("",1);return[i[1][d],c]}),"match");return this.match=n,n(e,t)}l(tt,"match");g();var nt="[^/]+";var st="(?:|/.*)",D=Symbol(),sr=new Set(".\\+*[^]$()");function In(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===".*"||e==="(?:|/.*)"?t==="(?:|/.*)"?-1:1:t===".*"||t==="(?:|/.*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}l(In,"compareKey");var ir=class rt{static{l(this,"Node")}#t;#e;#r=M();insert(t,r,n,s,o){let i=this;for(let a=0,c=t.length;a<c;a++){let d=t[a],u=d.length===1?d==="*"?a===c-1?["","",".*"]:["","",nt]:null:d==="/*"?["","",st]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),m;if(u){let p=u[1],f=u[2]||"[^/]+";if(p&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&sr.has(f)))throw D;if(m=i.#r[f],!m){if(f!==".*"&&f!=="(?:|/.*)"){for(let y in i.#r)if((f.length>1||y.length>1)&&y!==".*"&&y!=="(?:|/.*)")throw D}m=i.#r[f]=new rt}p!==""&&(m.#e??=s.varIndex++,n.push([p,m.#e]))}else if(m=i.#r[d],!m){for(let p in i.#r)if(p.length>1&&p!==".*"&&p!=="(?:|/.*)")throw D;m=i.#r[d]=new rt}i=m}if(i.#t!==void 0)throw D;i.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(In).map(r=>{let n=this.#r[r],s=n.buildRegExpStr();return s===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:sr.has(r)?`\\${r}`:r)+s}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&t.unshift(`#${this.#t}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}};g();var it=class{static{l(this,"Trie")}#t={varIndex:0};#e=new ir;#r=0;paths=M();insert(e,t){if(t){this.#e.insert(e.split(""),0,[],this.#t,!0);return}let r=[],n=[],s=e;for(let i=0;;){let a=!1;if(s=s.replace(/\{[^}]+\}/g,c=>{let d=`@\\${i}`;return n[i]=[d,c],i++,a=!0,d}),!a)break}let o=s.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,n[i][1]);break}}this.#e.insert(o,this.#r,r,this.#t,!1),this.paths[e]=[this.#r++,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,i)=>o!==void 0?(r[++t]=Number(o),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var or=M();function ar(e){return or[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?st:t==="*"?".*":`/:${nt}`)}$`)}l(ar,"buildWildcardRegExp");function Se(e,t){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(ar(r).test(t))return[...e[r]]}l(Se,"findMiddleware");var Me=class{static{l(this,"RegExpRouter")}name="RegExpRouter";#t;#e;#r;constructor(){this.#t={ALL:M()},this.#e={ALL:M()},this.#r={ALL:new it}}#i(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===D?new ve(t):r}}add(e,t,r){let n=this.#t,s=this.#e;if(!n)throw new Error(_e);if(!n[e]){this.#r[e]=new it;for(let a of[n,s]){a[e]=M();for(let c in a.ALL)a[e][c]=[...a.ALL[c]],this.#i(e,c)}}t==="/*"&&(t="*");let o=e==="ALL"?Object.keys(n):[e];if(/\*$/.test(t)){let a=ar(t);for(let c of o)n[c][t]||(this.#i(c,t),n[c][t]=Se(n[c],t)||Se(n.ALL,t)||[]);for(let c of[n,s])for(let d of o)for(let u in c[d])a.test(u)&&c[d][u].push([r,t]);return}let i=Re(t)||[t];for(let a of i)for(let c of o)s[c][a]||(this.#i(c,a),s[c][a]=Se(n[c],a)||Se(n.ALL,a)||[]),s[c][a].push([r,a])}match=tt;buildAllMatchers(){let e=M();for(let t of Object.keys(this.#e))e[t]=this.#n(t);return this.#t=this.#e=this.#r=void 0,or=M(),e}#n(e){let t=this.#t[e],r=this.#e[e],n=this.#r[e],s=M(),o=[],[i,a,c]=n.buildRegExp();for(let d of[t,r])for(let u in d){let m=d[u],p=n.paths[u];if(!p){s[u]=[m.map(([f])=>[f,M()]),Ie];continue}o[p[0]]=m.map(([f,y])=>[f,n.paths[y][1].reduceRight((h,[b],R)=>(h[b]=c[p[1][R][1]],h),M())])}return[i,a.map(d=>o[d]),s]}};g();g();g();var lr=class{static{l(this,"SmartRouter")}name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(_e);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,s=r.length,o=0,i;for(;o<s;o++){let a=r[o];try{for(let c=0,d=n.length;c<d;c++)a.add(...n[c]);i=a.match(e,t)}catch(c){if(c instanceof ve)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};g();g();var ot=M(),Sn=0,cr=class dr{static{l(this,"Node")}#t=[];#e=M();#r=[];#i;#n=ot;insert(t,r,n){let s=this,o=zt(r),i=new Set,a=0;for(let c of o){let d=o[++a],u=Vt(c,d)||(d===void 0&&c&&c.indexOf("*")===c.length-1?c:null),m=Array.isArray(u),p=m?u[0]:u||c,f=s.#e[p]||=new dr;u&&!f.#i&&(f.#i=u,s.#r.push(f)),s=f,m&&i.add(u[1])}s.#t.push({[t]:{handler:n,possibleKeys:[...i],score:++Sn}})}#s(t,r,n,s,o){for(let i=0,a=r.#t.length;i<a;i++){let c=r.#t[i],d=c[n]||c.ALL;if(d){d.params=M(),t.push(d);for(let u=0,m=d.possibleKeys.length;u<m;u++){let p=d.possibleKeys[u];d.params[p]=o?.[p]&&!u?o[p]:s[p]??o?.[p]}}}}search(t,r){let n=[];this.#n=ot;let s=[this],o=Ye(r),i=[],a=o.length,c=null;for(let d=0;d<a;d++){let u=o[d],m=d===a-1,p=[];for(let y=0,h=s.length;y<h;y++){let b=s[y],R=b.#e[u];R&&(R.#n=b.#n,m?(R.#e["*"]&&this.#s(n,R.#e["*"],t,b.#n),this.#s(n,R,t,b.#n)):p.push(R));for(let E of b.#r){let _=E.#i,w=b.#n===ot?{}:{...b.#n};if(typeof _=="string"){(_==="*"||u.startsWith(_.slice(0,-1)))&&(this.#s(n,E,t,b.#n),_==="*"&&(E.#n=w,p.push(E)));continue}let[,v,T]=_;if(!(!u&&T===!0)){if(T!==!0){if(!c){c=[];let $=r[0]==="/"?1:0;for(let F=0;F<a;F++)c[F]=$,$+=o[F].length+1}let I=r.slice(c[d]),N=T.exec(I);if(N){w[v]=N[0],this.#s(n,E,t,b.#n,w),N[0].length===I.length&&E.#e["*"]&&this.#s(n,E.#e["*"],t,b.#n,w);for(let $ in E.#e){E.#n=w;let F=N[0].match(/\//g)?.length??0;(i[F]||=[]).push(E);break}continue}}(T===!0||T.test(u))&&(w[v]=u,m?(this.#s(n,E,t,w,b.#n),E.#e["*"]&&this.#s(n,E.#e["*"],t,w,b.#n)):(E.#n=w,p.push(E)))}}}let f=i.shift();s=f?p.concat(f):p}return n[1]&&n.sort((d,u)=>d.score-u.score),[n.map(({handler:d,params:u})=>[d,u])]}};var at=class{static{l(this,"TrieRouter")}name="TrieRouter";#t=new cr;add(e,t,r){for(let n of Re(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};g();var lt=class extends rr{static{l(this,"Hono")}constructor(e={}){super(e),this.router=e.router??new lr({routers:[new Me,new at]})}};g();g();g();g();g();g();g();g();g();g();function ne(e){return typeof e=="string"?e:null}l(ne,"asString");var On=new lt,xn=5e4,C=5e3,Te=5*1024*1024,Pn=16*1024,Ln=new Set(["from","to","cc","bcc","subject","reply-to","date","message-id","in-reply-to","references","mime-version","content-type","content-transfer-encoding","content-disposition"]);function Dn(e){let t=0,r=!1;for(let n=0;n<e.byteLength;){let s=n;for(;s<e.byteLength&&e[s]!==10;)s++;let o=s>n&&e[s-1]===13?s-1:s;if(o===n)return!0;if(e[n]!==32&&e[n]!==9){let i=n;for(;i<o&&e[i]!==58;)i++;let a=new TextDecoder().decode(e.subarray(n,i)).toLowerCase();r=i<o&&!Ln.has(a)}if(r&&(t+=o-n+2,t>Pn))return!1;n=s+1}return!0}l(Dn,"customMimeHeaderBytesWithinLimit");var ur=50,fr=320,mr=320;function se(e){let t=e.EMAIL_SENDER_DOMAIN;if(typeof t!="string")return null;let r=t.trim().toLowerCase();return r.length>0?r:null}l(se,"readSenderDomain");var Cn=/[.*+?^${}()|[\]\\]/g;function jn(e){return e.replace(Cn,"\\$&")}l(jn,"escapeRegExp");var pr=new Map;function Un(e){let t=pr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${jn(e)}$`);return pr.set(e,r),r}l(Un,"strictFromRe");var $n=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function Le(e,t=200){return e.slice(0,t).replace($n," ")}l(Le,"sanitizeForLog");var Fn=128;function Hn(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}l(Hn,"bytesToStream");var gr=10,Ne=13,hr=32,wr=9,Bn=58,ke=[102,114,111,109];function Gn(e,t,r){if(r-t<=ke.length)return-1;for(let s=0;s<ke.length;s++)if((e[t+s]|32)!==ke[s])return-1;let n=t+ke.length;for(;n<r&&(e[n]===hr||e[n]===wr);)n++;return n<r&&e[n]===Bn?n+1:-1}l(Gn,"fromValueStart");var br={missing:"the message has no From header",multiple:"the message has more than one From header",malformed:"the From header must hold a single mailbox"};function De(e){let t=e.byteLength,r=0,n=-1,s=-1,o=!1,i=!1,a=e.indexOf(Ne),c=0;for(;c<t;){let m=e.indexOf(gr,c),f=m===-1?t:m;if(f>c&&e[f-1]===Ne&&f--,f===c)break;if(a!==-1&&a<c&&(a=e.indexOf(Ne,c)),a!==-1&&a<f)return{ok:!1,reason:"malformed"};if(e[c]===hr||e[c]===wr)i&&(s=f,o=!0);else{let y=Gn(e,c,f);i=y!==-1,i&&(r++,n=y,s=f,o=!1)}c=m===-1?t:m+1}if(r===0)return{ok:!1,reason:"missing"};if(r>1)return{ok:!1,reason:"multiple"};let d=e.subarray(n,s);if(o){d=e.slice(n,s);let m=0;for(let p=0;p<d.length;p++){let f=d[p];f!==Ne&&f!==gr&&(d[m++]=f)}d=d.subarray(0,m)}let u=zn(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}l(De,"readMimeFromAddrSpec");function zn(e){let t=!1,r=!1,n=-1,s=-1,o=-1;for(let a=0;a<e.length;a++){let c=e[a];if(t){r?r=!1:c==="\\"?r=!0:c==='"'&&(t=!1);continue}switch(c){case'"':if(n!==-1)return null;t=!0;break;case"<":if(n!==-1)return null;n=a;break;case">":if(n===-1||s!==-1)return null;s=a;break;case"@":o===-1&&(o=a);break;case",":case";":case":":case"(":case")":case"[":case"]":case"\\":return null;default:break}}if(t)return null;let i;if(n===-1)i=e.trim();else{if(s===-1||e.slice(s+1).trim().length!==0||o!==-1&&o<n)return null;i=e.slice(n+1,s)}return/^[\x21-\x7e]+$/.test(i)?i:null}l(zn,"singleMailboxAddrSpec");On.post("/send",async e=>{let t=we(xn),r=e.get("projectId"),n=e.get("body"),s=ne(n.from),o=ne(n.mimeBase64),i=ne(n.requestId),a=i===null?"unknown":Le(i,Fn),c=ne(n.idempotencyKey);if(c!==null&&(c.length===0||c.length>128||!/^[\x20-\x7e]+$/.test(c)))return e.json({ok:!1,error:{code:"INVALID_TO",message:"invalid idempotency key"}},400);let d=c??(i&&i.length<=128&&/^[\x20-\x7e]+$/.test(i)?i:crypto.randomUUID()),u=Array.isArray(n.recipients)?n.recipients:null;if(!s||!o||!u)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"invalid body"}},400);if(u.length>ur)return e.json({ok:!1,error:{code:"INVALID_TO",message:`too many recipients (max ${ur}, got ${u.length})`}},413);if(s.length>mr)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${mr} characters`}},413);let m=se(e.env);if(!m)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sender domain is not configured"}},502);let p=[],f=new Set;for(let A of u){if(typeof A!="string")continue;if(A.length>fr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${fr} characters`}},413);let S=A.trim().toLowerCase();!S||f.has(S)||(f.add(S),p.push(S))}if(p.length===0)return e.json({ok:!1,error:{code:"INVALID_TO",message:"no recipients"}},200);if(o.length>Math.ceil(Te*4/3)+4)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${Te} bytes (base64 length ${o.length})`}},413);let y;try{y=qn(o)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"invalid base64 mime"}},400)}if(y.byteLength>Te)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${Te} bytes (got ${y.byteLength})`}},413);if(!Dn(y))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let h=s.indexOf("@"),b=h===-1?"":s.slice(h+1).toLowerCase();if(b!==""&&b!==m)return Vn(e,r,s,b,m,p,y,a,d,t);let R=e.env.SEND_EMAIL;if(typeof R?.send!="function")return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sending is not configured"}},502);let E=s.split("@")[0]?.split("+")[0]??"";if(!/^[\x21-\x7e]+$/.test(s))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let _=s.toLowerCase();if(!Un(m).test(_))return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${m}`}},200);if((_.slice(0,_.indexOf("@")).split("+")[0]??"")!==E.toLowerCase())return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${m}`}},200);let T=De(y);if(!T.ok||T.addrSpec.toLowerCase()!==_){let A=T.ok?"the From header address does not match the envelope sender":br[T.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${s}: ${A}`}},403)}let I;try{I=await Z(e.env,{projectId:r,kind:"direct",key:d,digest:await Q("direct",s,p,y),from:s,recipients:p,transport:"binding"},t.remainingMs(C))}catch(A){let S=A instanceof Error&&A.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:S?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:S?"idempotency key has different content":"email admission unavailable"}},S?409:503)}let N=I.recipients.filter(A=>A.state!=="reserved").map(A=>({recipient:A.recipient,ok:A.state==="provider_accepted",state:A.state,messageId:A.providerReference??void 0,error:A.state==="provider_accepted"?void 0:{code:A.errorCode??(A.state==="outcome_unknown"||A.state==="attempt_started"?"OUTCOME_UNKNOWN":A.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:A.state==="outcome_unknown"||A.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":A.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(I.replay){for(let A of I.recipients.filter(S=>S.state==="reserved"))N.push({recipient:A.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return xe(e,I.operationId,N)}let $=I.recipients.filter(A=>A.state==="reserved").map(A=>A.recipient);for(let A=0;A<$.length;A++){let S=$[A];if(t.expired(C)){let H=$.slice(A),X=await ct(e.env,I.operationId,H,t.remainingMs());for(let ae of H)N.push({recipient:ae,ok:!1,state:X?"cancelled":"outcome_unknown",error:X?{code:"UPSTREAM_ERROR",message:"email batch deadline elapsed before provider submission"}:{code:"OUTCOME_UNKNOWN",message:"could not cancel unstarted email attempt"}});break}try{await ee(e.env,I.operationId,[S],t.remainingMs(C))}catch{let H=await ct(e.env,I.operationId,[S],t.remainingMs());N.push({recipient:S,ok:!1,state:H?"cancelled":"outcome_unknown",error:H?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});continue}try{let H=new kn(s,S,Hn(y)),X=await t.run(()=>R.send(H),C),ae=typeof X?.messageId=="string"?X.messageId:"";try{await O(e.env,I.operationId,[S],"provider_accepted",{providerReference:ae},t.remainingMs())}catch{N.push({recipient:S,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider accepted email but outcome could not be recorded"}});continue}N.push({recipient:S,ok:!0,state:"provider_accepted",messageId:ae})}catch{try{await O(e.env,I.operationId,[S],"outcome_unknown",{errorCode:"OUTCOME_UNKNOWN"},t.remainingMs())}catch{}N.push({recipient:S,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"}})}}return Rr(r,a,N),N.some(A=>!A.ok)?e.json({ok:!1,operationId:I.operationId,deliveries:N},200):e.json({ok:!0,operationId:I.operationId,ids:N.map(A=>({recipient:A.recipient,messageId:A.messageId,state:"provider_accepted"}))})});var yr=64*1024;async function dt(e,t=3e4){let r=new AbortController,n=Date.now()+Math.min(3e4,t),s=JSON.stringify({from:e.from,recipients:e.recipients,mime_message:e.mimeMessage}),o=l(async m=>{let p=n-Date.now();if(p<=0)throw r.abort(),new Error("email sending request timed out");let f=m(),y;try{return await Promise.race([f,new Promise((h,b)=>{y=setTimeout(()=>{r.abort(),b(new Error("email sending request timed out"))},p)})])}finally{y!==void 0&&clearTimeout(y)}},"beforeDeadline"),i=await o(()=>fetch(`https://api.cloudflare.com/client/v4/accounts/${e.accountId}/email/sending/send_raw`,{method:"POST",headers:{authorization:`Bearer ${e.bearer}`,"content-type":"application/json"},body:s,signal:r.signal}));if(!i.ok)return i.body?.cancel().catch(()=>{}),{ok:!1,status:i.status};let a=i.headers.get("content-length");if(a!==null&&(!/^\d+$/.test(a)||Number(a)>yr))throw i.body?.cancel().catch(()=>{}),new Error("email sending API response too large");let c=i.body?.getReader();if(!c)throw new Error("email sending API response unreadable");let d=new Uint8Array(yr),u=0;try{for(;;){let m=await o(()=>c.read());if(m.done)break;if(u+m.value.byteLength>d.byteLength)throw new Error("email sending API response too large");d.set(m.value,u),u+=m.value.byteLength}if(a!==null&&u!==Number(a))throw new Error("email sending API response length mismatch");return{ok:!0,data:JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(d.subarray(0,u)))}}finally{c.cancel().catch(()=>{});try{c.releaseLock()}catch{}}}l(dt,"requestSendRaw");function Oe(e){if(!Array.isArray(e))return null;let t=new Set;for(let r of e){if(typeof r!="string")return null;t.add(r.toLowerCase())}return t}l(Oe,"readSendRawAddressList");function ut(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=Oe(t.delivered),n=Oe(t.permanent_bounces),s=Oe(t.queued),o=Oe(t.suppressed_recipients);return!r||!n||!s||!o||typeof t.message_id!="string"||t.message_id===""?null:{delivered:r,messageId:t.message_id,permanentBounces:n,queued:s,suppressedRecipients:o}}l(ut,"parseSendRawResult");function ft(e,t){let r=t.toLowerCase(),n=[e.delivered.has(r),e.queued.has(r),e.permanentBounces.has(r),e.suppressedRecipients.has(r)];return n.filter(Boolean).length!==1?"outcome_unknown":n[0]||n[1]?"provider_accepted":n[2]?"permanent_bounce":"suppressed"}l(ft,"classifySendRawRecipient");async function Vn(e,t,r,n,s,o,i,a,c,d){if(!/^[\x21-\x7e]+$/.test(r))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let u=r.toLowerCase(),m=De(i);if(!m.ok||m.addrSpec.toLowerCase()!==u){let w=m.ok?"the From header address does not match the envelope sender":br[m.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${w}`}},403)}let p;try{p=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(i)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"mime must be valid UTF-8"}},400)}let f;try{f=await Z(e.env,{projectId:t,kind:"direct",key:c,digest:await Q("direct",r,o,i),from:r,recipients:o,transport:"send_raw"},d.remainingMs(C))}catch(w){let v=w instanceof Error&&w.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:v?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:v?"idempotency key has different content":"email admission unavailable"}},v?409:503)}let y=f.recipients.filter(w=>w.state!=="reserved").map(w=>({recipient:w.recipient,ok:w.state==="provider_accepted",state:w.state,messageId:w.providerReference??void 0,error:w.state==="provider_accepted"?void 0:{code:w.errorCode??(w.state==="outcome_unknown"||w.state==="attempt_started"?"OUTCOME_UNKNOWN":w.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:w.state==="outcome_unknown"||w.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":w.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(f.replay){for(let w of f.recipients.filter(v=>v.state==="reserved"))y.push({recipient:w.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return xe(e,f.operationId,y)}if(o=f.recipients.filter(w=>w.state==="reserved").map(w=>w.recipient),o.length===0)return xe(e,f.operationId,y);let h=await ye(e.env,n,t,d.remainingMs(C));if(!h)return await O(e.env,f.operationId,o,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"could not lease the domain credential"}},502);if(f.accountId!==h.accountId)return await O(e.env,f.operationId,o,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"email domain changed during admission"}},503);try{await ee(e.env,f.operationId,o,d.remainingMs(C))}catch{let w=await ct(e.env,f.operationId,o,d.remainingMs());for(let v of o)y.push({recipient:v,ok:!1,state:w?"cancelled":"outcome_unknown",error:w?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return xe(e,f.operationId,y)}let b=null,R="failed",E=null,_=null;try{_=await dt({accountId:h.accountId,bearer:ge(h),from:r,recipients:o,mimeMessage:p},d.remainingMs(C))}catch{b={code:"UPSTREAM_ERROR",message:"email sending request failed"},R="outcome_unknown"}if(_)if(!_.ok)b={code:_.status===429?"QUOTA_EXCEEDED":"UPSTREAM_ERROR",message:`email sending API returned ${_.status}`},R=_.status>=500||_.status===408?"outcome_unknown":"failed";else{let w=_.data,v=typeof w=="object"&&w!==null?w.success:void 0;v===!1?b={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:v!==!0?(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"):(E=ut(w.result),E||(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"))}for(let w of o){if(b){y.push({recipient:w,ok:!1,state:R,error:b});continue}let v=ft(E,w);v==="permanent_bounce"?y.push({recipient:w,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${w}' permanently bounced`}}):v==="suppressed"?y.push({recipient:w,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${w}' is on the suppression list`}}):v==="outcome_unknown"?y.push({recipient:w,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):y.push({recipient:w,ok:!0,state:"provider_accepted",messageId:E.messageId})}for(let w of y.filter(v=>f.recipients.some(T=>T.recipient===v.recipient&&T.state==="reserved")))try{await O(e.env,f.operationId,[w.recipient],w.ok?"provider_accepted":w.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:w.messageId,errorCode:w.ok?void 0:w.state==="outcome_unknown"?"OUTCOME_UNKNOWN":b?.code??w.error?.code},d.remainingMs()),w.state=w.ok?"provider_accepted":w.state==="outcome_unknown"?"outcome_unknown":"failed",w.state==="outcome_unknown"&&!w.ok&&(w.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{w.ok=!1,w.state="outcome_unknown",w.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return Rr(t,a,y),y.some(w=>!w.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:y},200):e.json({ok:!0,operationId:f.operationId,ids:y.map(w=>({recipient:w.recipient,messageId:w.messageId,state:"provider_accepted"}))})}l(Vn,"sendViaCustomDomain");async function Er(e,t){console.log(`[email-recv] ${e} ${Le(t.from,320)} -> ${Le(t.to,320)} ${t.status} (${t.byteSize}B) @${Date.now()}`)}l(Er,"recordInboundDelivery");async function ct(e,t,r,n){try{let s=await O(e,t,r,"cancelled",{},n);return r.every(o=>s.recipients.some(i=>i.recipient===o&&i.state==="cancelled"))}catch{return!1}}l(ct,"cancelUnstartedRecipients");function xe(e,t,r){return r.length===0?e.json({ok:!1,operationId:t,error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved"}},200):r.some(n=>!n.ok)?e.json({ok:!1,operationId:t,deliveries:r},200):e.json({ok:!0,operationId:t,ids:r.map(n=>({recipient:n.recipient,messageId:n.messageId??"",state:n.state}))},200)}l(xe,"emailActionResponse");function Rr(e,t,r){for(let n of r){let s=n.ok?"sent":n.error?.code??"unknown_error",o=n.messageId??"";console.log(`[email-log] ${e} ${t} ${Le(n.recipient,320)} ${s} ${o} @${Date.now()}`)}}l(Rr,"logSend");function qn(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}l(qn,"base64Decode");var Wn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function k(e,t){return e.slice(0,t).replace(Wn," ")}l(k,"sanitize");function ie(e,t){switch(typeof e){case"string":return k(e,t);case"number":case"boolean":case"undefined":return String(e);case"object":return e===null?"null":k(Object.prototype.toString.call(e),64);default:return`[${typeof e}]`}}l(ie,"describeUntrusted");function Xn(e){return{routeId:e.routeId,routeGeneration:e.routeGeneration,connectionId:e.connectionId,addressing:e.addressing,domain:e.domain,projectSlug:e.slug}}l(Xn,"receiptRouteFence");var x=10*1024*1024,oe=1024,gt=128*1024,Yn=1e3,Ar=100,Nr=320,_r=32,Ce=1024,vr=5*1024*1024,Ir=8*1024*1024,Jn=15e3,je=class extends Error{constructor(r){super(`inbound message exceeds ${x} bytes (got ${r})`);this.size=r;this.name="InboundTooLargeError"}size;static{l(this,"InboundTooLargeError")}},Ue=class extends Error{static{l(this,"InboundTooManyHeadersError")}constructor(){super(`inbound message carries more than ${oe} headers`),this.name="InboundTooManyHeadersError"}},$e=class extends Error{static{l(this,"InboundHeadersTooLargeError")}constructor(){super(`inbound headers exceed ${gt} bytes`),this.name="InboundHeadersTooLargeError"}};function mt(e){return typeof e=="string"&&e.length<=Nr&&(0,Tr.validate)(e)}l(mt,"isValidEmailAddress");function j(e){return ie(e,Nr)}l(j,"logAddress");function Kn(e){if(typeof e!="object"||e===null)return console.error("[email-router] action list dropped: forward headers is not a plain object"),!1;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return console.error("[email-router] action list dropped: forward headers is not a plain object"),!1;let r=Object.keys(e);if(r.length>_r)return console.error(`[email-router] action list dropped: forward has ${r.length} headers (max ${_r})`),!1;for(let n of r){let s=e[n];if(n.length>Ce)return console.error(`[email-router] action list dropped: forward header name exceeds ${Ce} characters`),!1;if(typeof s!="string")return console.error(`[email-router] action list dropped: forward header "${k(n,64)}" value is not a string`),!1;if(s.length>Ce)return console.error(`[email-router] action list dropped: forward header "${k(n,64)}" value exceeds ${Ce} characters`),!1}return!0}l(Kn,"forwardHeadersWithinBounds");function Qn(e,t){if(!/^[\x21-\x7e]+$/.test(e))return!1;let r=e.toLowerCase(),n=r.indexOf("@");return n<=0?!1:r.slice(n+1)!==t.domain||t.customDomain?!0:r.slice(0,n).split("+")[0]===t.slug}l(Qn,"isPermittedReplySender");async function kr(e,t,r,n){let s=se(t)??"void email",o=String(e.to??"").toLowerCase(),i=o.split("@")[0]??"",a=i.indexOf("+"),c=a===-1?i:i.slice(0,a),d=o.indexOf("@"),u=d===-1?"":o.slice(d+1);if(!c){e.setReject(`${s}: missing project slug in recipient`);return}if(n.addressing!=="custom"&&Tt(c)){e.setReject(`${s}: "${k(c,64)}" is a reserved platform address`);return}if(!n.projectId||!n.workerName||!n.deploymentId||n.domain?.toLowerCase()!==u||n.addressing==="shared"&&n.slug.toLowerCase()!==c){e.setReject(`${s}: authoritative route mismatch`);return}let m=n.workerName,p=n.projectId,f;try{f=n.limits?t.DISPATCH.get(m,{},{limits:n.limits}):t.DISPATCH.get(m)}catch(E){throw console.error(`[email-router] DISPATCH.get(${k(m,320)}) failed:`,E),new Error("email worker temporarily unavailable")}if(typeof e.rawSize=="number"&&e.rawSize>x){e.setReject(`${s}: message too large (max ${x} bytes)`);return}let y;try{y=await ts(e),n.addressing==="custom"&&(y.viaDomain=u)}catch(E){if(E instanceof je){e.setReject(`${s}: message too large (max ${x} bytes)`);return}if(E instanceof Ue){e.setReject(`${s}: too many headers (max ${oe})`);return}if(E instanceof $e){e.setReject(`${s}: headers too large (max ${gt} bytes)`);return}console.error(`[email-router] failed to read message body for ${k(c,64)}:`,E),e.setReject(`${s}: could not read inbound message body`);return}let h=crypto.randomUUID(),b={projectId:p,receiptId:h,transport:"native"},R;try{await z(t,h,p,"received",Xn(n))}catch{throw new Error("email admission temporarily unavailable")}try{R=(await We(f,t,{projectId:p,deploymentId:n.deploymentId,envelope:y,receiptId:h})).actions}catch(E){await z(t,h,p,"handler_failed").catch(()=>{});let _=E instanceof Error?E.message.slice(0,320):ie(E,320);throw console.error(`[email-router] dispatch to ${k(m,320)} failed:`,_),new Error("email handler execution unresolved")}try{await z(t,h,p,"handler_completed")}catch{console.error("[email-router] handler completed but receipt status could not be saved");return}try{await Pr(t,e,R,b,{customDomain:n.addressing==="custom",slug:n.slug.toLowerCase(),domain:u})}catch{console.error("[email-router] action execution unresolved",h);return}r.waitUntil(pt(t,p,e,R))}l(kr,"routeInbound");async function Or(e,t,r){let{stub:n,projectId:s,domain:o,envelope:i,authoritative:a,receiptId:c}=r;if(a.projectId!==s||!a.workerName||!a.slug||a.domain?.toLowerCase()!==o)return{reject:!0};let d=a.slug,u=a.workerName,m=Zn(i),p={projectId:s,receiptId:c,transport:"relay"},f;try{f=(await We(n,e,{projectId:s,deploymentId:a.deploymentId,envelope:i,receiptId:c})).actions}catch(y){await z(e,c,s,"handler_failed").catch(()=>{});let h=y instanceof Error?y.message.slice(0,320):ie(y,320);return console.error(`[email-relay] dispatch to ${k(u,320)} failed:`,h),t.waitUntil(pt(e,s,m.message,[{type:"reject",reason:"dispatch-error"}])),{reject:!0,temporary:!0}}try{await z(e,c,s,"handler_completed")}catch{return console.error("[email-relay] handler completed but receipt status could not be saved"),{reject:!1}}try{await Pr(e,m.message,f,p,{customDomain:a.addressing==="custom",slug:d.toLowerCase(),domain:o})}catch{return console.error("[email-relay] action execution unresolved",c),{reject:!1}}return t.waitUntil(pt(e,s,m.message,f)),{reject:m.rejectedReason()!==null}}l(Or,"routeRelayed");function Zn(e){let t=null;return{message:{from:e.from,to:e.to,rawSize:e.rawSize,headers:new Headers(e.headers),raw:xr(e.raw),setReject(n){t=n},async forward(n,s){throw new U("relayed forward requires a native email event")}},rejectedReason:l(()=>t,"rejectedReason")}}l(Zn,"createRelayedMessage");async function es(e,t,r,n,s){let o=r.slice(r.indexOf("@")+1).toLowerCase();if(o===se(e)){let c=e.SEND_EMAIL;if(!c||typeof c.send!="function")throw new Error("shared email binding is unavailable");return async d=>(await c.send(new Mr(r,d,xr(n))))?.messageId}let i=await ye(e,o,t);if(!i||s&&i.accountId!==s)throw new Error("could not lease the domain credential");let a=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(n);return async(c,d=3e4)=>{let u;try{u=await dt({accountId:i.accountId,bearer:ge(i),from:r,recipients:[c],mimeMessage:a},d)}catch{throw new Error("email sending request failed")}if(!u.ok)throw u.status>=500||u.status===408?new Error("email sending API outcome unknown"):new U(`email sending API returned ${u.status}`);let m=u.data;if(typeof m!="object"||m===null||!("success"in m))throw new Error("email sending API response invalid");if(m.success===!1)throw new U("email sending API refused the message");if(m.success!==!0)throw new Error("email sending API response invalid");let p=ut(m.result);if(!p)throw new Error("email sending API response invalid");let f=ft(p,c);if(f==="permanent_bounce")throw new U("recipient permanently bounced");if(f==="suppressed")throw new U("recipient is on the suppression list");if(f==="outcome_unknown")throw new Error("email sending API did not classify the recipient");return p.messageId}}l(es,"prepareRelayedReply");function xr(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}l(xr,"envelopeRawStream");async function pt(e,t,r,n){if(!t){console.error(`[email-router] cannot log inbound delivery: routing entry has no projectId (to=${k(String(r.to??""),320)})`);return}let s=n.some(o=>o&&typeof o=="object"&&o.type==="reject")?"rejected":n.length===0?"accepted":"handled";try{await Er(t,{from:String(r.from??""),to:String(r.to??""),byteSize:r.rawSize??0,status:s})}catch(o){console.error("[email-router] log-recv failed:",o)}}l(pt,"logRecv");async function ts(e){let t=[],r=0,n=new TextEncoder;for(let i of e.headers){if(t.length>=oe)throw new Ue;if(r+=n.encode(i[0]).byteLength+n.encode(i[1]).byteLength,r>gt)throw new $e;t.push(i)}let s=await rs(e.raw),o=Object.fromEntries(t);return{from:String(e.from??""),to:String(e.to??""),headers:o,raw:s,rawSize:e.rawSize??s.byteLength}}l(ts,"buildEnvelope");async function rs(e){let t=e.getReader(),r=[],n=0,s=Date.now()+Jn;try{for(;;){let a=s-Date.now();if(a<=0)throw new Error("inbound message stream timed out");let c,{value:d,done:u}=await Promise.race([t.read(),new Promise((m,p)=>{c=setTimeout(()=>p(new Error("inbound message stream timed out")),a)})]).finally(()=>{c!==void 0&&clearTimeout(c)});if(u)break;if(n+=d.byteLength,n>x)throw new je(n);r.push(d)}}catch(a){throw t.cancel().catch(()=>{}),a}finally{try{t.releaseLock()}catch{}}let o=new Uint8Array(n),i=0;for(let a of r)o.set(a,i),i+=a.byteLength;return o}l(rs,"readStreamToBytes");var U=class extends Error{static{l(this,"DefinitiveEmailActionError")}};async function ns(e,t){if(e.length>Ar)return console.error(`[email-router] action list dropped: ${e.length} actions returned (max ${Ar})`),null;let r=[],n=0;for(let s of e){if(!s||typeof s!="object")return console.error(`[email-router] dropping non-object action: ${ie(s,320)}`),null;if(s.type==="reject"){let o=typeof s.reason=="string"?s.reason:"",i=o.length>0?k(o,Yn):"rejected by handler";return r.push({type:"reject",reason:i}),r}if(s.type==="forward"){if(!mt(s.to))return console.error(`[email-router] forward dropped: invalid "to" address ${j(s.to)}`),null;let o;if(s.headers){if(!Kn(s.headers))return null;try{o=new Headers(s.headers)}catch(i){return console.error("[email-router] action list dropped: forward headers invalid:",i instanceof Error?k(i.message,320):k(String(i),320)),null}}r.push({type:"forward",to:s.to,headers:o})}else if(s.type==="reply"){if(!mt(s.from)||!mt(s.to))return console.error(`[email-router] reply dropped: invalid address (from=${j(s.from)} to=${j(s.to)})`),null;if(!await Qn(s.from,t))return console.error(`[email-router] reply dropped: sender not owned by project "${k(t.slug,64)}" (from=${j(s.from)})`),null;if(!(s.raw instanceof Uint8Array))return console.error(`[email-router] reply dropped: raw is not a Uint8Array (from=${j(s.from)})`),null;let o=s.raw.byteLength;if(o>vr)return console.error(`[email-router] reply dropped: raw is ${o} bytes (max ${vr}) (from=${j(s.from)})`),null;if(n+o>Ir)return console.error(`[email-router] reply dropped: cumulative reply bytes ${n+o} exceed this delivery's budget of ${Ir} (from=${j(s.from)})`),null;let i=De(s.raw);if(!i.ok||i.addrSpec.toLowerCase()!==s.from.toLowerCase())return console.error(`[email-router] reply dropped: MIME From is not the envelope sender (from=${j(s.from)}, ${i.ok?"header names another address":i.reason})`),null;n+=o,r.push({type:"reply",from:s.from,to:s.to,raw:s.raw})}else return console.warn(`[email-router] dropping unknown action type: ${ie(s.type,320)}`),null}return r}l(ns,"validateActions");async function Pr(e,t,r,n,s){let o=await ns(r,s);if(o===null){await z(e,n.receiptId,n.projectId,"actions_rejected").catch(()=>{console.error("[email-router] could not record rejected actions")});return}await ss(e,t,o,n)}l(Pr,"enactActions");async function ss(e,t,r,n){if(!n.projectId||!n.receiptId){console.error("[email-router] action admission unavailable: missing project or receipt identity");return}let s=we();for(let[o,i]of r.entries()){if(i.type==="reject"){t.setReject(i.reason);return}if(s.expired()){console.error("[email-router] action batch deadline elapsed before admission");break}let a=i.to.toLowerCase(),c=i.type==="reply"?i.from:t.to,d=await Q(i.type,c,[a],i.type==="reply"?i.raw:new TextEncoder().encode(JSON.stringify([...i.headers?.entries()??[]].sort()))),u;try{u=await Z(e,{projectId:n.projectId,kind:i.type,key:`${n.receiptId}:${o}:${d.slice(0,16)}`,digest:d,from:c,recipients:[a],transport:n.transport==="relay"?i.type==="reply"&&i.from.slice(i.from.indexOf("@")+1).toLowerCase()===se(e)?"binding":"send_raw":i.type==="forward"?"native_forward":"native_reply",receiptId:n.receiptId})}catch(f){console.error("[email-router] action admission unavailable:",f instanceof Error?f.message:"unknown");continue}let m=u.recipients.find(f=>f.recipient===a);if(u.replay||m?.state!=="reserved")continue;let p;if(n.transport==="relay"&&i.type==="reply")try{p=await es(e,n.projectId,i.from,i.raw,u.accountId)}catch{await O(e,u.operationId,[a],"cancelled").catch(()=>{console.error("[email-router] could not cancel unsubmitted relayed reply")}),console.error("[email-router] relayed reply could not be prepared");continue}if(s.expired()){let f=await Sr(e,u.operationId,a);console.error(f?"[email-router] action batch deadline elapsed; reservation cancelled":"[email-router] action batch deadline elapsed; cancellation unresolved");break}try{await ee(e,u.operationId,[a])}catch{let f=await Sr(e,u.operationId,a);console.error(f?"[email-router] attempt did not start; reservation cancelled":"[email-router] could not confirm attempt status");continue}try{let f;if(i.type==="forward")await s.run(()=>t.forward(a,i.headers));else if(p)f=await s.run(()=>p(a,s.remainingMs()));else{let y=new ReadableStream({start(h){h.enqueue(i.raw),h.close()}});await s.run(()=>t.reply(new Mr(i.from,a,y)))}try{await O(e,u.operationId,[a],"provider_accepted",{providerReference:f})}catch{console.error("[email-router] provider accepted action but outcome ledger write failed")}}catch(f){let y=f instanceof U;try{await O(e,u.operationId,[a],y?"failed":"outcome_unknown",{errorCode:y?"UPSTREAM_ERROR":"OUTCOME_UNKNOWN"})}catch{}console.error(y?"[email-router] action provider refused":"[email-router] action provider outcome unknown")}}}l(ss,"enactSanitized");async function Sr(e,t,r){try{return(await O(e,t,[r],"cancelled")).recipients.some(s=>s.recipient===r&&s.state==="cancelled")}catch{return!1}}l(Sr,"cancelUnstartedAction");var He=new TextEncoder,Et=new TextDecoder,yt=128*1024,bt=320,is=2,jr="/email/destinations/confirm",os=4*1024,Lr=32*1024,Dr=5e3,ht=0,P=class extends Error{constructor(r,n){super(r);this.status=n;this.name="MimeHeaderError"}status;static{l(this,"MimeHeaderError")}};async function Cr(e){if(ht>=is)throw new Error("email gateway busy");ht++;try{return await e()}finally{ht--}}l(Cr,"withDeliverySlot");async function Ur(e,t){if(!t)throw new Error("Email signing key is not configured");let r=await crypto.subtle.importKey("raw",He.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,He.encode(e))),s="";for(let o of n)s+=String.fromCharCode(o);return btoa(s).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}l(Ur,"sign");async function $r(e,t){let r=Date.now()+5e3,n=new AbortController,s=l(async b=>{let R=r-Date.now();if(R<=0)throw n.abort(),new Error("ingress resolution timeout");let E;try{return await Promise.race([b(),new Promise((_,w)=>{E=setTimeout(()=>{n.abort(),w(new Error("ingress resolution timeout"))},R)})])}finally{E!==void 0&&clearTimeout(E)}},"beforeDeadline"),o=await Ur(`email-ingress-v1
3
+ ${t.toLowerCase()}`,e.EMAIL_SIGNING_SECRET);a=await i(()=>e.API.fetch("https://api/internal/email/domain-credential",{method:"POST",headers:{"content-type":"application/json","x-void-internal":p},body:JSON.stringify({domain:t,projectId:r}),signal:s.signal}))}catch{return null}if(!a.ok)return a.body?.cancel().catch(()=>{}),null;let l=a.headers.get("content-length");if(l!==null&&(!/^\d+$/.test(l)||Number(l)>Bt))return a.body?.cancel().catch(()=>{}),null;let d=a.body?.getReader();if(!d)return null;let u=new Uint8Array(Bt),m=0;try{for(;;){let f=await i(()=>d.read());if(f.done)break;if(m+f.value.byteLength>u.byteLength)throw new Error("email credential lease response too large");u.set(f.value,m),m+=f.value.byteLength}if(l!==null&&m!==Number(l))return null;let p=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,m)));return En(p)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}c(we,"leaseEmailDomainCredential");function En(e){if(typeof e!="object"||e===null)return null;let t=e.kind,r=e.accountId;if(typeof r!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(r))return null;if(t==="api_token"){let n=e.token;return typeof n=="string"&&n.length>0?{kind:t,token:n,accountId:r}:null}return null}c(En,"parseLease");g();var Ee=class extends Error{static{c(this,"EmailProviderTimeoutError")}constructor(){super("email provider outcome unknown after timeout"),this.name="EmailProviderTimeoutError"}};function be(e=6e4){let t=Date.now()+e;return{remainingMs(r=0){return Math.max(0,t-Date.now()-r)},expired(r=0){return Date.now()>=t-r},async run(r,n=0){let s=Math.min(3e4,t-Date.now()-n);if(s<=0)throw new Ee;let o=r(),i;try{return await Promise.race([o,new Promise((a,l)=>{i=setTimeout(()=>l(new Ee),s)})])}finally{i!==void 0&&clearTimeout(i)}}}}c(be,"createEmailProviderDeadline");g();import{EmailMessage as Dn}from"cloudflare:email";g();g();g();g();g();var Gt=Symbol();g();g();g();var zt=c((e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData(),"bufferToFormData");var bn=1e4,Re=c(e=>"headers"in e,"isRawRequest"),Wt=c(async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,s=(Re(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return s==="multipart/form-data"||s==="application/x-www-form-urlencoded"?Rn(e,{all:r,dot:n}):{}},"parseBody");async function Rn(e,t){if(!Re(e)&&e.bodyCache.formData)return Vt(await e.bodyCache.formData,t);let r=Re(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),s=zt(n,r.get("Content-Type")||"");Re(e)||(e.bodyCache.formData=s);let o=await s;return o?Vt(o,t):{}}c(Rn,"parseFormData");function Vt(e,t){let r=Object.create(null),n={count:0};return e.forEach((s,o)=>{t.all||o.endsWith("[]")?An(r,o,s):r[o]=s}),t.dot&&Object.entries(r).forEach(([s,o])=>{s.includes(".")&&(_n(r,s,o,n),delete r[s])}),r}c(Vt,"convertFormDataToBodyData");var An=c((e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},"handleParsingAllValues"),_n=c((e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let s=e,o=t.split(".",34);o.length>33&&qt(),o.forEach((i,a)=>{a===o.length-1?s[i]=r:((!s[i]||typeof s[i]!="object"||Array.isArray(s[i])||s[i]instanceof File)&&(n.count++>=bn&&qt(),s[i]=Object.create(null)),s=s[i])})},"handleParsingNestedValues"),qt=c(()=>{throw new Error("Nesting limit exceeded")},"throwNestingLimitExceeded");g();var Xe=c(e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},"splitPath"),Xt=c(e=>{let{groups:t,path:r}=vn(e),n=Xe(r);return In(n,t)},"splitRoutingPath"),vn=c(e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let s=`@${n}`;return t.push([s,r]),s}),{groups:t,path:e}},"extractGroupsFromPath"),In=c((e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let s=e.length-1;s>=0;s--)if(e[s].includes(n)){e[s]=e[s].replace(n,t[r][1]);break}}return e},"replaceGroupMarks"),Ae={},Jt=c((e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Ae[n]||(r[2]?Ae[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Ae[n]=[e,r[1],!0]),Ae[n]}return null},"getPattern"),Yt=c((e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},"tryDecode"),Sn=c(e=>Yt(e,decodeURI),"tryDecodeURI"),Je=c(e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let s=t.charCodeAt(n);if(s===37){let o=t.indexOf("?",n),i=t.indexOf("#",n),a=o===-1?i===-1?void 0:i:i===-1?o:Math.min(o,i),l=t.slice(r,a);return Sn(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(s===63||s===35)break}return t.slice(r,n)},"getPath");var Kt=c(e=>{let t=Je(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},"getPathNoStrict"),C=c((e,t,...r)=>(r.length&&(t=C(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),"mergePath"),_e=c(e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(s=>{if(s!==""&&!/\:/.test(s))n+="/"+s;else if(/\:/.test(s))if(s.charCodeAt(s.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let o=s.slice(0,-1);n+="/"+o,r.push(n)}else n+="/"+s}),r.filter((s,o,i)=>i.indexOf(s)===o)},"checkOptionalParameter"),ve=c(e=>e.indexOf("%")!==-1?Yt(e,Mn):e,"tryDecodeURIComponent"),We=c(e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),ve(e)),"_decodeURI"),Qt=c((e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let s;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;for(e.startsWith(t,a+1)||(a=e.indexOf(`&${t}`,a+1));a!==-1;){let l=e.charCodeAt(a+t.length+1);if(l===61){let d=a+t.length+2,u=e.indexOf("&",d);return We(e.slice(d,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";a=e.indexOf(`&${t}`,a+1)}if(s=/[%+]/.test(e),!s)return}let o=Object.create(null);s??=/[%+]/.test(e);let i=e.indexOf("?",8);for(;i!==-1;){let a=e.indexOf("&",i+1),l=e.indexOf("=",i);l>a&&a!==-1&&(l=-1);let d=e.slice(i+1,l===-1?a===-1?void 0:a:l);if(s&&(d=We(d)),i=a,d==="")continue;let u;l===-1?u="":(u=e.slice(l+1,a===-1?void 0:a),s&&(u=We(u))),r?(o[d]&&Array.isArray(o[d])||(o[d]=[]),o[d].push(u)):o[d]??=u}return t?o[t]:o},"_getQueryParam"),Zt=Qt,er=c((e,t)=>Qt(e,t,!0),"getQueryParams"),Mn=decodeURIComponent;var tr=class{static{c(this,"HonoRequest")}raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#i()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#n(t);return r&&ve(r)}#i(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#n(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=ve(n))}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Zt(this.url,e)}queries(e){return er(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,n)=>{t[n]=r}),t}async parseBody(e){return Wt(this,e)}#s=c(e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let s in t)return t[s].then(o=>{s==="json"&&(o=JSON.stringify(o));let i=s==="formData"?void 0:r.headers.get("content-type");return new Response(o,{headers:i?{"Content-Type":i}:void 0})[e]()});return t[e]=r[e]()},"#cachedBody");json(){return this.#s("text").then(e=>JSON.parse(e))}text(){return this.#s("text")}arrayBuffer(){return this.#s("arrayBuffer")}bytes(){return this.#s("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#s("blob")}formData(){return this.#s("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Gt](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};g();var rr={Stringify:1,BeforeStream:2,Stream:3},Tn=c((e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},"raw");var Ye=c(async(e,t,r,n,s)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let o=e.callbacks;if(!o?.length)return Promise.resolve(e);s?s[0]+=e:s=[e];let i=Promise.all(o.map(a=>a({phase:t,buffer:s,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(l=>Ye(l,t,!1,n,s))).then(()=>s[0]));return r?Tn(await i,o):i},"resolveCallback");var Nn="text/plain; charset=UTF-8",Ke=c((e,t)=>({"Content-Type":e,...t}),"setDefaultContentType"),Z=c((e,t)=>new Response(e,t),"createResponseInstance"),Qe=class{static{c(this,"Context")}#t;#e;env={};#r;finalized=!1;error;#i;#n;#s;#d;#c;#l;#a;#u;#f;constructor(e,t){this.#t=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new tr(this.#t,this.#f,this.#u),this.#e}get event(){if(this.#n&&"respondWith"in this.#n)return this.#n;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#n)return this.#n;throw Error("This context has no ExecutionContext")}get res(){return this.#s||=Z(null,{headers:this.#a??=new Headers})}set res(e){if(this.#s&&e){e=Z(e.body,e);for(let[t,r]of this.#s.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#s.headers.getSetCookie();e.headers.delete("set-cookie");for(let s of n)e.headers.append("set-cookie",s)}else e.headers.set(t,r)}this.#s=e,this.finalized=!0}render=c((...e)=>(this.#c??=t=>this.html(t),this.#c(...e)),"render");setLayout=c(e=>this.#d=e,"setLayout");getLayout=c(()=>this.#d,"getLayout");setRenderer=c(e=>{this.#c=e},"setRenderer");header=c((e,t,r)=>{this.finalized&&(this.#s=Z(this.#s.body,this.#s));let n=this.#s?this.#s.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)},"header");status=c(e=>{this.#i=e},"status");set=c((e,t)=>{this.#r??=new Map,this.#r.set(e,t)},"set");get=c(e=>this.#r?this.#r.get(e):void 0,"get");get var(){return this.#r?Object.fromEntries(this.#r):{}}#o(e,t,r){let n=this.#s?new Headers(this.#s.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[o,i]of new Headers(t.headers))o==="set-cookie"?n.append(o,i):n.set(o,i)}if(r){if(!n){let o=0;for(let i in r)if(++o>1||typeof r[i]!="string"){n=new Headers;break}}if(n)for(let o in r){let i=r[o];if(typeof i=="string")n.set(o,i);else{n.delete(o);for(let a of i)n.append(o,a)}}}let s=typeof t=="number"?t:t?.status??this.#i;return Z(e,{status:s,headers:n??r})}newResponse=c((...e)=>this.#o(...e),"newResponse");body=c((e,t,r)=>this.#o(e,t,r),"body");text=c((e,t,r)=>!this.#a&&!this.#i&&!t&&!r&&!this.finalized?new Response(e):this.#o(e,t,Ke(Nn,r)),"text");json=c((e,t,r)=>this.#o(JSON.stringify(e),t,Ke("application/json",r)),"json");html=c((e,t,r)=>{let n=c(s=>this.#o(s,t,Ke("text/html; charset=UTF-8",r)),"res");return typeof e=="object"?Ye(e,rr.Stringify,!1,{}).then(n):n(e)},"html");redirect=c((e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)},"redirect");notFound=c(()=>(this.#l??=()=>Z(),this.#l(this)),"notFound")};g();g();g();var Ze=c((e,t,r)=>(n,s)=>{let o=-1;return i(0);async function i(a){if(a<=o)throw new Error("next() called multiple times");o=a;let l,d=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&s||void 0,u)try{l=await u(n,()=>i(a+1))}catch(m){if(m instanceof Error&&t)n.error=m,l=await t(m,n),d=!0;else throw m}else n.finalized===!1&&r&&(l=await r(n));return l&&(n.finalized===!1||d)&&(n.res=l),n}},"compose");g();var nr=["get","post","put","delete","options","patch","query"],Ie="Can not add a route since the matcher is already built.",Se=class extends Error{static{c(this,"UnsupportedPathError")}};g();var sr="__COMPOSED_HANDLER";var xn=c(e=>e.text("404 Not Found",404),"notFoundHandler"),ir=c((e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},"errorHandler"),or=class ar{static{c(this,"Hono")}get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...nr,"all"].forEach(s=>{this[s]=(o,...i)=>{let a=s.toUpperCase();return typeof o=="string"?this.#t=o:this.#i(a,this.#t,o),i.forEach(l=>{this.#i(a,this.#t,l)}),this}}),this.on=(s,o,...i)=>{for(let a of[o].flat()){this.#t=a;for(let l of[s].flat()){let d=l.toUpperCase();for(let u of i)this.#i(d,this.#t,u)}}return this},this.use=(s,...o)=>(typeof s=="string"?this.#t=s:(this.#t="*",o.unshift(s)),o.forEach(i=>{this.#i("ALL",this.#t,i)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??Je:Kt}#e(){let t=new ar({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=xn;errorHandler=ir;route(t,r){let n=this.basePath(t);return r.routes.map(s=>{let o;r.errorHandler===ir?o=s.handler:(o=c(async(i,a)=>(await Ze([],r.errorHandler)(i,()=>s.handler(i,a))).res,"handler"),o[sr]=s.handler),n.#i(s.method,s.path,o,s.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=C(this._basePath,t),r}onError=c(t=>(this.errorHandler=t,this),"onError");notFound=c(t=>(this.#r=t,this),"notFound");mount(t,r,n){let s,o;n&&(typeof n=="function"?o=n:(o=n.optionHandler,n.replaceRequest===!1?s=c(l=>l,"replaceRequest"):s=n.replaceRequest));let i=o?l=>{let d=o(l);return Array.isArray(d)?d:[d]}:l=>{let d;try{d=l.executionCtx}catch{}return[l.env,d]};s||=(()=>{let l=C(this._basePath,t),d=l==="/"?0:l.length;return u=>{let m=new URL(u.url);return m.pathname=this.getPath(u).slice(d)||"/",new Request(m,u)}})();let a=c(async(l,d)=>{let u=await r(s(l.req.raw),...i(l));if(u)return u;await d()},"handler");return this.#i("ALL",C(t,"*"),a),this}#i(t,r,n,s){r=C(this._basePath,r);let o={basePath:s!==void 0?C(this._basePath,s):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,o]),this.routes.push(o)}#n(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#s(t,r,n,s){if(s==="HEAD")return(async()=>new Response(null,await this.#s(t,r,n,"GET")))();let o=this.getPath(t,{env:n}),i=this.router.match(s,o),a=new Qe(t,{path:o,matchResult:i,env:n,executionCtx:r,notFoundHandler:this.#r});if(i[0].length===1){let d;try{d=i[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#n(u,a)}return d instanceof Promise?d.then(u=>u||(a.finalized?a.res:this.#r(a))).catch(u=>this.#n(u,a)):d??this.#r(a)}let l=Ze(i[0],this.errorHandler,this.#r);return(async()=>{try{let d=await l(a);if(!d.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return d.res}catch(d){return this.#n(d,a)}})()}fetch=c((t,...r)=>this.#s(t,r[1],r[0],t.method),"fetch");request=c((t,r,n,s)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,s):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${C("/",t)}`,r),n,s)),"request");fire=c(()=>{addEventListener("fetch",t=>{t.respondWith(this.#s(t.request,t,void 0,t.request.method))})},"fire")};g();g();var I=c(()=>Object.create(null),"createNullObject");g();var Me=[];function et(e,t){let r=this.buildAllMatchers(),n=c(((s,o)=>{let i=r[s]||r.ALL,a=i[2][o];if(a)return a;let l=o.match(i[0]);if(!l)return[[],Me];let d=l.indexOf("",1);return[i[1][d],l]}),"match");return this.match=n,n(e,t)}c(et,"match");g();var rt="[^/]+";var nt="(?:|/.*)",j=Symbol(),cr=new Set(".\\+*[^]$()");function On(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===".*"||e==="(?:|/.*)"?t==="(?:|/.*)"?-1:1:t===".*"||t==="(?:|/.*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}c(On,"compareKey");var lr=class tt{static{c(this,"Node")}#t;#e;#r=I();insert(t,r,n,s,o){let i=this;for(let a=0,l=t.length;a<l;a++){let d=t[a],u=d.length===1?d==="*"?a===l-1?["","",".*"]:["","",rt]:null:d==="/*"?["","",nt]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),m;if(u){let p=u[1],f=u[2]||"[^/]+";if(p&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&cr.has(f)))throw j;if(m=i.#r[f],!m){if(f!==".*"&&f!=="(?:|/.*)"){for(let h in i.#r)if((f.length>1||h.length>1)&&h!==".*"&&h!=="(?:|/.*)")throw j}m=i.#r[f]=new tt}p!==""&&(m.#e??=s.varIndex++,n.push([p,m.#e]))}else if(m=i.#r[d],!m){for(let p in i.#r)if(p.length>1&&p!==".*"&&p!=="(?:|/.*)")throw j;m=i.#r[d]=new tt}i=m}if(i.#t!==void 0)throw j;i.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(On).map(r=>{let n=this.#r[r],s=n.buildRegExpStr();return s===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:cr.has(r)?`\\${r}`:r)+s}).filter(Boolean);return typeof this.#t=="number"&&this.#t!==-1&&t.unshift(`#${this.#t}`),t.length===0?"":t.length===1?t[0]:"(?:"+t.join("|")+")"}};g();var st=class{static{c(this,"Trie")}#t={varIndex:0};#e=new lr;#r=0;paths=I();insert(e,t){if(t){this.#e.insert(e.split(""),0,[],this.#t,!0);return}let r=[],n=[],s=e;for(let i=0;;){let a=!1;if(s=s.replace(/\{[^}]+\}/g,l=>{let d=`@\\${i}`;return n[i]=[d,l],i++,a=!0,d}),!a)break}let o=s.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let i=n.length-1;i>=0;i--){let[a]=n[i];for(let l=o.length-1;l>=0;l--)if(o[l].indexOf(a)!==-1){o[l]=o[l].replace(a,n[i][1]);break}}this.#e.insert(o,this.#r,r,this.#t,!1),this.paths[e]=[this.#r++,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(s,o,i)=>o!==void 0?(r[++t]=Number(o),"$()"):(i!==void 0&&(n[Number(i)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var dr=I();function ur(e){return dr[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?nt:t==="*"?".*":`/:${rt}`)}$`)}c(ur,"buildWildcardRegExp");function Te(e,t){for(let r of Object.keys(e).sort((n,s)=>s.length-n.length))if(ur(r).test(t))return[...e[r]]}c(Te,"findMiddleware");var Ne=class{static{c(this,"RegExpRouter")}name="RegExpRouter";#t;#e;#r;constructor(){this.#t={ALL:I()},this.#e={ALL:I()},this.#r={ALL:new st}}#i(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===j?new Se(t):r}}add(e,t,r){let n=this.#t,s=this.#e;if(!n)throw new Error(Ie);if(!n[e]){this.#r[e]=new st;for(let a of[n,s]){a[e]=I();for(let l in a.ALL)a[e][l]=[...a.ALL[l]],this.#i(e,l)}}t==="/*"&&(t="*");let o=e==="ALL"?Object.keys(n):[e];if(/\*$/.test(t)){let a=ur(t);for(let l of o)n[l][t]||(this.#i(l,t),n[l][t]=Te(n[l],t)||Te(n.ALL,t)||[]);for(let l of[n,s])for(let d of o)for(let u in l[d])a.test(u)&&l[d][u].push([r,t]);return}let i=_e(t)||[t];for(let a of i)for(let l of o)s[l][a]||(this.#i(l,a),s[l][a]=Te(n[l],a)||Te(n.ALL,a)||[]),s[l][a].push([r,a])}match=et;buildAllMatchers(){let e=I();for(let t of Object.keys(this.#e))e[t]=this.#n(t);return this.#t=this.#e=this.#r=void 0,dr=I(),e}#n(e){let t=this.#t[e],r=this.#e[e],n=this.#r[e],s=I(),o=[],[i,a,l]=n.buildRegExp();for(let d of[t,r])for(let u in d){let m=d[u],p=n.paths[u];if(!p){s[u]=[m.map(([f])=>[f,I()]),Me];continue}o[p[0]]=m.map(([f,h])=>[f,n.paths[h][1].reduceRight((y,[w],R)=>(y[w]=l[p[1][R][1]],y),I())])}return[i,a.map(d=>o[d]),s]}};g();g();g();var fr=class{static{c(this,"SmartRouter")}name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(Ie);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,s=r.length,o=0,i;for(;o<s;o++){let a=r[o];try{for(let l=0,d=n.length;l<d;l++)a.add(...n[l]);i=a.match(e,t)}catch(l){if(l instanceof Se)continue;throw l}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===s)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,i}get activeRouter(){if(this.#e||this.#t.length!==1)throw new Error("No active router has been determined yet.");return this.#t[0]}};g();g();var it=I(),kn=0,mr=class pr{static{c(this,"Node")}#t=[];#e=I();#r=[];#i;#n=it;insert(t,r,n){let s=this,o=Xt(r),i=new Set,a=0;for(let l of o){let d=o[++a],u=Jt(l,d)||(d===void 0&&l&&l.indexOf("*")===l.length-1?l:null),m=Array.isArray(u),p=m?u[0]:u||l,f=s.#e[p]||=new pr;u&&!f.#i&&(f.#i=u,s.#r.push(f)),s=f,m&&i.add(u[1])}s.#t.push({[t]:{handler:n,possibleKeys:[...i],score:++kn}})}#s(t,r,n,s,o){for(let i=0,a=r.#t.length;i<a;i++){let l=r.#t[i],d=l[n]||l.ALL;if(d){d.params=I(),t.push(d);for(let u=0,m=d.possibleKeys.length;u<m;u++){let p=d.possibleKeys[u];d.params[p]=o?.[p]&&!u?o[p]:s[p]??o?.[p]}}}}search(t,r){let n=[];this.#n=it;let s=[this],o=Xe(r),i=[],a=o.length,l=null;for(let d=0;d<a;d++){let u=o[d],m=d===a-1,p=[];for(let h=0,y=s.length;h<y;h++){let w=s[h],R=w.#e[u];R&&(R.#n=w.#n,m?(R.#e["*"]&&this.#s(n,R.#e["*"],t,w.#n),this.#s(n,R,t,w.#n)):p.push(R));for(let E of w.#r){let A=E.#i,b=w.#n===it?{}:{...w.#n};if(typeof A=="string"){(A==="*"||u.startsWith(A.slice(0,-1)))&&(this.#s(n,E,t,w.#n),A==="*"&&(E.#n=b,p.push(E)));continue}let[,_,M]=A;if(!(!u&&M===!0)){if(M!==!0){if(!l){l=[];let x=r[0]==="/"?1:0;for(let P=0;P<a;P++)l[P]=x,x+=o[P].length+1}let O=r.slice(l[d]),N=M.exec(O);if(N){b[_]=N[0],this.#s(n,E,t,w.#n,b),N[0].length===O.length&&E.#e["*"]&&this.#s(n,E.#e["*"],t,w.#n,b);for(let x in E.#e){E.#n=b;let P=N[0].match(/\//g)?.length??0;(i[P]||=[]).push(E);break}continue}}(M===!0||M.test(u))&&(b[_]=u,m?(this.#s(n,E,t,b,w.#n),E.#e["*"]&&this.#s(n,E.#e["*"],t,b,w.#n)):(E.#n=b,p.push(E)))}}}let f=i.shift();s=f?p.concat(f):p}return n[1]&&n.sort((d,u)=>d.score-u.score),[n.map(({handler:d,params:u})=>[d,u])]}};var ot=class{static{c(this,"TrieRouter")}name="TrieRouter";#t=new mr;add(e,t,r){for(let n of _e(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};g();var at=class extends or{static{c(this,"Hono")}constructor(e={}){super(e),this.router=e.router??new fr({routers:[new Ne,new ot]})}};g();g();g();g();g();g();g();g();g();g();function ee(e){return typeof e=="string"?e:null}c(ee,"asString");var Cn=new at,jn=5e4,z=5e3,xe=5*1024*1024,$n=16*1024,Un=new Set(["from","to","cc","bcc","subject","reply-to","date","message-id","in-reply-to","references","mime-version","content-type","content-transfer-encoding","content-disposition"]);function Fn(e){let t=0,r=!1;for(let n=0;n<e.byteLength;){let s=n;for(;s<e.byteLength&&e[s]!==10;)s++;let o=s>n&&e[s-1]===13?s-1:s;if(o===n)return!0;if(e[n]!==32&&e[n]!==9){let i=n;for(;i<o&&e[i]!==58;)i++;let a=new TextDecoder().decode(e.subarray(n,i)).toLowerCase();r=i<o&&!Un.has(a)}if(r&&(t+=o-n+2,t>$n))return!1;n=s+1}return!0}c(Fn,"customMimeHeaderBytesWithinLimit");var hr=50,yr=320,wr=320;function te(e){let t=e.EMAIL_SENDER_DOMAIN;if(typeof t!="string")return null;let r=t.trim().toLowerCase();return r.length>0?r:null}c(te,"readSenderDomain");var Hn=/[.*+?^${}()|[\]\\]/g;function Bn(e){return e.replace(Hn,"\\$&")}c(Bn,"escapeRegExp");var Er=new Map;function Gn(e){let t=Er.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${Bn(e)}$`);return Er.set(e,r),r}c(Gn,"strictFromRe");var zn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function v(e,t=200){return e.slice(0,t).replace(zn," ")}c(v,"sanitizeForLog");var Vn=128;function re(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}c(re,"bytesToStream");var br=10,Oe=13,Ar=32,_r=9,qn=58,ke=[102,114,111,109];function Wn(e,t,r){if(r-t<=ke.length)return-1;for(let s=0;s<ke.length;s++)if((e[t+s]|32)!==ke[s])return-1;let n=t+ke.length;for(;n<r&&(e[n]===Ar||e[n]===_r);)n++;return n<r&&e[n]===qn?n+1:-1}c(Wn,"fromValueStart");var Xn={missing:"the message has no From header",multiple:"the message has more than one From header",malformed:"the From header must hold a single mailbox"};function dt(e){let t=e.byteLength,r=0,n=-1,s=-1,o=!1,i=!1,a=e.indexOf(Oe),l=0;for(;l<t;){let m=e.indexOf(br,l),f=m===-1?t:m;if(f>l&&e[f-1]===Oe&&f--,f===l)break;if(a!==-1&&a<l&&(a=e.indexOf(Oe,l)),a!==-1&&a<f)return{ok:!1,reason:"malformed"};if(e[l]===Ar||e[l]===_r)i&&(s=f,o=!0);else{let h=Wn(e,l,f);i=h!==-1,i&&(r++,n=h,s=f,o=!1)}l=m===-1?t:m+1}if(r===0)return{ok:!1,reason:"missing"};if(r>1)return{ok:!1,reason:"multiple"};let d=e.subarray(n,s);if(o){d=e.slice(n,s);let m=0;for(let p=0;p<d.length;p++){let f=d[p];f!==Oe&&f!==br&&(d[m++]=f)}d=d.subarray(0,m)}let u=Jn(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}c(dt,"readMimeFromAddrSpec");function Jn(e){let t=!1,r=!1,n=-1,s=-1,o=-1;for(let a=0;a<e.length;a++){let l=e[a];if(t){r?r=!1:l==="\\"?r=!0:l==='"'&&(t=!1);continue}switch(l){case'"':if(n!==-1)return null;t=!0;break;case"<":if(n!==-1)return null;n=a;break;case">":if(n===-1||s!==-1)return null;s=a;break;case"@":o===-1&&(o=a);break;case",":case";":case":":case"(":case")":case"[":case"]":case"\\":return null;default:break}}if(t)return null;let i;if(n===-1)i=e.trim();else{if(s===-1||e.slice(s+1).trim().length!==0||o!==-1&&o<n)return null;i=e.slice(n+1,s)}return/^[\x21-\x7e]+$/.test(i)?i:null}c(Jn,"singleMailboxAddrSpec");Cn.post("/send",async e=>{let t=be(jn),r=e.get("projectId"),n=e.get("body"),s=ee(n.from),o=ee(n.mimeBase64),i=ee(n.requestId),a=i===null?"unknown":v(i,Vn),l=ee(n.idempotencyKey);if(l!==null&&(l.length===0||l.length>128||!/^[\x20-\x7e]+$/.test(l)))return e.json({ok:!1,error:{code:"INVALID_TO",message:"invalid idempotency key"}},400);let d=l??(i&&i.length<=128&&/^[\x20-\x7e]+$/.test(i)?i:crypto.randomUUID()),u=Array.isArray(n.recipients)?n.recipients:null;if(!s||!o||!u)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"invalid body"}},400);if(u.length>hr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`too many recipients (max ${hr}, got ${u.length})`}},413);if(s.length>wr)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${wr} characters`}},413);let m=te(e.env);if(!m)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sender domain is not configured"}},502);let p=[],f=new Set;for(let S of u){if(typeof S!="string")continue;if(S.length>yr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${yr} characters`}},413);let T=S.trim().toLowerCase();!T||f.has(T)||(f.add(T),p.push(T))}if(p.length===0)return e.json({ok:!1,error:{code:"INVALID_TO",message:"no recipients"}},200);if(o.length>Math.ceil(xe*4/3)+4)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${xe} bytes (base64 length ${o.length})`}},413);let h;try{h=Kn(o)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"invalid base64 mime"}},400)}if(h.byteLength>xe)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${xe} bytes (got ${h.byteLength})`}},413);if(!Fn(h))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let y=s.indexOf("@"),w=y===-1?"":s.slice(y+1).toLowerCase();if(w!==""&&w!==m)return Yn(e,r,s,w,m,p,h,a,d,t);let R=e.env.SEND_EMAIL;if(typeof R?.send!="function")return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sending is not configured"}},502);let E=s.split("@")[0]?.split("+")[0]??"";if(!/^[\x21-\x7e]+$/.test(s))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let A=s.toLowerCase();if(!Gn(m).test(A))return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${m}`}},200);if((A.slice(0,A.indexOf("@")).split("+")[0]??"")!==E.toLowerCase())return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${m}`}},200);let M=Ir(e,h,s);if(M)return M;let O=await Sr(e,t,{projectId:r,operationKey:d,from:s,recipients:p,raw:h,transport:"binding"});if(O instanceof Response)return O;let{admission:N,deliveries:x}=O,P=N.recipients.filter(S=>S.state==="reserved").map(S=>S.recipient);for(let S=0;S<P.length;S++){let T=P[S];if(t.expired(z)){let F=P.slice(S),W=await ct(e.env,N.operationId,F,t.remainingMs());for(let ie of F)x.push({recipient:ie,ok:!1,state:W?"cancelled":"outcome_unknown",error:W?{code:"UPSTREAM_ERROR",message:"email batch deadline elapsed before provider submission"}:{code:"OUTCOME_UNKNOWN",message:"could not cancel unstarted email attempt"}});break}try{await K(e.env,N.operationId,[T],t.remainingMs(z))}catch{let F=await ct(e.env,N.operationId,[T],t.remainingMs());x.push({recipient:T,ok:!1,state:F?"cancelled":"outcome_unknown",error:F?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});continue}try{let F=new Dn(s,T,re(h)),W=await t.run(()=>R.send(F),z),ie=typeof W?.messageId=="string"?W.messageId:"";try{await k(e.env,N.operationId,[T],"provider_accepted",{providerReference:ie},t.remainingMs())}catch{x.push({recipient:T,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider accepted email but outcome could not be recorded"}});continue}x.push({recipient:T,ok:!0,state:"provider_accepted",messageId:ie})}catch{try{await k(e.env,N.operationId,[T],"outcome_unknown",{errorCode:"OUTCOME_UNKNOWN"},t.remainingMs())}catch{}x.push({recipient:T,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"}})}}return Mr(r,a,x),x.some(S=>!S.ok)?e.json({ok:!1,operationId:N.operationId,deliveries:x},200):e.json({ok:!0,operationId:N.operationId,ids:x.map(S=>({recipient:S.recipient,messageId:S.messageId,state:"provider_accepted"}))})});var Rr=64*1024;async function ut(e,t=3e4){let r=new AbortController,n=Date.now()+Math.min(3e4,t),s=JSON.stringify({from:e.from,recipients:e.recipients,mime_message:e.mimeMessage}),o=c(async m=>{let p=n-Date.now();if(p<=0)throw r.abort(),new Error("email sending request timed out");let f=m(),h;try{return await Promise.race([f,new Promise((y,w)=>{h=setTimeout(()=>{r.abort(),w(new Error("email sending request timed out"))},p)})])}finally{h!==void 0&&clearTimeout(h)}},"beforeDeadline"),i=await o(()=>fetch(`https://api.cloudflare.com/client/v4/accounts/${e.accountId}/email/sending/send_raw`,{method:"POST",headers:{authorization:`Bearer ${e.bearer}`,"content-type":"application/json"},body:s,signal:r.signal}));if(!i.ok)return i.body?.cancel().catch(()=>{}),{ok:!1,status:i.status};let a=i.headers.get("content-length");if(a!==null&&(!/^\d+$/.test(a)||Number(a)>Rr))throw i.body?.cancel().catch(()=>{}),new Error("email sending API response too large");let l=i.body?.getReader();if(!l)throw new Error("email sending API response unreadable");let d=new Uint8Array(Rr),u=0;try{for(;;){let m=await o(()=>l.read());if(m.done)break;if(u+m.value.byteLength>d.byteLength)throw new Error("email sending API response too large");d.set(m.value,u),u+=m.value.byteLength}if(a!==null&&u!==Number(a))throw new Error("email sending API response length mismatch");return{ok:!0,data:JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(d.subarray(0,u)))}}finally{l.cancel().catch(()=>{});try{l.releaseLock()}catch{}}}c(ut,"requestSendRaw");function Pe(e){if(!Array.isArray(e))return null;let t=new Set;for(let r of e){if(typeof r!="string")return null;t.add(r.toLowerCase())}return t}c(Pe,"readSendRawAddressList");function ft(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=Pe(t.delivered),n=Pe(t.permanent_bounces),s=Pe(t.queued),o=Pe(t.suppressed_recipients);return!r||!n||!s||!o||typeof t.message_id!="string"||t.message_id===""?null:{delivered:r,messageId:t.message_id,permanentBounces:n,queued:s,suppressedRecipients:o}}c(ft,"parseSendRawResult");function mt(e,t){let r=t.toLowerCase(),n=[e.delivered.has(r),e.queued.has(r),e.permanentBounces.has(r),e.suppressedRecipients.has(r)];return n.filter(Boolean).length!==1?"outcome_unknown":n[0]||n[1]?"provider_accepted":n[2]?"permanent_bounce":"suppressed"}c(mt,"classifySendRawRecipient");async function Yn(e,t,r,n,s,o,i,a,l,d){if(!/^[\x21-\x7e]+$/.test(r))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let u=Ir(e,i,r);if(u)return u;let m;try{m=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(i)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"mime must be valid UTF-8"}},400)}let p=await Sr(e,d,{projectId:t,operationKey:l,from:r,recipients:o,raw:i,transport:"send_raw"});if(p instanceof Response)return p;let{admission:f,deliveries:h}=p;if(o=f.recipients.filter(b=>b.state==="reserved").map(b=>b.recipient),o.length===0)return lt(e,f.operationId,h);let y=await we(e.env,n,t,d.remainingMs(z));if(!y)return await k(e.env,f.operationId,o,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"could not lease the domain credential"}},502);if(f.accountId!==y.accountId)return await k(e.env,f.operationId,o,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"email domain changed during admission"}},503);try{await K(e.env,f.operationId,o,d.remainingMs(z))}catch{let b=await ct(e.env,f.operationId,o,d.remainingMs());for(let _ of o)h.push({recipient:_,ok:!1,state:b?"cancelled":"outcome_unknown",error:b?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return lt(e,f.operationId,h)}let w=null,R="failed",E=null,A=null;try{A=await ut({accountId:y.accountId,bearer:ye(y),from:r,recipients:o,mimeMessage:m},d.remainingMs(z))}catch{w={code:"UPSTREAM_ERROR",message:"email sending request failed"},R="outcome_unknown"}if(A)if(!A.ok)w={code:A.status===429?"QUOTA_EXCEEDED":"UPSTREAM_ERROR",message:`email sending API returned ${A.status}`},R=A.status>=500||A.status===408?"outcome_unknown":"failed";else{let b=A.data,_=typeof b=="object"&&b!==null?b.success:void 0;_===!1?w={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:_!==!0?(w={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"):(E=ft(b.result),E||(w={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"))}for(let b of o){if(w){h.push({recipient:b,ok:!1,state:R,error:w});continue}let _=mt(E,b);_==="permanent_bounce"?h.push({recipient:b,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${b}' permanently bounced`}}):_==="suppressed"?h.push({recipient:b,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${b}' is on the suppression list`}}):_==="outcome_unknown"?h.push({recipient:b,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):h.push({recipient:b,ok:!0,state:"provider_accepted",messageId:E.messageId})}for(let b of h.filter(_=>f.recipients.some(M=>M.recipient===_.recipient&&M.state==="reserved")))try{await k(e.env,f.operationId,[b.recipient],b.ok?"provider_accepted":b.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:b.messageId,errorCode:b.ok?void 0:b.state==="outcome_unknown"?"OUTCOME_UNKNOWN":w?.code??b.error?.code},d.remainingMs()),b.state=b.ok?"provider_accepted":b.state==="outcome_unknown"?"outcome_unknown":"failed",b.state==="outcome_unknown"&&!b.ok&&(b.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{b.ok=!1,b.state="outcome_unknown",b.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return Mr(t,a,h),h.some(b=>!b.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:h},200):e.json({ok:!0,operationId:f.operationId,ids:h.map(b=>({recipient:b.recipient,messageId:b.messageId,state:"provider_accepted"}))})}c(Yn,"sendViaCustomDomain");async function vr(e,t){console.log(`[email-recv] ${e} ${v(t.from,320)} -> ${v(t.to,320)} ${t.status} (${t.byteSize}B) @${Date.now()}`)}c(vr,"recordInboundDelivery");function Ir(e,t,r){let n=dt(t);if(n.ok&&n.addrSpec.toLowerCase()===r.toLowerCase())return null;let s=n.ok?"the From header address does not match the envelope sender":Xn[n.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${s}`}},403)}c(Ir,"refuseMimeFromMismatch");async function Sr(e,t,r){let{projectId:n,operationKey:s,from:o,recipients:i,raw:a,transport:l}=r,d;try{d=await he(e.env,{projectId:n,kind:"direct",key:s,digest:await ge("direct",o,i,a),from:o,recipients:i,transport:l},t.remainingMs(z))}catch(m){let p=m instanceof Error&&m.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:p?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:p?"idempotency key has different content":"email admission unavailable"}},p?409:503)}let u=d.recipients.filter(m=>m.state!=="reserved").map(m=>({recipient:m.recipient,ok:m.state==="provider_accepted",state:m.state,messageId:m.providerReference??void 0,error:m.state==="provider_accepted"?void 0:{code:m.errorCode??(m.state==="outcome_unknown"||m.state==="attempt_started"?"OUTCOME_UNKNOWN":m.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:m.state==="outcome_unknown"||m.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":m.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(d.replay){for(let m of d.recipients.filter(p=>p.state==="reserved"))u.push({recipient:m.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return lt(e,d.operationId,u)}return{admission:d,deliveries:u}}c(Sr,"admitDirectSend");async function ct(e,t,r,n){try{let s=await k(e,t,r,"cancelled",{},n);return r.every(o=>s.recipients.some(i=>i.recipient===o&&i.state==="cancelled"))}catch{return!1}}c(ct,"cancelUnstartedRecipients");function lt(e,t,r){return r.length===0?e.json({ok:!1,operationId:t,error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved"}},200):r.some(n=>!n.ok)?e.json({ok:!1,operationId:t,deliveries:r},200):e.json({ok:!0,operationId:t,ids:r.map(n=>({recipient:n.recipient,messageId:n.messageId??"",state:n.state}))},200)}c(lt,"emailActionResponse");function Mr(e,t,r){for(let n of r){let s=n.ok?"sent":n.error?.code??"unknown_error",o=n.messageId??"";console.log(`[email-log] ${e} ${t} ${v(n.recipient,320)} ${s} ${o} @${Date.now()}`)}}c(Mr,"logSend");function Kn(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}c(Kn,"base64Decode");function ne(e,t){switch(typeof e){case"string":return v(e,t);case"number":case"boolean":case"undefined":return String(e);case"object":return e===null?"null":v(Object.prototype.toString.call(e),64);default:return`[${typeof e}]`}}c(ne,"describeUntrusted");function Qn(e){return{routeId:e.routeId,routeGeneration:e.routeGeneration,connectionId:e.connectionId,addressing:e.addressing,domain:e.domain,projectSlug:e.slug}}c(Qn,"receiptRouteFence");var L=10*1024*1024,se=1024,ht=128*1024,Zn=1e3,Tr=100,Dr=320,Nr=32,De=1024,xr=5*1024*1024,Or=8*1024*1024,es=15e3,Ce=class extends Error{constructor(r){super(`inbound message exceeds ${L} bytes (got ${r})`);this.size=r;this.name="InboundTooLargeError"}size;static{c(this,"InboundTooLargeError")}},je=class extends Error{static{c(this,"InboundTooManyHeadersError")}constructor(){super(`inbound message carries more than ${se} headers`),this.name="InboundTooManyHeadersError"}},$e=class extends Error{static{c(this,"InboundHeadersTooLargeError")}constructor(){super(`inbound headers exceed ${ht} bytes`),this.name="InboundHeadersTooLargeError"}};function pt(e){return typeof e=="string"&&e.length<=Dr&&(0,Lr.validate)(e)}c(pt,"isValidEmailAddress");function $(e){return ne(e,Dr)}c($,"logAddress");function ts(e){if(typeof e!="object"||e===null)return console.error("[email-router] action list dropped: forward headers is not a plain object"),!1;let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return console.error("[email-router] action list dropped: forward headers is not a plain object"),!1;let r=Object.keys(e);if(r.length>Nr)return console.error(`[email-router] action list dropped: forward has ${r.length} headers (max ${Nr})`),!1;for(let n of r){let s=e[n];if(n.length>De)return console.error(`[email-router] action list dropped: forward header name exceeds ${De} characters`),!1;if(typeof s!="string")return console.error(`[email-router] action list dropped: forward header "${v(n,64)}" value is not a string`),!1;if(s.length>De)return console.error(`[email-router] action list dropped: forward header "${v(n,64)}" value exceeds ${De} characters`),!1}return!0}c(ts,"forwardHeadersWithinBounds");function rs(e,t){if(!/^[\x21-\x7e]+$/.test(e))return!1;let r=e.toLowerCase(),n=r.indexOf("@");return n<=0?!1:r.slice(n+1)!==t.domain||t.customDomain?!0:r.slice(0,n).split("+")[0]===t.slug}c(rs,"isPermittedReplySender");async function Cr(e,t,r,n){let s=te(t)??"void email",o=String(e.to??"").toLowerCase(),i=o.split("@")[0]??"",a=i.indexOf("+"),l=a===-1?i:i.slice(0,a),d=o.indexOf("@"),u=d===-1?"":o.slice(d+1);if(!l){e.setReject(`${s}: missing project slug in recipient`);return}if(n.addressing!=="custom"&&kt(l)){e.setReject(`${s}: "${v(l,64)}" is a reserved platform address`);return}if(!n.projectId||!n.workerName||!n.deploymentId||n.domain?.toLowerCase()!==u||n.addressing==="shared"&&n.slug.toLowerCase()!==l){e.setReject(`${s}: authoritative route mismatch`);return}let m=n.workerName,p=n.projectId,f;try{f=n.limits?t.DISPATCH.get(m,{},{limits:n.limits}):t.DISPATCH.get(m)}catch(E){throw console.error(`[email-router] DISPATCH.get(${v(m,320)}) failed:`,E),new Error("email worker temporarily unavailable")}if(typeof e.rawSize=="number"&&e.rawSize>L){e.setReject(`${s}: message too large (max ${L} bytes)`);return}let h;try{h=await is(e),n.addressing==="custom"&&(h.viaDomain=u)}catch(E){if(E instanceof Ce){e.setReject(`${s}: message too large (max ${L} bytes)`);return}if(E instanceof je){e.setReject(`${s}: too many headers (max ${se})`);return}if(E instanceof $e){e.setReject(`${s}: headers too large (max ${ht} bytes)`);return}console.error(`[email-router] failed to read message body for ${v(l,64)}:`,E),e.setReject(`${s}: could not read inbound message body`);return}let y=crypto.randomUUID(),w={projectId:p,receiptId:y,transport:"native"},R;try{await G(t,y,p,"received",Qn(n))}catch{throw new Error("email admission temporarily unavailable")}try{R=(await qe(f,t,{projectId:p,deploymentId:n.deploymentId,envelope:h,receiptId:y})).actions}catch(E){await G(t,y,p,"handler_failed").catch(()=>{});let A=E instanceof Error?E.message.slice(0,320):ne(E,320);throw console.error(`[email-router] dispatch to ${v(m,320)} failed:`,A),new Error("email handler execution unresolved")}try{await G(t,y,p,"handler_completed")}catch{console.error("[email-router] handler completed but receipt status could not be saved");return}try{await $r(t,e,R,w,{customDomain:n.addressing==="custom",slug:n.slug.toLowerCase(),domain:u})}catch{console.error("[email-router] action execution unresolved",y);return}r.waitUntil(gt(t,p,e,R))}c(Cr,"routeInbound");async function jr(e,t,r){let{stub:n,projectId:s,domain:o,envelope:i,authoritative:a,receiptId:l}=r;if(a.projectId!==s||!a.workerName||!a.slug||a.domain?.toLowerCase()!==o)return{reject:!0};let d=a.slug,u=a.workerName,m=ns(i),p={projectId:s,receiptId:l,transport:"relay"},f;try{f=(await qe(n,e,{projectId:s,deploymentId:a.deploymentId,envelope:i,receiptId:l})).actions}catch(h){await G(e,l,s,"handler_failed").catch(()=>{});let y=h instanceof Error?h.message.slice(0,320):ne(h,320);return console.error(`[email-relay] dispatch to ${v(u,320)} failed:`,y),t.waitUntil(gt(e,s,m.message,[{type:"reject",reason:"dispatch-error"}])),{reject:!0,temporary:!0}}try{await G(e,l,s,"handler_completed")}catch{return console.error("[email-relay] handler completed but receipt status could not be saved"),{reject:!1}}try{await $r(e,m.message,f,p,{customDomain:a.addressing==="custom",slug:d.toLowerCase(),domain:o})}catch{return console.error("[email-relay] action execution unresolved",l),{reject:!1}}return t.waitUntil(gt(e,s,m.message,f)),{reject:m.rejectedReason()!==null}}c(jr,"routeRelayed");function ns(e){let t=null;return{message:{from:e.from,to:e.to,rawSize:e.rawSize,headers:new Headers(e.headers),raw:re(e.raw),setReject(n){t=n},async forward(n,s){throw new U("relayed forward requires a native email event")}},rejectedReason:c(()=>t,"rejectedReason")}}c(ns,"createRelayedMessage");async function ss(e,t,r,n,s){let o=r.slice(r.indexOf("@")+1).toLowerCase();if(o===te(e)){let l=e.SEND_EMAIL;if(!l||typeof l.send!="function")throw new Error("shared email binding is unavailable");return async d=>(await l.send(new Pr(r,d,re(n))))?.messageId}let i=await we(e,o,t);if(!i||s&&i.accountId!==s)throw new Error("could not lease the domain credential");let a=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(n);return async(l,d=3e4)=>{let u;try{u=await ut({accountId:i.accountId,bearer:ye(i),from:r,recipients:[l],mimeMessage:a},d)}catch{throw new Error("email sending request failed")}if(!u.ok)throw u.status>=500||u.status===408?new Error("email sending API outcome unknown"):new U(`email sending API returned ${u.status}`);let m=u.data;if(typeof m!="object"||m===null||!("success"in m))throw new Error("email sending API response invalid");if(m.success===!1)throw new U("email sending API refused the message");if(m.success!==!0)throw new Error("email sending API response invalid");let p=ft(m.result);if(!p)throw new Error("email sending API response invalid");let f=mt(p,l);if(f==="permanent_bounce")throw new U("recipient permanently bounced");if(f==="suppressed")throw new U("recipient is on the suppression list");if(f==="outcome_unknown")throw new Error("email sending API did not classify the recipient");return p.messageId}}c(ss,"prepareRelayedReply");async function gt(e,t,r,n){if(!t){console.error(`[email-router] cannot log inbound delivery: routing entry has no projectId (to=${v(String(r.to??""),320)})`);return}let s=n.some(o=>o&&typeof o=="object"&&o.type==="reject")?"rejected":n.length===0?"accepted":"handled";try{await vr(t,{from:String(r.from??""),to:String(r.to??""),byteSize:r.rawSize??0,status:s})}catch(o){console.error("[email-router] log-recv failed:",o)}}c(gt,"logRecv");async function is(e){let t=[],r=0,n=new TextEncoder;for(let i of e.headers){if(t.length>=se)throw new je;if(r+=n.encode(i[0]).byteLength+n.encode(i[1]).byteLength,r>ht)throw new $e;t.push(i)}let s=await os(e.raw),o=Object.fromEntries(t);return{from:String(e.from??""),to:String(e.to??""),headers:o,raw:s,rawSize:e.rawSize??s.byteLength}}c(is,"buildEnvelope");async function os(e){let t=e.getReader(),r=[],n=0,s=Date.now()+es;try{for(;;){let a=s-Date.now();if(a<=0)throw new Error("inbound message stream timed out");let l,{value:d,done:u}=await Promise.race([t.read(),new Promise((m,p)=>{l=setTimeout(()=>p(new Error("inbound message stream timed out")),a)})]).finally(()=>{l!==void 0&&clearTimeout(l)});if(u)break;if(n+=d.byteLength,n>L)throw new Ce(n);r.push(d)}}catch(a){throw t.cancel().catch(()=>{}),a}finally{try{t.releaseLock()}catch{}}let o=new Uint8Array(n),i=0;for(let a of r)o.set(a,i),i+=a.byteLength;return o}c(os,"readStreamToBytes");var U=class extends Error{static{c(this,"DefinitiveEmailActionError")}};async function as(e,t){if(e.length>Tr)return console.error(`[email-router] action list dropped: ${e.length} actions returned (max ${Tr})`),null;let r=[],n=0;for(let s of e){if(!s||typeof s!="object")return console.error(`[email-router] dropping non-object action: ${ne(s,320)}`),null;if(s.type==="reject"){let o=typeof s.reason=="string"?s.reason:"",i=o.length>0?v(o,Zn):"rejected by handler";return r.push({type:"reject",reason:i}),r}if(s.type==="forward"){if(!pt(s.to))return console.error(`[email-router] forward dropped: invalid "to" address ${$(s.to)}`),null;let o;if(s.headers){if(!ts(s.headers))return null;try{o=new Headers(s.headers)}catch(i){return console.error("[email-router] action list dropped: forward headers invalid:",i instanceof Error?v(i.message,320):v(String(i),320)),null}}r.push({type:"forward",to:s.to,headers:o})}else if(s.type==="reply"){if(!pt(s.from)||!pt(s.to))return console.error(`[email-router] reply dropped: invalid address (from=${$(s.from)} to=${$(s.to)})`),null;if(!rs(s.from,t))return console.error(`[email-router] reply dropped: sender not owned by project "${v(t.slug,64)}" (from=${$(s.from)})`),null;if(!(s.raw instanceof Uint8Array))return console.error(`[email-router] reply dropped: raw is not a Uint8Array (from=${$(s.from)})`),null;let o=s.raw.byteLength;if(o>xr)return console.error(`[email-router] reply dropped: raw is ${o} bytes (max ${xr}) (from=${$(s.from)})`),null;if(n+o>Or)return console.error(`[email-router] reply dropped: cumulative reply bytes ${n+o} exceed this delivery's budget of ${Or} (from=${$(s.from)})`),null;let i=dt(s.raw);if(!i.ok||i.addrSpec.toLowerCase()!==s.from.toLowerCase())return console.error(`[email-router] reply dropped: MIME From is not the envelope sender (from=${$(s.from)}, ${i.ok?"header names another address":i.reason})`),null;n+=o,r.push({type:"reply",from:s.from,to:s.to,raw:s.raw})}else return console.warn(`[email-router] dropping unknown action type: ${ne(s.type,320)}`),null}return r}c(as,"validateActions");async function $r(e,t,r,n,s){let o=await as(r,s);if(o===null){await G(e,n.receiptId,n.projectId,"actions_rejected").catch(()=>{console.error("[email-router] could not record rejected actions")});return}await cs(e,t,o,n)}c($r,"enactActions");async function cs(e,t,r,n){if(!n.projectId||!n.receiptId){console.error("[email-router] action admission unavailable: missing project or receipt identity");return}let s=be();for(let[o,i]of r.entries()){if(i.type==="reject"){t.setReject(i.reason);return}if(s.expired()){console.error("[email-router] action batch deadline elapsed before admission");break}let a=i.to.toLowerCase(),l=i.type==="reply"?i.from:t.to,d=await ge(i.type,l,[a],i.type==="reply"?i.raw:new TextEncoder().encode(JSON.stringify([...i.headers?.entries()??[]].sort()))),u;try{u=await he(e,{projectId:n.projectId,kind:i.type,key:`${n.receiptId}:${o}:${d.slice(0,16)}`,digest:d,from:l,recipients:[a],transport:n.transport==="relay"?i.type==="reply"&&i.from.slice(i.from.indexOf("@")+1).toLowerCase()===te(e)?"binding":"send_raw":i.type==="forward"?"native_forward":"native_reply",receiptId:n.receiptId})}catch(f){console.error("[email-router] action admission unavailable:",f instanceof Error?f.message:"unknown");continue}let m=u.recipients.find(f=>f.recipient===a);if(u.replay||m?.state!=="reserved")continue;let p;if(n.transport==="relay"&&i.type==="reply")try{p=await ss(e,n.projectId,i.from,i.raw,u.accountId)}catch{await k(e,u.operationId,[a],"cancelled").catch(()=>{console.error("[email-router] could not cancel unsubmitted relayed reply")}),console.error("[email-router] relayed reply could not be prepared");continue}if(s.expired()){let f=await kr(e,u.operationId,a);console.error(f?"[email-router] action batch deadline elapsed; reservation cancelled":"[email-router] action batch deadline elapsed; cancellation unresolved");break}try{await K(e,u.operationId,[a])}catch{let f=await kr(e,u.operationId,a);console.error(f?"[email-router] attempt did not start; reservation cancelled":"[email-router] could not confirm attempt status");continue}try{let f;i.type==="forward"?await s.run(()=>t.forward(a,i.headers)):p?f=await s.run(()=>p(a,s.remainingMs())):await s.run(()=>t.reply(new Pr(i.from,a,re(i.raw))));try{await k(e,u.operationId,[a],"provider_accepted",{providerReference:f})}catch{console.error("[email-router] provider accepted action but outcome ledger write failed")}}catch(f){let h=f instanceof U;try{await k(e,u.operationId,[a],h?"failed":"outcome_unknown",{errorCode:h?"UPSTREAM_ERROR":"OUTCOME_UNKNOWN"})}catch{}console.error(h?"[email-router] action provider refused":"[email-router] action provider outcome unknown")}}}c(cs,"enactSanitized");async function kr(e,t,r){try{return(await k(e,t,[r],"cancelled")).recipients.some(s=>s.recipient===r&&s.state==="cancelled")}catch{return!1}}c(kr,"cancelUnstartedAction");var Fe=new TextEncoder,Rt=new TextDecoder,yt=128*1024,bt=320,ls=2,Br="/email/destinations/confirm",ds=4*1024,Ur=32*1024,Fr=5e3,wt=0,D=class extends Error{constructor(r,n){super(r);this.status=n;this.name="MimeHeaderError"}status;static{c(this,"MimeHeaderError")}};function At(e){return e.PLATFORM_TRAFFIC_STATE==="staging"||e.PLATFORM_TRAFFIC_STATE==="sandbox-drain"}c(At,"isTrafficPaused");async function Hr(e){if(wt>=ls)throw new Error("email gateway busy");wt++;try{return await e()}finally{wt--}}c(Hr,"withDeliverySlot");async function Gr(e,t){if(!t)throw new Error("Email signing key is not configured");let r=await crypto.subtle.importKey("raw",Fe.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,Fe.encode(e))),s="";for(let o of n)s+=String.fromCharCode(o);return btoa(s).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}c(Gr,"sign");async function zr(e,t){let r=Date.now()+5e3,n=new AbortController,s=c(async w=>{let R=r-Date.now();if(R<=0)throw n.abort(),new Error("ingress resolution timeout");let E;try{return await Promise.race([w(),new Promise((A,b)=>{E=setTimeout(()=>{n.abort(),b(new Error("ingress resolution timeout"))},R)})])}finally{E!==void 0&&clearTimeout(E)}},"beforeDeadline"),o=await Gr(`email-ingress-v1
4
4
  ${t.accountId}
5
5
  ${t.zoneId}
6
6
  ${t.ingressName}
7
- ${t.to.toLowerCase()}`,e.EMAIL_SIGNING_SECRET),i=await s(()=>e.API.fetch("https://api/internal/email/resolve-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":o},body:JSON.stringify(t),signal:n.signal}));if(!i.ok){if(i.body?.cancel().catch(()=>{}),i.status>=500||i.status===429)throw new Error("email routing unavailable");return null}let a=Number(i.headers.get("content-length"));if(Number.isFinite(a)&&a>4096)throw i.body?.cancel().catch(()=>{}),new Error("invalid email routing response");let c=i.body?.getReader();if(!c)throw new Error("invalid email routing response");let d=[],u=0;try{for(;;){let b=await s(()=>c.read());if(b.done)break;if(u+=b.value.byteLength,u>4096)throw new Error("invalid email routing response");d.push(b.value)}}finally{c.cancel().catch(()=>{});try{c.releaseLock()}catch{}}let m=new Uint8Array(u),p=0;for(let b of d)m.set(b,p),p+=b.byteLength;let f=Et.decode(m),y;try{y=JSON.parse(f)}catch{throw new Error("invalid email routing response")}if(!y||typeof y!="object")throw new Error("invalid email routing response");let h=y;if(typeof h.routeId!="string"||!Number.isSafeInteger(h.routeGeneration)||h.routeGeneration<1||typeof h.projectId!="string"||typeof h.connectionId!="string"||typeof h.workerName!="string"||typeof h.deploymentId!="string"||typeof h.slug!="string"||typeof h.domain!="string"||h.addressing!=="shared"&&h.addressing!=="custom")throw new Error("invalid email routing response");return h}l($r,"resolveIngress");async function as(e,t){if(!e||!Number.isSafeInteger(t)||t<0||t>x)throw new Error("invalid MIME length");let r=e.getReader(),n=new Uint8Array(t),s=0,o=Date.now()+15e3;try{for(;;){let i=o-Date.now();if(i<=0)throw new Error("MIME timeout");let a,c=await Promise.race([r.read(),new Promise((d,u)=>{a=setTimeout(()=>u(new Error("MIME timeout")),i)})]).finally(()=>{a!==void 0&&clearTimeout(a)});if(c.done)break;if(s+=c.value.byteLength,s>t||s>x)throw new Error("MIME too large");n.set(c.value,s-c.value.byteLength)}if(s!==t)throw new Error("truncated MIME");return n}catch(i){throw r.cancel().catch(()=>{}),i}finally{try{r.releaseLock()}catch{}}}l(as,"readMime");function ls(e){let t=-1;for(let i=0;i<e.length-3&&i<yt+4;i++)if(e[i]===13&&e[i+1]===10&&e[i+2]===13&&e[i+3]===10){t=i;break}if(t<0)throw new P("invalid MIME headers",e.byteLength>yt?413:400);if(t>yt)throw new P("MIME headers too large",413);let r=Et.decode(e.subarray(0,t)).split(`\r
8
- `),n=Object.create(null),s="",o=0;for(let i of r){if(++o>oe)throw new P("too many MIME headers",413);if(/^[ \t]/.test(i)){if(!s)throw new P("invalid MIME header fold",400);n[s]+=` ${i.trim()}`;continue}let a=i.indexOf(":");if(a<=0)throw new P("invalid MIME header",400);let c=i.slice(0,a).toLowerCase();if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c))throw new P("invalid MIME header name",400);n[c]=n[c]?`${n[c]}, ${i.slice(a+1).trim()}`:i.slice(a+1).trim(),s=c}return n}l(ls,"parseHeaders");async function cs(e,t,r){if(t.PLATFORM_TRAFFIC_STATE==="staging"||t.PLATFORM_TRAFFIC_STATE==="sandbox-drain")return new Response(null,{status:503});if(e.headers.get("content-encoding"))return new Response(null,{status:415});let n=e.headers.get("x-void-email-account")??"",s=e.headers.get("x-void-email-zone")??"",o=e.headers.get("x-void-email-ingress")??"",i=e.headers.get("x-void-email-request-id")??"",a=e.headers.get("x-void-email-from")??"",c=e.headers.get("x-void-email-to")??"",d=e.headers.get("authorization")??"";if([n,s,o,a,c,d].some(h=>!h||h.length>bt)||!d.startsWith("Bearer ")||!/^[a-f0-9-]{36}$/.test(i))return new Response(null,{status:400});let u=e.headers.get("content-length");if(u===null||!/^\d+$/.test(u))return new Response(null,{status:411});let m=Number(u);if(!Number.isSafeInteger(m)||m<0)return new Response(null,{status:411});if(m>x)return new Response(null,{status:413});let p;try{p=await $r(t,{accountId:n,zoneId:s,ingressName:o,from:a,to:c,secret:d.slice(7)})}catch{return new Response(null,{status:503})}if(!p)return new Response(null,{status:403});let f;try{f=await as(e.body,m)}catch(h){return console.error("[email-gateway] ingress failed:",h instanceof Error?h.message.slice(0,200):"unknown"),new Response(null,{status:502})}let y;try{y=ls(f)}catch(h){if(h instanceof P)return new Response(null,{status:h.status});throw h}try{let h=c.slice(c.lastIndexOf("@")+1).toLowerCase();if(h!==p.domain)return new Response(null,{status:403});let b={from:a,to:c,raw:f,rawSize:f.byteLength,headers:y,...p.addressing==="custom"?{viaDomain:h}:{}},R;try{R=p.limits?t.DISPATCH.get(p.workerName,{},{limits:p.limits}):t.DISPATCH.get(p.workerName)}catch(I){return console.error("[email-gateway] tenant dispatch stub unavailable:",I),new Response(null,{status:503})}let E=await wt(He.encode(JSON.stringify([p.connectionId,i]))),_=await wt(He.encode(JSON.stringify([a,c,await wt(f)]))),w={receiptId:E,projectId:p.projectId,payloadDigest:_,route:{routeId:p.routeId,routeGeneration:p.routeGeneration,connectionId:p.connectionId,addressing:p.addressing,domain:p.domain,projectSlug:p.slug}},v;try{v=await St(t,w)}catch(I){if(I instanceof Error&&I.message==="IDEMPOTENCY_CONFLICT")return new Response(null,{status:409});throw I}if(v.state==="completed"&&typeof v.reject=="boolean")return new Response(null,{status:v.reject?403:204,headers:{"x-void-email-receipt":E}});if(v.state!=="claimed")return new Response(null,{status:503,headers:{"x-void-email-receipt":E}});let T=await Or(t,r,{stub:R,projectId:p.projectId,domain:h,envelope:b,authoritative:p,receiptId:E});if(T.temporary)return new Response(null,{status:503});try{await Mt(t,w,T.reject)}catch{console.error("[email-gateway] receipt completion remains unresolved",E)}return new Response(null,{status:T.reject?403:204,headers:{"x-void-email-receipt":E}})}catch(h){return console.error("[email-gateway] ingress failed:",h instanceof Error?h.message.slice(0,200):"unknown"),new Response(null,{status:502})}}l(cs,"ingress");async function wt(e){return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e)),t=>t.toString(16).padStart(2,"0")).join("")}l(wt,"sha256");async function ds(e,t){if(e.headers.get("content-encoding"))return e.body?.cancel().catch(()=>{}),new Response(null,{status:400});let r=e.headers.get("content-length");if(r&&(!/^\d+$/.test(r)||Number(r)>1024))return e.body?.cancel().catch(()=>{}),new Response(null,{status:400});let n=e.headers.get("authorization")??"";if(!n.startsWith("Bearer ")||n.length>bt)return new Response(null,{status:403});let s=e.body?.getReader();if(!s)return new Response(null,{status:400});let o=new Uint8Array(1024),i=0,a=Date.now()+5e3;try{for(;;){let b=a-Date.now();if(b<=0)return new Response(null,{status:400});let R,E=await Promise.race([s.read(),new Promise((_,w)=>{R=setTimeout(()=>w(new Error("probe timeout")),b)})]).finally(()=>{R!==void 0&&clearTimeout(R)});if(E.done)break;if(i+=E.value.byteLength,i>o.byteLength)return new Response(null,{status:400});o.set(E.value,i-E.value.byteLength)}}catch{return new Response(null,{status:400})}finally{s.cancel().catch(()=>{});try{s.releaseLock()}catch{}}if(i===0||r&&i!==Number(r))return new Response(null,{status:400});let c;try{c=JSON.parse(Et.decode(o.subarray(0,i)))}catch{return new Response(null,{status:400})}if(!c||typeof c!="object")return new Response(null,{status:400});let{accountId:d,zoneId:u,ingressName:m}=c;if([d,u,m].some(b=>typeof b!="string"||!b||b.length>bt))return new Response(null,{status:400});let p=await Ur(`email-probe-v1
7
+ ${t.to.toLowerCase()}`,e.EMAIL_SIGNING_SECRET),i=await s(()=>e.API.fetch("https://api/internal/email/resolve-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":o},body:JSON.stringify(t),signal:n.signal}));if(!i.ok){if(i.body?.cancel().catch(()=>{}),i.status>=500||i.status===429)throw new Error("email routing unavailable");return null}let a=Number(i.headers.get("content-length"));if(Number.isFinite(a)&&a>4096)throw i.body?.cancel().catch(()=>{}),new Error("invalid email routing response");let l=i.body?.getReader();if(!l)throw new Error("invalid email routing response");let d=[],u=0;try{for(;;){let w=await s(()=>l.read());if(w.done)break;if(u+=w.value.byteLength,u>4096)throw new Error("invalid email routing response");d.push(w.value)}}finally{l.cancel().catch(()=>{});try{l.releaseLock()}catch{}}let m=new Uint8Array(u),p=0;for(let w of d)m.set(w,p),p+=w.byteLength;let f=Rt.decode(m),h;try{h=JSON.parse(f)}catch{throw new Error("invalid email routing response")}if(!h||typeof h!="object")throw new Error("invalid email routing response");let y=h;if(typeof y.routeId!="string"||!Number.isSafeInteger(y.routeGeneration)||y.routeGeneration<1||typeof y.projectId!="string"||typeof y.connectionId!="string"||typeof y.workerName!="string"||typeof y.deploymentId!="string"||typeof y.slug!="string"||typeof y.domain!="string"||y.addressing!=="shared"&&y.addressing!=="custom")throw new Error("invalid email routing response");return y}c(zr,"resolveIngress");async function us(e,t){if(!e||!Number.isSafeInteger(t)||t<0||t>L)throw new Error("invalid MIME length");let r=e.getReader(),n=new Uint8Array(t),s=0,o=Date.now()+15e3;try{for(;;){let i=o-Date.now();if(i<=0)throw new Error("MIME timeout");let a,l=await Promise.race([r.read(),new Promise((d,u)=>{a=setTimeout(()=>u(new Error("MIME timeout")),i)})]).finally(()=>{a!==void 0&&clearTimeout(a)});if(l.done)break;if(s+=l.value.byteLength,s>t||s>L)throw new Error("MIME too large");n.set(l.value,s-l.value.byteLength)}if(s!==t)throw new Error("truncated MIME");return n}catch(i){throw r.cancel().catch(()=>{}),i}finally{try{r.releaseLock()}catch{}}}c(us,"readMime");function fs(e){let t=-1;for(let i=0;i<e.length-3&&i<yt+4;i++)if(e[i]===13&&e[i+1]===10&&e[i+2]===13&&e[i+3]===10){t=i;break}if(t<0)throw new D("invalid MIME headers",e.byteLength>yt?413:400);if(t>yt)throw new D("MIME headers too large",413);let r=Rt.decode(e.subarray(0,t)).split(`\r
8
+ `),n=Object.create(null),s="",o=0;for(let i of r){if(++o>se)throw new D("too many MIME headers",413);if(/^[ \t]/.test(i)){if(!s)throw new D("invalid MIME header fold",400);n[s]+=` ${i.trim()}`;continue}let a=i.indexOf(":");if(a<=0)throw new D("invalid MIME header",400);let l=i.slice(0,a).toLowerCase();if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(l))throw new D("invalid MIME header name",400);n[l]=n[l]?`${n[l]}, ${i.slice(a+1).trim()}`:i.slice(a+1).trim(),s=l}return n}c(fs,"parseHeaders");async function ms(e,t,r){if(At(t))return new Response(null,{status:503});if(e.headers.get("content-encoding"))return new Response(null,{status:415});let n=e.headers.get("x-void-email-account")??"",s=e.headers.get("x-void-email-zone")??"",o=e.headers.get("x-void-email-ingress")??"",i=e.headers.get("x-void-email-request-id")??"",a=e.headers.get("x-void-email-from")??"",l=e.headers.get("x-void-email-to")??"",d=e.headers.get("authorization")??"";if([n,s,o,a,l,d].some(y=>!y||y.length>bt)||!d.startsWith("Bearer ")||!/^[a-f0-9-]{36}$/.test(i))return new Response(null,{status:400});let u=e.headers.get("content-length");if(u===null||!/^\d+$/.test(u))return new Response(null,{status:411});let m=Number(u);if(!Number.isSafeInteger(m)||m<0)return new Response(null,{status:411});if(m>L)return new Response(null,{status:413});let p;try{p=await zr(t,{accountId:n,zoneId:s,ingressName:o,from:a,to:l,secret:d.slice(7)})}catch{return new Response(null,{status:503})}if(!p)return new Response(null,{status:403});let f;try{f=await us(e.body,m)}catch(y){return console.error("[email-gateway] ingress failed:",y instanceof Error?y.message.slice(0,200):"unknown"),new Response(null,{status:502})}let h;try{h=fs(f)}catch(y){if(y instanceof D)return new Response(null,{status:y.status});throw y}try{let y=l.slice(l.lastIndexOf("@")+1).toLowerCase();if(y!==p.domain)return new Response(null,{status:403});let w={from:a,to:l,raw:f,rawSize:f.byteLength,headers:h,...p.addressing==="custom"?{viaDomain:y}:{}},R;try{R=p.limits?t.DISPATCH.get(p.workerName,{},{limits:p.limits}):t.DISPATCH.get(p.workerName)}catch(O){return console.error("[email-gateway] tenant dispatch stub unavailable:",O),new Response(null,{status:503})}let E=await Et(Fe.encode(JSON.stringify([p.connectionId,i]))),A=await Et(Fe.encode(JSON.stringify([a,l,await Et(f)]))),b={receiptId:E,projectId:p.projectId,payloadDigest:A,route:{routeId:p.routeId,routeGeneration:p.routeGeneration,connectionId:p.connectionId,addressing:p.addressing,domain:p.domain,projectSlug:p.slug}},_;try{_=await xt(t,b)}catch(O){if(O instanceof Error&&O.message==="IDEMPOTENCY_CONFLICT")return new Response(null,{status:409});throw O}if(_.state==="completed"&&typeof _.reject=="boolean")return new Response(null,{status:_.reject?403:204,headers:{"x-void-email-receipt":E}});if(_.state!=="claimed")return new Response(null,{status:503,headers:{"x-void-email-receipt":E}});let M=await jr(t,r,{stub:R,projectId:p.projectId,domain:y,envelope:w,authoritative:p,receiptId:E});if(M.temporary)return new Response(null,{status:503});try{await Ot(t,b,M.reject)}catch{console.error("[email-gateway] receipt completion remains unresolved",E)}return new Response(null,{status:M.reject?403:204,headers:{"x-void-email-receipt":E}})}catch(y){return console.error("[email-gateway] ingress failed:",y instanceof Error?y.message.slice(0,200):"unknown"),new Response(null,{status:502})}}c(ms,"ingress");async function Et(e){return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e)),t=>t.toString(16).padStart(2,"0")).join("")}c(Et,"sha256");async function ps(e,t){if(e.headers.get("content-encoding"))return e.body?.cancel().catch(()=>{}),new Response(null,{status:400});let r=e.headers.get("content-length");if(r&&(!/^\d+$/.test(r)||Number(r)>1024))return e.body?.cancel().catch(()=>{}),new Response(null,{status:400});let n=e.headers.get("authorization")??"";if(!n.startsWith("Bearer ")||n.length>bt)return new Response(null,{status:403});let s=e.body?.getReader();if(!s)return new Response(null,{status:400});let o=new Uint8Array(1024),i=0,a=Date.now()+5e3;try{for(;;){let w=a-Date.now();if(w<=0)return new Response(null,{status:400});let R,E=await Promise.race([s.read(),new Promise((A,b)=>{R=setTimeout(()=>b(new Error("probe timeout")),w)})]).finally(()=>{R!==void 0&&clearTimeout(R)});if(E.done)break;if(i+=E.value.byteLength,i>o.byteLength)return new Response(null,{status:400});o.set(E.value,i-E.value.byteLength)}}catch{return new Response(null,{status:400})}finally{s.cancel().catch(()=>{});try{s.releaseLock()}catch{}}if(i===0||r&&i!==Number(r))return new Response(null,{status:400});let l;try{l=JSON.parse(Rt.decode(o.subarray(0,i)))}catch{return new Response(null,{status:400})}if(!l||typeof l!="object")return new Response(null,{status:400});let{accountId:d,zoneId:u,ingressName:m}=l;if([d,u,m].some(w=>typeof w!="string"||!w||w.length>bt))return new Response(null,{status:400});let p=await Gr(`email-probe-v1
9
9
  ${d}
10
10
  ${u}
11
- ${m}`,t.EMAIL_SIGNING_SECRET),f=new AbortController,y=Date.now()+5e3,h;try{let b=await Promise.race([t.API.fetch("https://api/internal/email/probe-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":p},body:JSON.stringify({accountId:d,zoneId:u,ingressName:m,secret:n.slice(7)}),signal:f.signal}),new Promise((R,E)=>{h=setTimeout(()=>{f.abort(),E(new Error("email probe timeout"))},Math.max(0,y-Date.now()))})]);return b.body?.cancel().catch(()=>{}),new Response(null,{status:b.status===204?204:403})}catch{return new Response(null,{status:503})}finally{h!==void 0&&clearTimeout(h)}}l(ds,"probe");function Fe(e,t,r){let n=new Headers({"cache-control":"no-store","referrer-policy":"no-referrer","x-content-type-options":"nosniff"});return r&&n.set("content-type",r),new Response(e,{status:t,headers:n})}l(Fe,"confirmationResponse");async function us(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>Lr)throw new Error("confirmation response too large");let s=e.body?.getReader();if(!s)return null;let o=new Uint8Array(Lr),i=0;try{for(;;){let a=t-Date.now();if(a<=0)throw new Error("confirmation response timeout");let c,d=await Promise.race([s.read(),new Promise((u,m)=>{c=setTimeout(()=>{r.abort(),m(new Error("confirmation response timeout"))},a)})]).finally(()=>{c!==void 0&&clearTimeout(c)});if(d.done)return o.slice(0,i);if(i+=d.value.byteLength,i>o.byteLength)throw new Error("confirmation response too large");o.set(d.value,i-d.value.byteLength)}}finally{s.cancel().catch(()=>{});try{s.releaseLock()}catch{}}}l(us,"readConfirmationResponse");async function fs(e,t){let n=[...new URL(e.url).searchParams.entries()];if(n.length!==1||n[0][0]!=="token"||!n[0][1]||n[0][1].length>os||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(n[0][1]))return Fe(null,400);if(t.PLATFORM_TRAFFIC_STATE==="staging"||t.PLATFORM_TRAFFIC_STATE==="sandbox-drain")return Fe(null,503);let s=Date.now()+Dr,o=new AbortController,i,a;try{let c=new URL(`https://api${jr}`);c.searchParams.set("token",n[0][1]);let d=t.API.fetch(c.toString(),{method:"GET",redirect:"manual",signal:o.signal});d.then(m=>{o.signal.aborted&&m!==i&&m.body?.cancel().catch(()=>{})},()=>{}),i=await Promise.race([d,new Promise((m,p)=>{a=setTimeout(()=>{o.abort(),p(new Error("confirmation request timeout"))},Dr)})]),a!==void 0&&(clearTimeout(a),a=void 0);let u=await us(i,s,o);return Fe(u,i.status,i.headers.get("content-type"))}catch{return Fe(null,503)}finally{o.abort(),a!==void 0&&clearTimeout(a),i?.body?.cancel().catch(()=>{})}}l(fs,"confirmDestination");var Gl={async fetch(e,t,r){let n=new URL(e.url);if(e.method==="GET"&&n.pathname==="/health")return Response.json({ok:!0,installationId:t.PLATFORM_INSTALLATION_ID,platformVersion:t.PLATFORM_VERSION,emailProtocolVersion:1});if(e.method==="GET"&&n.pathname===jr)return fs(e,t);if(e.method!=="POST")return new Response(null,{status:404});if(n.pathname==="/email/probe")return ds(e,t);if(n.pathname==="/email/ingress")try{return await Cr(()=>cs(e,t,r))}catch{return new Response(null,{status:503})}return new Response(null,{status:404})},async email(e,t,r){if(t.PLATFORM_TRAFFIC_STATE==="staging"||t.PLATFORM_TRAFFIC_STATE==="sandbox-drain")throw new Error("Email gateway temporarily unavailable");let n=t.EMAIL_SHARED_ACCOUNT_ID,s=t.EMAIL_SHARED_ZONE_ID,o=t.EMAIL_SHARED_INGRESS_NAME;if(!n||!s||!o){e.setReject("Email routing is not configured");return}let i;try{i=await $r(t,{accountId:n,zoneId:s,ingressName:o,from:e.from,to:e.to,native:!0})}catch{throw new Error("Email route temporarily unavailable")}if(!i){e.setReject("Email route unavailable");return}await Cr(()=>kr(e,t,r,i))}};export{Gl as default};
11
+ ${m}`,t.EMAIL_SIGNING_SECRET),f=new AbortController,h=Date.now()+5e3,y;try{let w=await Promise.race([t.API.fetch("https://api/internal/email/probe-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":p},body:JSON.stringify({accountId:d,zoneId:u,ingressName:m,secret:n.slice(7)}),signal:f.signal}),new Promise((R,E)=>{y=setTimeout(()=>{f.abort(),E(new Error("email probe timeout"))},Math.max(0,h-Date.now()))})]);return w.body?.cancel().catch(()=>{}),new Response(null,{status:w.status===204?204:403})}catch{return new Response(null,{status:503})}finally{y!==void 0&&clearTimeout(y)}}c(ps,"probe");function Ue(e,t,r){let n=new Headers({"cache-control":"no-store","content-security-policy":"frame-ancestors 'none'","referrer-policy":"no-referrer","x-content-type-options":"nosniff","x-frame-options":"DENY"});return r&&n.set("content-type",r),new Response(e,{status:t,headers:n})}c(Ue,"confirmationResponse");async function gs(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>Ur)throw new Error("confirmation response too large");let s=e.body?.getReader();if(!s)return null;let o=new Uint8Array(Ur),i=0;try{for(;;){let a=t-Date.now();if(a<=0)throw new Error("confirmation response timeout");let l,d=await Promise.race([s.read(),new Promise((u,m)=>{l=setTimeout(()=>{r.abort(),m(new Error("confirmation response timeout"))},a)})]).finally(()=>{l!==void 0&&clearTimeout(l)});if(d.done)return o.slice(0,i);if(i+=d.value.byteLength,i>o.byteLength)throw new Error("confirmation response too large");o.set(d.value,i-d.value.byteLength)}}finally{s.cancel().catch(()=>{});try{s.releaseLock()}catch{}}}c(gs,"readConfirmationResponse");async function hs(e,t){let n=[...new URL(e.url).searchParams.entries()];if(n.length!==1||n[0][0]!=="token"||!n[0][1]||n[0][1].length>ds||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(n[0][1]))return Ue(null,400);if(At(t))return Ue(null,503);let s=Date.now()+Fr,o=new AbortController,i,a;try{let l=new URL(`https://api${Br}`);l.searchParams.set("token",n[0][1]);let d=t.API.fetch(l.toString(),{method:e.method,redirect:"manual",signal:o.signal});d.then(m=>{o.signal.aborted&&m!==i&&m.body?.cancel().catch(()=>{})},()=>{}),i=await Promise.race([d,new Promise((m,p)=>{a=setTimeout(()=>{o.abort(),p(new Error("confirmation request timeout"))},Fr)})]),a!==void 0&&(clearTimeout(a),a=void 0);let u=await gs(i,s,o);return Ue(u,i.status,i.headers.get("content-type"))}catch{return Ue(null,503)}finally{o.abort(),a!==void 0&&clearTimeout(a),i?.body?.cancel().catch(()=>{})}}c(hs,"confirmDestination");var Zc={async fetch(e,t,r){let n=new URL(e.url);if(e.method==="GET"&&n.pathname==="/health")return Response.json({ok:!0,installationId:t.PLATFORM_INSTALLATION_ID,platformVersion:t.PLATFORM_VERSION,emailProtocolVersion:1});if((e.method==="GET"||e.method==="POST")&&n.pathname===Br)return hs(e,t);if(e.method!=="POST")return new Response(null,{status:404});if(n.pathname==="/email/probe")return ps(e,t);if(n.pathname==="/email/ingress")try{return await Hr(()=>ms(e,t,r))}catch{return new Response(null,{status:503})}return new Response(null,{status:404})},async email(e,t,r){if(At(t))throw new Error("Email gateway temporarily unavailable");let n=t.EMAIL_SHARED_ACCOUNT_ID,s=t.EMAIL_SHARED_ZONE_ID,o=t.EMAIL_SHARED_INGRESS_NAME;if(!n||!s||!o){e.setReject("Email routing is not configured");return}let i;try{i=await zr(t,{accountId:n,zoneId:s,ingressName:o,from:e.from,to:e.to,native:!0})}catch{throw new Error("Email route temporarily unavailable")}if(!i){e.setReject("Email route unavailable");return}await Hr(()=>Cr(e,t,r,i))}};export{Zc as default};
@@ -2,18 +2,18 @@
2
2
  "artifacts": {
3
3
  "api": {
4
4
  "path": "api/index.js",
5
- "sha256": "37de91758f606f49225bc42e22b3c1037edfab093d57bc74d57563c20a96d44a",
6
- "size": 3323725
5
+ "sha256": "9e78a28a8ccd679aeff4869400d22b47d4e1cc06ba24b81848e861e52db83d4d",
6
+ "size": 3346032
7
7
  },
8
8
  "dispatch": {
9
9
  "path": "dispatch/index.js",
10
- "sha256": "e36a2c3a44f6cabbafcea040ef872157a7249f96b5b561d48f777f0d6de56451",
11
- "size": 79124
10
+ "sha256": "d619f318d6a73b60969d11e8b0718b85d328b4abd25e62c92699d3c1115cf095",
11
+ "size": 79671
12
12
  },
13
13
  "proxy": {
14
14
  "path": "proxy/index.js",
15
- "sha256": "f094539fcf582ba65e7d223263bde0caa54463f099f9220dd6158674ac8d421e",
16
- "size": 79456
15
+ "sha256": "01284295c77ff80ab80d39cd30210cca9c58741ce0cae52f501b014f2377b232",
16
+ "size": 83335
17
17
  },
18
18
  "tail": {
19
19
  "path": "tail/index.js",
@@ -22,8 +22,8 @@
22
22
  },
23
23
  "emailGateway": {
24
24
  "path": "emailGateway/index.js",
25
- "sha256": "5f02839a0a6a75470df74927e4bbbc6e872e73c4257c64489ca295a279a10f9c",
26
- "size": 81977
25
+ "sha256": "9a563491e7e7f30e49502f650fc016f63085989285316881ae0792cf22ebb958",
26
+ "size": 80619
27
27
  }
28
28
  },
29
29
  "appAccessSetup": 1,
@@ -31,20 +31,20 @@
31
31
  "assets": {
32
32
  "adminClient": {
33
33
  "path": "api/assets/admin/client.js",
34
- "sha256": "01d1854f3c52704b987414adc16f01729314f56b27e1a7949b8745aeb2ea4a14",
35
- "size": 967790
34
+ "sha256": "8d88705dcd28f0d982ee4611802fd310d4c4feb6479ba8713db6d087cbede20a",
35
+ "size": 981233
36
36
  },
37
37
  "adminStyle": {
38
38
  "path": "api/assets/admin/style.css",
39
- "sha256": "59dcdfacd9683b5d93a6df0c77b6f7e2612197a1b7edc2b2565fcdede3100539",
40
- "size": 212879
39
+ "sha256": "ed1e208405cc27469cf83e1b16270c56fa220c93315e15daf9e37d4091e0bc29",
40
+ "size": 216265
41
41
  }
42
42
  },
43
43
  "authenticationProtocolVersion": 1,
44
44
  "emailProtocolVersion": 1,
45
45
  "applicationRoutingVersion": 1,
46
46
  "database": {
47
- "journalSha256": "5af56a8a144d346bd334437a5cbb672c8747ffc111f7b64ec408c6f745ee16b8",
47
+ "journalSha256": "bbe646675b3df4742258f5069d4491d8d503e7cba9af6029beee3aec8033983a",
48
48
  "lineage": "void-platform-postgresql-v1",
49
49
  "migrations": [
50
50
  {
@@ -352,6 +352,12 @@
352
352
  "sha256": "1437adb6fcc524546938a6e4a4a25f4ed8f6cb183337ffb27541cd1d0e9edaa9",
353
353
  "tag": "0057_github_authority_constraints",
354
354
  "timestampMillis": 1790912739624
355
+ },
356
+ {
357
+ "index": 58,
358
+ "sha256": "1f2b0f24c7a2f397542c58c6a4d55ead2ceda7b889aae84ca186e64cd03164e2",
359
+ "tag": "0058_project_proxy_token_gen",
360
+ "timestampMillis": 1791311435335
355
361
  }
356
362
  ],
357
363
  "protocolVersion": 1,
@@ -411,15 +417,23 @@
411
417
  {
412
418
  "platformVersion": "0.24.0",
413
419
  "schemaDigest": "3e3458ba1268853dc8e9a887270863557c2a4c5a5210f8615d247bf1f4bf6bcc"
420
+ },
421
+ {
422
+ "platformVersion": "0.25.0",
423
+ "schemaDigest": "7581930465664b7c578518bea54f36a83d20fcc47d9528183419033930d7ff4a"
424
+ },
425
+ {
426
+ "platformVersion": "0.26.0",
427
+ "schemaDigest": "7581930465664b7c578518bea54f36a83d20fcc47d9528183419033930d7ff4a"
414
428
  }
415
429
  ],
416
- "schemaDigest": "7581930465664b7c578518bea54f36a83d20fcc47d9528183419033930d7ff4a"
430
+ "schemaDigest": "8580c6074cecbe15a7078428bd7f3ac4f5009f922bb8d2f300c58dcb717bfea3"
417
431
  },
418
- "platformVersion": "0.26.0",
432
+ "platformVersion": "0.26.1",
419
433
  "safetyProtocols": {
420
434
  "sandboxDrain": 3
421
435
  },
422
436
  "schemaVersion": 2,
423
- "sourceRevision": "66cbbb9c30b42433b8ec22a4cdea5f2caef76400",
437
+ "sourceRevision": "73e2ab095059bab669f66b40c9125aa272dc01b8",
424
438
  "usageProtocolVersion": 2
425
439
  }