@void/platform 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser-page.d.mts +1 -3
- package/dist/browser-page.mjs +1 -2
- package/dist/email-protocol.d.mts +1 -3
- package/dist/email-protocol.mjs +1 -2
- package/dist/index.d.mts +0 -18
- package/dist/index.mjs +10 -19
- package/dist/installer.d.mts +1 -3
- package/dist/installer.mjs +2 -3
- package/dist/plans.d.mts +1 -3
- package/dist/plans.mjs +2 -3
- package/dist/runtime/api/assets/admin/client.js +44 -42
- package/dist/runtime/api/assets/admin/style.css +1 -1
- package/dist/runtime/api/index.js +306 -302
- package/dist/runtime/dispatch/index.js +7 -7
- package/dist/runtime/emailGateway/index.js +5 -5
- package/dist/runtime/manifest.json +14 -14
- package/dist/runtime/proxy/index.js +5 -5
- package/dist/{validate-DbJR7Q0Z.mjs → validate-CTKcW3Vp.mjs} +1 -2
- package/package.json +4 -4
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var Wr=Object.create;var He=Object.defineProperty;var Xr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Yr=Object.getPrototypeOf,Kr=Object.prototype.hasOwnProperty;var l=(e,t)=>He(e,"name",{value:t,configurable:!0});var ae=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var Qr=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Zr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Jr(t))!Kr.call(e,o)&&o!==r&&He(e,o,{get:()=>t[o],enumerable:!(n=Xr(t,o))||n.enumerable});return e};var en=(e,t,r)=>(r=e!=null?Wr(Yr(e)):{},Zr(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=ae(()=>{g();l(H,"createNotImplementedError")});var Be,Ge,tn,B,ze,X,J,le,V,ce,Y,It=ae(()=>{g();_t();Be=globalThis.performance?.timeOrigin??Date.now(),Ge=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-Be,tn={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{l(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{l(this,"PerformanceMark")}entryType="mark";constructor(){super(...arguments)}get duration(){return 0}},X=class extends B{static{l(this,"PerformanceMeasure")}entryType="measure"},J=class extends B{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},le=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=Be;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(t,r){throw H("Performance.timerify")}get nodeTiming(){return tn}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 o,i;typeof r=="string"?(o=this.getEntriesByName(r,"mark")[0]?.startTime,i=this.getEntriesByName(n,"mark")[0]?.startTime):(o=Number.parseFloat(r?.start)||this.now(),i=Number.parseFloat(r?.end)||this.now());let s=new X(t,{startTime:o,detail:{start:o,end:i}});return this._entries.push(s),s}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{l(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 vt=ae(()=>{g();It()});var g=ae(()=>{vt();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=le;globalThis.PerformanceResourceTiming=J});var Lt=Qr(Dt=>{"use strict";g();var un=/^[-!#$%&'*+\/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])+$/;Dt.validate=function(e){if(!e||e.length>254)return!1;var t=un.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(o){return o.length>63})}});g();g();g();var Mt=new TextEncoder,de,St;async function rn(e){return de&&St===e||(de=await crypto.subtle.importKey("raw",Mt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),St=e),de}l(rn,"getSignKey");async function ue(e,t){let r=await rn(t),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,Mt.encode(e)));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}l(ue,"hmacSign");var fe=new TextEncoder,K=new TextDecoder,nn=5e3,me=15e3,Nt=15e3,on=65536;async function sn(e,t){if(!t)throw new Error("Email signing key is not configured");return ue(e,t)}l(sn,"sign");async function q(e,t,r,n=nn){let o=new AbortController,i=Date.now()+n,s=l(async f=>{let h=i-Date.now();if(h<=0)throw o.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let y=f(),b;try{return await Promise.race([y,new Promise((R,w)=>{b=setTimeout(()=>{o.abort(),w(new Error("EMAIL_ADMISSION_TIMEOUT"))},h)})])}finally{b!==void 0&&clearTimeout(b)}},"beforeDeadline"),a=JSON.stringify(r),c=await sn(a,e.EMAIL_SIGNING_SECRET),d=await s(()=>e.API.fetch(`https://api/internal/email/actions${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":c},body:a,signal:o.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(on),p=0;try{for(;;){let f=await s(()=>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(K.decode(m.subarray(0,p)))}finally{u.cancel().catch(()=>{});try{u.releaseLock()}catch{}}}l(q,"call");function Ot(e,t){return q(e,"/receipts/claim",t)}l(Ot,"claimRelayedReceipt");function kt(e,t,r){return q(e,"/receipts/complete",{receiptId:t.receiptId,projectId:t.projectId,payloadDigest:t.payloadDigest,reject:r})}l(kt,"completeRelayedReceipt");function an(e){if(ln(e)===-1)return e;let t=new Map,r=[],n=0,o=0,i=!1,s=!0,a=!0,c=l(f=>{f.byteLength!==0&&(r.push(f),n+=f.byteLength)},"append"),d=l((f,h,y)=>{c(e.subarray(o,f)),c(y),o=h,i=!0},"replace"),u=0;for(;u<e.byteLength;){let f=Tt(e,u),h=f===e.byteLength?e.byteLength:f+2;if(s){if(f===u)s=!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=f,b=h,R=K.decode(e.subarray(u,y));for(;e[b]===32||e[b]===9;)y=Tt(e,b),R+=` ${K.decode(e.subarray(b,y)).replace(/^[ \t]+/,"")}`,b=y===e.byteLength?e.byteLength:y+2;let w=R.replace(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(A,E)=>{let _=t.get(E);return _||(_=`<void-boundary-${t.size}>`,t.set(E,_)),`boundary="${_}"`});w!==R&&d(u,y,fe.encode(w)),u=b;continue}}else if(e[u]===45&&e[u+1]===45){let y=u+2,b=xt(e,y,f)?K.decode(e.subarray(y,f)):void 0,R=b===void 0?void 0:t.get(b);if(R!==void 0)d(u,f,fe.encode(`--${R}`)),s=!0;else if(f-y>=2&&e[f-2]===45&&e[f-1]===45&&xt(e,y,f-2)){let w=K.decode(e.subarray(y,f-2)),A=t.get(w);A!==void 0&&d(u,f,fe.encode(`--${A}--`))}}u=h}if(!i)return e;c(e.subarray(o));let m=new Uint8Array(n),p=0;for(let f of r)m.set(f,p),p+=f.byteLength;return m}l(an,"canonicalizeVoidMime");function ln(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(ln,"findCrlfCrlf");function Tt(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(Tt,"findCrlf");function pe(e,t,r,n){if(r-t<n.length)return!1;for(let o=0;o<n.length;o++){let i=e[t+o],s=n.charCodeAt(o);if((i>=65&&i<=90?i+32:i)!==(s|32))return!1}return!0}l(pe,"asciiPrefixEquals");function cn(e,t,r){let n="Content-Type:";if(!pe(e,t,r,n))return!1;let o=t+n.length;for(;o<r&&(e[o]===32||e[o]===9||e[o]===11||e[o]===12);)o++;return pe(e,o,r,"multipart/")}l(cn,"isMultipartContentType");function xt(e,t,r){if(r<=t)return!1;for(let n=t;n<r;n++){let o=e[n];if(!(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===95||o===45||o===61))return!1}return!0}l(xt,"isBoundaryToken");async function ge(e,t,r,n){let o=an(n),i=fe.encode(JSON.stringify({kind:e,from:t.toLowerCase(),recipients:[...new Set(r.map(a=>a.toLowerCase()))].sort()})),s=new Uint8Array(i.length+1+o.length);return s.set(i),s[i.length]=0,s.set(o,i.length+1),[...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(a=>a.toString(16).padStart(2,"0")).join("")}l(ge,"emailPayloadDigest");function he(e,t,r=Nt){return q(e,"/admit",t,Math.min(r,Nt))}l(he,"admitEmail");function Q(e,t,r,n=me){return q(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Math.min(n,me))}l(Q,"startEmailAttempt");function k(e,t,r,n,o={},i=me){return q(e,`/${encodeURIComponent(t)}/finish`,{recipients:r,state:n,...o},Math.min(i,me))}l(k,"finishEmailAttempt");function G(e,t,r,n,o){return q(e,"/receipts",{receiptId:t,projectId:r,status:n,...o?{route:o}:{}})}l(G,"recordEmailReceipt");g();g();var dn=new Set(["abuse","bounce","noreply","postmaster","security"]);function Pt(e){return dn.has(e)}l(Pt,"isReservedEmailSlug");var Lr=en(Lt(),1);import{EmailMessage as Dr}from"cloudflare:email";g();g();var jt="/__void/email/receipt/v1";var Ve=new TextEncoder,fn=new TextDecoder("utf-8",{fatal:!0});function mn(e,t,r){let n=0,o=0,i=!1,s=!1;for(let a of e)if(i)s?s=!1:a===92?s=!0:a===34&&(i=!1);else if(a===34)i=!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&&++o>r)throw new Error("too many email metadata fields");if(i||n!==0)throw new Error("invalid email metadata")}l(mn,"assertFlatJson");function $t(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}l($t,"encodeEmailEnvelope");function Ct(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}l(Ct,"base64url");async function pn(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])}l(pn,"receiptKey");async function Ut(e,t){let r=Ve.encode(JSON.stringify(e)),n=new Uint8Array(await crypto.subtle.sign("HMAC",await pn(t,"sign"),r));return`${Ct(r)}.${Ct(n)}`}l(Ut,"signEmailReceipt");async function Ft(e,t=15e3){return hn(e,async r=>{let n=[],o=new Uint8Array(0),i=0,s=Date.now()+t,a=l(()=>gn(r,s,"email response timeout"),"readChunk");async function c(d){let u=new Uint8Array(d),m=0;for(;m<d;){if(o.byteLength===0){let f=await a();if(f.done)throw new Error("truncated email response");if(i+=f.value.byteLength,i>8388608)throw new Error("email response too large");o=f.value}let p=Math.min(o.byteLength,d-m);u.set(o.subarray(0,p),m),o=o.subarray(p),m+=p}return u}for(l(c,"exact");;){let d=await c(5),u=new DataView(d.buffer).getUint32(0),m=d[4];if(m===0){if(u!==0||o.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 c(u);mn(p,2,40);let f=JSON.parse(fn.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 c(5),b=new DataView(y.buffer).getUint32(0);if(y[4]!==2||b>5242880)throw new Error("invalid email reply frame");n.push({type:"reply",from:h.from,to:h.to,raw:await c(b)})}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(b=>typeof b!="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")}})}l(Ft,"readEmailActions");async function gn(e,t,r){let n=t-Date.now();if(n<=0)throw new Error(r);let o;return Promise.race([e.read(),new Promise((i,s)=>{o=setTimeout(()=>s(new Error(r)),n)})]).finally(()=>{o!==void 0&&clearTimeout(o)})}l(gn,"readBeforeDeadline");async function hn(e,t){let r=e.getReader();try{return await t(r)}catch(n){throw r.cancel().catch(()=>{}),n}finally{try{r.releaseLock()}catch{}}}l(hn,"withReader");var yn=8,bn=2e4,En=15e3,Z=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 o=Z.get(r.projectId)??0;if(o>=yn)throw new Error("email project concurrency exceeded");Z.set(r.projectId,o+1);let i=Date.now()+bn,s=new AbortController,a;try{let c=await Ut({version:1,receiptId:n,projectId:r.projectId,deploymentId:r.deploymentId,recipient:r.envelope.to,expiresAt:Date.now()+3e4},t.EMAIL_SIGNING_SECRET),d=i-Date.now();if(d<=0)throw new Error("email tenant request timeout");let u;try{a=await Promise.race([e.fetch(`https://worker${jt}`,{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:$t(r.envelope),signal:s.signal}),new Promise((f,h)=>{u=setTimeout(()=>{s.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(En,i-Date.now());if(m<=0)throw new Error("email tenant request timeout");return{actions:await Ft(a.body,m),receiptId:n}}finally{s.abort(),a?.body?.cancel().catch(()=>{});let c=(Z.get(r.projectId)??1)-1;c===0?Z.delete(r.projectId):Z.set(r.projectId,c)}}l(qe,"dispatchBoundedEmailToTenant");g();var Bt=5e3,Gt=4*1024;function ye(e){return e.token}l(ye,"leaseBearer");async function be(e,t,r,n=Bt){if(!e.EMAIL_SIGNING_SECRET)return null;let o=new AbortController,i=Date.now()+Math.min(n,Bt),s=l(async p=>{let f=i-Date.now();if(f<=0)throw o.abort(),new Error("email credential lease timed out");let h=p(),y;try{return await Promise.race([h,new Promise((b,R)=>{y=setTimeout(()=>{o.abort(),R(new Error("email credential lease timed out"))},f)})])}finally{y!==void 0&&clearTimeout(y)}},"beforeDeadline"),a;try{let p=await ue(`email-lease-v1
|
|
1
|
+
var zr=Object.create;var He=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Vr=Object.getOwnPropertyNames;var Wr=Object.getPrototypeOf,Xr=Object.prototype.hasOwnProperty;var a=(e,t)=>He(e,"name",{value:t,configurable:!0});var ae=(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 Jr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vr(t))!Xr.call(e,o)&&o!==r&&He(e,o,{get:()=>t[o],enumerable:!(n=qr(t,o))||n.enumerable});return e};var Kr=(e,t,r)=>(r=e!=null?zr(Wr(e)):{},Jr(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 Rt=ae(()=>{g();a(H,"createNotImplementedError")});var Be,Ge,Qr,B,ze,X,Y,le,q,ce,J,At=ae(()=>{g();Rt();Be=globalThis.performance?.timeOrigin??Date.now(),Ge=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-Be,Qr={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{a(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{a(this,"PerformanceMark")}entryType="mark";constructor(){super(...arguments)}get duration(){return 0}},X=class extends B{static{a(this,"PerformanceMeasure")}entryType="measure"},Y=class extends B{static{a(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},le=class{static{a(this,"PerformanceObserverEntryList")}__unenv__=!0;getEntries(){return[]}getEntriesByName(t,r){return[]}getEntriesByType(t){return[]}},q=class{static{a(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 Qr}eventLoopUtilization(){return{}}markResourceTiming(){return new Y("")}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 o,i;typeof r=="string"?(o=this.getEntriesByName(r,"mark")[0]?.startTime,i=this.getEntriesByName(n,"mark")[0]?.startTime):(o=Number.parseFloat(r?.start)||this.now(),i=Number.parseFloat(r?.end)||this.now());let s=new X(t,{startTime:o,detail:{start:o,end:i}});return this._entries.push(s),s}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{a(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}},J=globalThis.performance&&"addEventListener"in globalThis.performance?globalThis.performance:new q});var _t=ae(()=>{g();At()});var g=ae(()=>{_t();if(!("__unenv__"in J)){let e=q.prototype;for(let t of Object.getOwnPropertyNames(e))if(t!=="constructor"&&!(t in J)){let r=Object.getOwnPropertyDescriptor(e,t);r&&Object.defineProperty(J,t,r)}}globalThis.performance=J;globalThis.Performance=q;globalThis.PerformanceEntry=B;globalThis.PerformanceMark=ze;globalThis.PerformanceMeasure=X;globalThis.PerformanceObserver=ce;globalThis.PerformanceObserverEntryList=le;globalThis.PerformanceResourceTiming=Y});var Pt=Yr(kt=>{"use strict";g();var ln=/^[-!#$%&'*+\/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])+$/;kt.validate=function(e){if(!e||e.length>254)return!1;var t=ln.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(o){return o.length>63})}});g();g();g();var It=new TextEncoder,de,vt;async function Zr(e){return de&&vt===e||(de=await crypto.subtle.importKey("raw",It.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),vt=e),de}a(Zr,"getSignKey");async function ue(e,t){let r=await Zr(t),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,It.encode(e)));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}a(ue,"hmacSign");var fe=new TextEncoder,K=new TextDecoder,en=5e3,me=15e3,St=15e3,tn=65536;async function rn(e,t){if(!t)throw new Error("Email signing key is not configured");return ue(e,t)}a(rn,"sign");async function V(e,t,r,n=en){let o=new AbortController,i=Date.now()+n,s=a(async m=>{let h=i-Date.now();if(h<=0)throw o.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let y=m(),b;try{return await Promise.race([y,new Promise((R,E)=>{b=setTimeout(()=>{o.abort(),E(new Error("EMAIL_ADMISSION_TIMEOUT"))},h)})])}finally{b!==void 0&&clearTimeout(b)}},"beforeDeadline"),l=JSON.stringify(r),c=await rn(l,e.EMAIL_SIGNING_SECRET),d=await s(()=>e.API.fetch(`https://api/internal/email/actions${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":c},body:l,signal:o.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 f=new Uint8Array(tn),p=0;try{for(;;){let m=await s(()=>u.read());if(m.done)break;if(p+m.value.byteLength>f.length)throw new Error("EMAIL_ADMISSION_RESPONSE_TOO_LARGE");f.set(m.value,p),p+=m.value.byteLength}return JSON.parse(K.decode(f.subarray(0,p)))}finally{u.cancel().catch(()=>{});try{u.releaseLock()}catch{}}}a(V,"call");function Tt(e,t){return V(e,"/receipts/claim",t)}a(Tt,"claimRelayedReceipt");function xt(e,t,r){return V(e,"/receipts/complete",{receiptId:t.receiptId,projectId:t.projectId,payloadDigest:t.payloadDigest,reject:r})}a(xt,"completeRelayedReceipt");function nn(e){if(on(e)===-1)return e;let t=new Map,r=[],n=0,o=0,i=!1,s=!0,l=!0,c=a(m=>{m.byteLength!==0&&(r.push(m),n+=m.byteLength)},"append"),d=a((m,h,y)=>{c(e.subarray(o,m)),c(y),o=h,i=!0},"replace"),u=0;for(;u<e.byteLength;){let m=Mt(e,u),h=m===e.byteLength?e.byteLength:m+2;if(s){if(m===u)s=!1,l=!1;else if(l&&(pe(e,u,m,"Date: ")||pe(e,u,m,"Message-ID: ")))d(u,h,new Uint8Array);else if(sn(e,u,m)){let y=m,b=h,R=K.decode(e.subarray(u,y));for(;e[b]===32||e[b]===9;)y=Mt(e,b),R+=` ${K.decode(e.subarray(b,y)).replace(/^[ \t]+/,"")}`,b=y===e.byteLength?e.byteLength:y+2;let E=R.replace(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(A,w)=>{let _=t.get(w);return _||(_=`<void-boundary-${t.size}>`,t.set(w,_)),`boundary="${_}"`});E!==R&&d(u,y,fe.encode(E)),u=b;continue}}else if(e[u]===45&&e[u+1]===45){let y=u+2,b=Nt(e,y,m)?K.decode(e.subarray(y,m)):void 0,R=b===void 0?void 0:t.get(b);if(R!==void 0)d(u,m,fe.encode(`--${R}`)),s=!0;else if(m-y>=2&&e[m-2]===45&&e[m-1]===45&&Nt(e,y,m-2)){let E=K.decode(e.subarray(y,m-2)),A=t.get(E);A!==void 0&&d(u,m,fe.encode(`--${A}--`))}}u=h}if(!i)return e;c(e.subarray(o));let f=new Uint8Array(n),p=0;for(let m of r)f.set(m,p),p+=m.byteLength;return f}a(nn,"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}a(on,"findCrlfCrlf");function Mt(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}a(Mt,"findCrlf");function pe(e,t,r,n){if(r-t<n.length)return!1;for(let o=0;o<n.length;o++){let i=e[t+o],s=n.charCodeAt(o);if((i>=65&&i<=90?i+32:i)!==(s|32))return!1}return!0}a(pe,"asciiPrefixEquals");function sn(e,t,r){let n="Content-Type:";if(!pe(e,t,r,n))return!1;let o=t+n.length;for(;o<r&&(e[o]===32||e[o]===9||e[o]===11||e[o]===12);)o++;return pe(e,o,r,"multipart/")}a(sn,"isMultipartContentType");function Nt(e,t,r){if(r<=t)return!1;for(let n=t;n<r;n++){let o=e[n];if(!(o>=65&&o<=90||o>=97&&o<=122||o>=48&&o<=57||o===95||o===45||o===61))return!1}return!0}a(Nt,"isBoundaryToken");async function ge(e,t,r,n){let o=nn(n),i=fe.encode(JSON.stringify({kind:e,from:t.toLowerCase(),recipients:[...new Set(r.map(l=>l.toLowerCase()))].sort()})),s=new Uint8Array(i.length+1+o.length);return s.set(i),s[i.length]=0,s.set(o,i.length+1),[...new Uint8Array(await crypto.subtle.digest("SHA-256",s))].map(l=>l.toString(16).padStart(2,"0")).join("")}a(ge,"emailPayloadDigest");function he(e,t,r=St){return V(e,"/admit",t,Math.min(r,St))}a(he,"admitEmail");function Q(e,t,r,n=me){return V(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Math.min(n,me))}a(Q,"startEmailAttempt");function k(e,t,r,n,o={},i=me){return V(e,`/${encodeURIComponent(t)}/finish`,{recipients:r,state:n,...o},Math.min(i,me))}a(k,"finishEmailAttempt");function G(e,t,r,n,o){return V(e,"/receipts",{receiptId:t,projectId:r,status:n,...o?{route:o}:{}})}a(G,"recordEmailReceipt");g();g();var an=new Set(["abuse","bounce","noreply","postmaster","security"]);function Ot(e){return an.has(e)}a(Ot,"isReservedEmailSlug");var kr=Kr(Pt(),1);import{EmailMessage as Or}from"cloudflare:email";g();g();var Lt="/__void/email/receipt/v1";var qe=new TextEncoder,cn=new TextDecoder("utf-8",{fatal:!0});function dn(e,t,r){let n=0,o=0,i=!1,s=!1;for(let l of e)if(i)s?s=!1:l===92?s=!0:l===34&&(i=!1);else if(l===34)i=!0;else if(l===123||l===91){if(++n>t)throw new Error("email metadata too deep")}else if(l===125||l===93){if(--n<0)throw new Error("invalid email metadata")}else if(l===58&&++o>r)throw new Error("too many email metadata fields");if(i||n!==0)throw new Error("invalid email metadata")}a(dn,"assertFlatJson");function Ct(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}a(Ct,"encodeEmailEnvelope");function Dt(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}a(Dt,"base64url");async function un(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])}a(un,"receiptKey");async function jt(e,t){let r=qe.encode(JSON.stringify(e)),n=new Uint8Array(await crypto.subtle.sign("HMAC",await un(t,"sign"),r));return`${Dt(r)}.${Dt(n)}`}a(jt,"signEmailReceipt");async function $t(e,t=15e3){return mn(e,async r=>{let n=[],o=new Uint8Array(0),i=0,s=Date.now()+t,l=a(()=>fn(r,s,"email response timeout"),"readChunk");async function c(d){let u=new Uint8Array(d),f=0;for(;f<d;){if(o.byteLength===0){let m=await l();if(m.done)throw new Error("truncated email response");if(i+=m.value.byteLength,i>8388608)throw new Error("email response too large");o=m.value}let p=Math.min(o.byteLength,d-f);u.set(o.subarray(0,p),f),o=o.subarray(p),f+=p}return u}for(a(c,"exact");;){let d=await c(5),u=new DataView(d.buffer).getUint32(0),f=d[4];if(f===0){if(u!==0||o.byteLength!==0)throw new Error("invalid email response tail");if(!(await l()).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(f!==1||u>8192||n.length>=100)throw new Error("invalid email action frame");let p=await c(u);dn(p,2,40);let m=JSON.parse(cn.decode(p));if(!m||typeof m!="object"||Array.isArray(m))throw new Error("invalid email action");let h=m;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 c(5),b=new DataView(y.buffer).getUint32(0);if(y[4]!==2||b>5242880)throw new Error("invalid email reply frame");n.push({type:"reply",from:h.from,to:h.to,raw:await c(b)})}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(b=>typeof b!="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")}})}a($t,"readEmailActions");async function fn(e,t,r){let n=t-Date.now();if(n<=0)throw new Error(r);let o;return Promise.race([e.read(),new Promise((i,s)=>{o=setTimeout(()=>s(new Error(r)),n)})]).finally(()=>{o!==void 0&&clearTimeout(o)})}a(fn,"readBeforeDeadline");async function mn(e,t){let r=e.getReader();try{return await t(r)}catch(n){throw r.cancel().catch(()=>{}),n}finally{try{r.releaseLock()}catch{}}}a(mn,"withReader");var pn=8,gn=2e4,hn=15e3,Z=new Map;async function Ve(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 o=Z.get(r.projectId)??0;if(o>=pn)throw new Error("email project concurrency exceeded");Z.set(r.projectId,o+1);let i=Date.now()+gn,s=new AbortController,l;try{let c=await jt({version:1,receiptId:n,projectId:r.projectId,deploymentId:r.deploymentId,recipient:r.envelope.to,expiresAt:Date.now()+3e4},t.EMAIL_SIGNING_SECRET),d=i-Date.now();if(d<=0)throw new Error("email tenant request timeout");let u;try{l=await Promise.race([e.fetch(`https://worker${Lt}`,{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:Ct(r.envelope),signal:s.signal}),new Promise((m,h)=>{u=setTimeout(()=>{s.abort(),h(new Error("email tenant request timeout"))},d)})])}finally{u!==void 0&&clearTimeout(u)}if(!l.ok||l.headers.get("content-encoding")||l.headers.get("content-type")!==`application/vnd.void.email-actions; version=${1}`||!l.body)throw new Error(`invalid email tenant response (${l.status})`);let f=Math.min(hn,i-Date.now());if(f<=0)throw new Error("email tenant request timeout");return{actions:await $t(l.body,f),receiptId:n}}finally{s.abort(),l?.body?.cancel().catch(()=>{});let c=(Z.get(r.projectId)??1)-1;c===0?Z.delete(r.projectId):Z.set(r.projectId,c)}}a(Ve,"dispatchBoundedEmailToTenant");g();var Ft=5e3,Ht=4*1024;function ye(e){return e.token}a(ye,"leaseBearer");async function be(e,t,r,n=Ft){if(!e.EMAIL_SIGNING_SECRET)return null;let o=new AbortController,i=Date.now()+Math.min(n,Ft),s=a(async p=>{let m=i-Date.now();if(m<=0)throw o.abort(),new Error("email credential lease timed out");let h=p(),y;try{return await Promise.race([h,new Promise((b,R)=>{y=setTimeout(()=>{o.abort(),R(new Error("email credential lease timed out"))},m)})])}finally{y!==void 0&&clearTimeout(y)}},"beforeDeadline"),l;try{let p=await ue(`email-lease-v1
|
|
2
2
|
${r}
|
|
3
|
-
${t.toLowerCase()}`,e.EMAIL_SIGNING_SECRET);a=await s(()=>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:o.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)>Gt))return a.body?.cancel().catch(()=>{}),null;let d=a.body?.getReader();if(!d)return null;let u=new Uint8Array(Gt),m=0;try{for(;;){let f=await s(()=>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 wn(p)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}l(be,"leaseEmailDomainCredential");function wn(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(wn,"parseLease");g();var Ee=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 o=Math.min(3e4,t-Date.now()-n);if(o<=0)throw new Ee;let i=r(),s;try{return await Promise.race([i,new Promise((a,c)=>{s=setTimeout(()=>c(new Ee),o)})])}finally{s!==void 0&&clearTimeout(s)}}}}l(we,"createEmailProviderDeadline");g();import{EmailMessage as jn}from"cloudflare:email";g();g();g();g();g();var zt=Symbol();g();g();g();var Vt=l((e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData(),"bufferToFormData");var Rn=1e4,Re=l(e=>"headers"in e,"isRawRequest"),Xt=l(async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,o=(Re(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?An(e,{all:r,dot:n}):{}},"parseBody");async function An(e,t){if(!Re(e)&&e.bodyCache.formData)return qt(await e.bodyCache.formData,t);let r=Re(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=Vt(n,r.get("Content-Type")||"");Re(e)||(e.bodyCache.formData=o);let i=await o;return i?qt(i,t):{}}l(An,"parseFormData");function qt(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,i)=>{t.all||i.endsWith("[]")?_n(r,i,o):r[i]=o}),t.dot&&Object.entries(r).forEach(([o,i])=>{o.includes(".")&&(In(r,o,i,n),delete r[o])}),r}l(qt,"convertFormDataToBodyData");var _n=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"),In=l((e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,i=t.split(".",34);i.length>33&&Wt(),i.forEach((s,a)=>{a===i.length-1?o[s]=r:((!o[s]||typeof o[s]!="object"||Array.isArray(o[s])||o[s]instanceof File)&&(n.count++>=Rn&&Wt(),o[s]=Object.create(null)),o=o[s])})},"handleParsingNestedValues"),Wt=l(()=>{throw new Error("Nesting limit exceeded")},"throwNestingLimitExceeded");g();var Xe=l(e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},"splitPath"),Jt=l(e=>{let{groups:t,path:r}=vn(e),n=Xe(r);return Sn(n,t)},"splitRoutingPath"),vn=l(e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},"extractGroupsFromPath"),Sn=l((e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},"replaceGroupMarks"),Ae={},Yt=l((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"),Kt=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"),Mn=l(e=>Kt(e,decodeURI),"tryDecodeURI"),Je=l(e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let i=t.indexOf("?",n),s=t.indexOf("#",n),a=i===-1?s===-1?void 0:s:s===-1?i:Math.min(i,s),c=t.slice(r,a);return Mn(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)},"getPath");var Qt=l(e=>{let t=Je(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},"getPathNoStrict"),C=l((e,t,...r)=>(r.length&&(t=C(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),"mergePath"),_e=l(e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let i=o.slice(0,-1);n+="/"+i,r.push(n)}else n+="/"+o}),r.filter((o,i,s)=>s.indexOf(o)===i)},"checkOptionalParameter"),Ie=l(e=>e.indexOf("%")!==-1?Kt(e,Nn):e,"tryDecodeURIComponent"),We=l(e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Ie(e)),"_decodeURI"),Zt=l((e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;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 We(e.slice(d,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(o=/[%+]/.test(e),!o)return}let i=Object.create(null);o??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let a=e.indexOf("&",s+1),c=e.indexOf("=",s);c>a&&a!==-1&&(c=-1);let d=e.slice(s+1,c===-1?a===-1?void 0:a:c);if(o&&(d=We(d)),s=a,d==="")continue;let u;c===-1?u="":(u=e.slice(c+1,a===-1?void 0:a),o&&(u=We(u))),r?(i[d]&&Array.isArray(i[d])||(i[d]=[]),i[d].push(u)):i[d]??=u}return t?i[t]:i},"_getQueryParam"),er=Zt,tr=l((e,t)=>Zt(e,t,!0),"getQueryParams"),Nn=decodeURIComponent;var rr=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.#s()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#n(t);return r&&Ie(r)}#s(){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]=Ie(n))}return e}#n(e){return this.#e[1]?this.#e[1][e]:e}query(e){return er(this.url,e)}queries(e){return tr(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 Xt(this,e)}#o=l(e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let o in t)return t[o].then(i=>{o==="json"&&(i=JSON.stringify(i));let s=o==="formData"?void 0:r.headers.get("content-type");return new Response(i,{headers:s?{"Content-Type":s}:void 0})[e]()});return t[e]=r[e]()},"#cachedBody");json(){return this.#o("text").then(e=>JSON.parse(e))}text(){return this.#o("text")}arrayBuffer(){return this.#o("arrayBuffer")}bytes(){return this.#o("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#o("blob")}formData(){return this.#o("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[zt](){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 nr={Stringify:1,BeforeStream:2,Stream:3},Tn=l((e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},"raw");var Ye=l(async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let i=e.callbacks;if(!i?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let s=Promise.all(i.map(a=>a({phase:t,buffer:o,context:n}))).then(a=>Promise.all(a.filter(Boolean).map(c=>Ye(c,t,!1,n,o))).then(()=>o[0]));return r?Tn(await s,i):s},"resolveCallback");var xn="text/plain; charset=UTF-8",Ke=l((e,t)=>({"Content-Type":e,...t}),"setDefaultContentType"),ee=l((e,t)=>new Response(e,t),"createResponseInstance"),Qe=class{static{l(this,"Context")}#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#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 rr(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.#o||=ee(null,{headers:this.#a??=new Headers})}set res(e){if(this.#o&&e){e=ee(e.body,e);for(let[t,r]of this.#o.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#o.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#o=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.#o=ee(this.#o.body,this.#o));let n=this.#o?this.#o.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.#s=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):{}}#i(e,t,r){let n=this.#o?new Headers(this.#o.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[i,s]of new Headers(t.headers))i==="set-cookie"?n.append(i,s):n.set(i,s)}if(r){if(!n){let i=0;for(let s in r)if(++i>1||typeof r[s]!="string"){n=new Headers;break}}if(n)for(let i in r){let s=r[i];if(typeof s=="string")n.set(i,s);else{n.delete(i);for(let a of s)n.append(i,a)}}}let o=typeof t=="number"?t:t?.status??this.#s;return ee(e,{status:o,headers:n??r})}newResponse=l((...e)=>this.#i(...e),"newResponse");body=l((e,t,r)=>this.#i(e,t,r),"body");text=l((e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,Ke(xn,r)),"text");json=l((e,t,r)=>this.#i(JSON.stringify(e),t,Ke("application/json",r)),"json");html=l((e,t,r)=>{let n=l(o=>this.#i(o,t,Ke("text/html; charset=UTF-8",r)),"res");return typeof e=="object"?Ye(e,nr.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??=()=>ee(),this.#c(this)),"notFound")};g();g();g();var Ze=l((e,t,r)=>(n,o)=>{let i=-1;return s(0);async function s(a){if(a<=i)throw new Error("next() called multiple times");i=a;let c,d=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{c=await u(n,()=>s(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 or=["get","post","put","delete","options","patch","query"],ve="Can not add a route since the matcher is already built.",Se=class extends Error{static{l(this,"UnsupportedPathError")}};g();var sr="__COMPOSED_HANDLER";var On=l(e=>e.text("404 Not Found",404),"notFoundHandler"),ir=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"),ar=class lr{static{l(this,"Hono")}get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...or,"all"].forEach(o=>{this[o]=(i,...s)=>{let a=o.toUpperCase();return typeof i=="string"?this.#t=i:this.#s(a,this.#t,i),s.forEach(c=>{this.#s(a,this.#t,c)}),this}}),this.on=(o,i,...s)=>{for(let a of[i].flat()){this.#t=a;for(let c of[o].flat()){let d=c.toUpperCase();for(let u of s)this.#s(d,this.#t,u)}}return this},this.use=(o,...i)=>(typeof o=="string"?this.#t=o:(this.#t="*",i.unshift(o)),i.forEach(s=>{this.#s("ALL",this.#t,s)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??Je:Qt}#e(){let t=new lr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=On;errorHandler=ir;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let i;r.errorHandler===ir?i=o.handler:(i=l(async(s,a)=>(await Ze([],r.errorHandler)(s,()=>o.handler(s,a))).res,"handler"),i[sr]=o.handler),n.#s(o.method,o.path,i,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=C(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 o,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===!1?o=l(c=>c,"replaceRequest"):o=n.replaceRequest));let s=i?c=>{let d=i(c);return Array.isArray(d)?d:[d]}:c=>{let d;try{d=c.executionCtx}catch{}return[c.env,d]};o||=(()=>{let c=C(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(o(c.req.raw),...s(c));if(u)return u;await d()},"handler");return this.#s("ALL",C(t,"*"),a),this}#s(t,r,n,o){r=C(this._basePath,r);let i={basePath:o!==void 0?C(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,i]),this.routes.push(i)}#n(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#o(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#o(t,r,n,"GET")))();let i=this.getPath(t,{env:n}),s=this.router.match(o,i),a=new Qe(t,{path:i,matchResult:s,env:n,executionCtx:r,notFoundHandler:this.#r});if(s[0].length===1){let d;try{d=s[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=Ze(s[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.#o(t,r[1],r[0],t.method),"fetch");request=l((t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${C("/",t)}`,r),n,o)),"request");fire=l(()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})},"fire")};g();g();var v=l(()=>Object.create(null),"createNullObject");g();var Me=[];function et(e,t){let r=this.buildAllMatchers(),n=l(((o,i)=>{let s=r[o]||r.ALL,a=s[2][i];if(a)return a;let c=i.match(s[0]);if(!c)return[[],Me];let d=c.indexOf("",1);return[s[1][d],c]}),"match");return this.match=n,n(e,t)}l(et,"match");g();var rt="[^/]+";var nt="(?:|/.*)",j=Symbol(),cr=new Set(".\\+*[^]$()");function kn(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(kn,"compareKey");var dr=class tt{static{l(this,"Node")}#t;#e;#r=v();insert(t,r,n,o,i){let s=this;for(let a=0,c=t.length;a<c;a++){let d=t[a],u=d.length===1?d==="*"?a===c-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=s.#r[f],!m){if(f!==".*"&&f!=="(?:|/.*)"){for(let h in s.#r)if((f.length>1||h.length>1)&&h!==".*"&&h!=="(?:|/.*)")throw j}m=s.#r[f]=new tt}p!==""&&(m.#e??=o.varIndex++,n.push([p,m.#e]))}else if(m=s.#r[d],!m){for(let p in s.#r)if(p.length>1&&p!==".*"&&p!=="(?:|/.*)")throw j;m=s.#r[d]=new tt}s=m}if(s.#t!==void 0)throw j;s.#t=i?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(kn).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:cr.has(r)?`\\${r}`:r)+o}).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 ot=class{static{l(this,"Trie")}#t={varIndex:0};#e=new dr;#r=0;paths=v();insert(e,t){if(t){this.#e.insert(e.split(""),0,[],this.#t,!0);return}let r=[],n=[],o=e;for(let s=0;;){let a=!1;if(o=o.replace(/\{[^}]+\}/g,c=>{let d=`@\\${s}`;return n[s]=[d,c],s++,a=!0,d}),!a)break}let i=o.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=n.length-1;s>=0;s--){let[a]=n[s];for(let c=i.length-1;c>=0;c--)if(i[c].indexOf(a)!==-1){i[c]=i[c].replace(a,n[s][1]);break}}this.#e.insert(i,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,(o,i,s)=>i!==void 0?(r[++t]=Number(i),"$()"):(s!==void 0&&(n[Number(s)]=++t),"")),[new RegExp(`^${e}`),r,n]}};var ur=v();function fr(e){return ur[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?nt:t==="*"?".*":`/:${rt}`)}$`)}l(fr,"buildWildcardRegExp");function Ne(e,t){for(let r of Object.keys(e).sort((n,o)=>o.length-n.length))if(fr(r).test(t))return[...e[r]]}l(Ne,"findMiddleware");var Te=class{static{l(this,"RegExpRouter")}name="RegExpRouter";#t;#e;#r;constructor(){this.#t={ALL:v()},this.#e={ALL:v()},this.#r={ALL:new ot}}#s(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,o=this.#e;if(!n)throw new Error(ve);if(!n[e]){this.#r[e]=new ot;for(let a of[n,o]){a[e]=v();for(let c in a.ALL)a[e][c]=[...a.ALL[c]],this.#s(e,c)}}t==="/*"&&(t="*");let i=e==="ALL"?Object.keys(n):[e];if(/\*$/.test(t)){let a=fr(t);for(let c of i)n[c][t]||(this.#s(c,t),n[c][t]=Ne(n[c],t)||Ne(n.ALL,t)||[]);for(let c of[n,o])for(let d of i)for(let u in c[d])a.test(u)&&c[d][u].push([r,t]);return}let s=_e(t)||[t];for(let a of s)for(let c of i)o[c][a]||(this.#s(c,a),o[c][a]=Ne(n[c],a)||Ne(n.ALL,a)||[]),o[c][a].push([r,a])}match=et;buildAllMatchers(){let e=v();for(let t of Object.keys(this.#e))e[t]=this.#n(t);return this.#t=this.#e=this.#r=void 0,ur=v(),e}#n(e){let t=this.#t[e],r=this.#e[e],n=this.#r[e],o=v(),i=[],[s,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){o[u]=[m.map(([f])=>[f,v()]),Me];continue}i[p[0]]=m.map(([f,h])=>[f,n.paths[h][1].reduceRight((y,[b],R)=>(y[b]=c[p[1][R][1]],y),v())])}return[s,a.map(d=>i[d]),o]}};g();g();g();var mr=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(ve);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,i=0,s;for(;i<o;i++){let a=r[i];try{for(let c=0,d=n.length;c<d;c++)a.add(...n[c]);s=a.match(e,t)}catch(c){if(c instanceof Se)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(i===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}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 st=v(),Pn=0,pr=class gr{static{l(this,"Node")}#t=[];#e=v();#r=[];#s;#n=st;insert(t,r,n){let o=this,i=Jt(r),s=new Set,a=0;for(let c of i){let d=i[++a],u=Yt(c,d)||(d===void 0&&c&&c.indexOf("*")===c.length-1?c:null),m=Array.isArray(u),p=m?u[0]:u||c,f=o.#e[p]||=new gr;u&&!f.#s&&(f.#s=u,o.#r.push(f)),o=f,m&&s.add(u[1])}o.#t.push({[t]:{handler:n,possibleKeys:[...s],score:++Pn}})}#o(t,r,n,o,i){for(let s=0,a=r.#t.length;s<a;s++){let c=r.#t[s],d=c[n]||c.ALL;if(d){d.params=v(),t.push(d);for(let u=0,m=d.possibleKeys.length;u<m;u++){let p=d.possibleKeys[u];d.params[p]=i?.[p]&&!u?i[p]:o[p]??i?.[p]}}}}search(t,r){let n=[];this.#n=st;let o=[this],i=Xe(r),s=[],a=i.length,c=null;for(let d=0;d<a;d++){let u=i[d],m=d===a-1,p=[];for(let h=0,y=o.length;h<y;h++){let b=o[h],R=b.#e[u];R&&(R.#n=b.#n,m?(R.#e["*"]&&this.#o(n,R.#e["*"],t,b.#n),this.#o(n,R,t,b.#n)):p.push(R));for(let w of b.#r){let A=w.#s,E=b.#n===st?{}:{...b.#n};if(typeof A=="string"){(A==="*"||u.startsWith(A.slice(0,-1)))&&(this.#o(n,w,t,b.#n),A==="*"&&(w.#n=E,p.push(w)));continue}let[,_,M]=A;if(!(!u&&M===!0)){if(M!==!0){if(!c){c=[];let x=r[0]==="/"?1:0;for(let P=0;P<a;P++)c[P]=x,x+=i[P].length+1}let O=r.slice(c[d]),T=M.exec(O);if(T){E[_]=T[0],this.#o(n,w,t,b.#n,E),T[0].length===O.length&&w.#e["*"]&&this.#o(n,w.#e["*"],t,b.#n,E);for(let x in w.#e){w.#n=E;let P=T[0].match(/\//g)?.length??0;(s[P]||=[]).push(w);break}continue}}(M===!0||M.test(u))&&(E[_]=u,m?(this.#o(n,w,t,E,b.#n),w.#e["*"]&&this.#o(n,w.#e["*"],t,E,b.#n)):(w.#n=E,p.push(w)))}}}let f=s.shift();o=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 it=class{static{l(this,"TrieRouter")}name="TrieRouter";#t=new pr;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 ar{static{l(this,"Hono")}constructor(e={}){super(e),this.router=e.router??new mr({routers:[new Te,new it]})}};g();g();g();g();g();g();g();g();g();g();g();function te(e){return typeof e=="string"?e:null}l(te,"asString");var $n=new at,Un=5e4,z=5e3,xe=5*1024*1024,Fn=16*1024,Hn=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 Bn(e){let t=0,r=!1;for(let n=0;n<e.byteLength;){let o=n;for(;o<e.byteLength&&e[o]!==10;)o++;let i=o>n&&e[o-1]===13?o-1:o;if(i===n)return!0;if(e[n]!==32&&e[n]!==9){let s=n;for(;s<i&&e[s]!==58;)s++;let a=new TextDecoder().decode(e.subarray(n,s)).toLowerCase();r=s<i&&!Hn.has(a)}if(r&&(t+=i-n+2,t>Fn))return!1;n=o+1}return!0}l(Bn,"customMimeHeaderBytesWithinLimit");var yr=50,br=320,Er=320;function re(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(re,"readSenderDomain");var Gn=/[.*+?^${}()|[\]\\]/g;function zn(e){return e.replace(Gn,"\\$&")}l(zn,"escapeRegExp");var wr=new Map;function Vn(e){let t=wr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${zn(e)}$`);return wr.set(e,r),r}l(Vn,"strictFromRe");var qn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function I(e,t=200){return e.slice(0,t).replace(qn," ")}l(I,"sanitizeForLog");var Wn=128;function ne(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}l(ne,"bytesToStream");var Rr=10,Oe=13,_r=32,Ir=9,Xn=58,ke=[102,114,111,109];function Jn(e,t,r){if(r-t<=ke.length)return-1;for(let o=0;o<ke.length;o++)if((e[t+o]|32)!==ke[o])return-1;let n=t+ke.length;for(;n<r&&(e[n]===_r||e[n]===Ir);)n++;return n<r&&e[n]===Xn?n+1:-1}l(Jn,"fromValueStart");var Yn={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,o=-1,i=!1,s=!1,a=e.indexOf(Oe),c=0;for(;c<t;){let m=e.indexOf(Rr,c),f=m===-1?t:m;if(f>c&&e[f-1]===Oe&&f--,f===c)break;if(a!==-1&&a<c&&(a=e.indexOf(Oe,c)),a!==-1&&a<f)return{ok:!1,reason:"malformed"};if(e[c]===_r||e[c]===Ir)s&&(o=f,i=!0);else{let h=Jn(e,c,f);s=h!==-1,s&&(r++,n=h,o=f,i=!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,o);if(i){d=e.slice(n,o);let m=0;for(let p=0;p<d.length;p++){let f=d[p];f!==Oe&&f!==Rr&&(d[m++]=f)}d=d.subarray(0,m)}let u=Kn(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}l(dt,"readMimeFromAddrSpec");function Kn(e){let t=!1,r=!1,n=-1,o=-1,i=-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||o!==-1)return null;o=a;break;case"@":i===-1&&(i=a);break;case",":case";":case":":case"(":case")":case"[":case"]":case"\\":return null;default:break}}if(t)return null;let s;if(n===-1)s=e.trim();else{if(o===-1||e.slice(o+1).trim().length!==0||i!==-1&&i<n)return null;s=e.slice(n+1,o)}return/^[\x21-\x7e]+$/.test(s)?s:null}l(Kn,"singleMailboxAddrSpec");$n.post("/send",async e=>{let t=we(Un),r=e.get("projectId"),n=e.get("body"),o=te(n.from),i=te(n.mimeBase64),s=te(n.requestId),a=s===null?"unknown":I(s,Wn),c=te(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??(s&&s.length<=128&&/^[\x20-\x7e]+$/.test(s)?s:crypto.randomUUID()),u=Array.isArray(n.recipients)?n.recipients:null;if(!o||!i||!u)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"invalid body"}},400);if(u.length>yr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`too many recipients (max ${yr}, got ${u.length})`}},413);if(o.length>Er)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${Er} characters`}},413);let m=re(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>br)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${br} characters`}},413);let N=S.trim().toLowerCase();!N||f.has(N)||(f.add(N),p.push(N))}if(p.length===0)return e.json({ok:!1,error:{code:"INVALID_TO",message:"no recipients"}},200);if(i.length>Math.ceil(xe*4/3)+4)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${xe} bytes (base64 length ${i.length})`}},413);let h;try{h=Zn(i)}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(!Bn(h))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let y=o.indexOf("@"),b=y===-1?"":o.slice(y+1).toLowerCase();if(b!==""&&b!==m)return Qn(e,r,o,b,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 w=o.split("@")[0]?.split("+")[0]??"";if(!/^[\x21-\x7e]+$/.test(o))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let A=o.toLowerCase();if(!Vn(m).test(A))return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${w}>[+tag]@${m}`}},200);if((A.slice(0,A.indexOf("@")).split("+")[0]??"")!==w.toLowerCase())return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${w}>[+tag]@${m}`}},200);let M=Sr(e,h,o);if(M)return M;let O=await Mr(e,t,{projectId:r,operationKey:d,from:o,recipients:p,raw:h,transport:"binding"});if(O instanceof Response)return O;let{admission:T,deliveries:x}=O,P=T.recipients.filter(S=>S.state==="reserved").map(S=>S.recipient);for(let S=0;S<P.length;S++){let N=P[S];if(t.expired(z)){let F=P.slice(S),W=await lt(e.env,T.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 Q(e.env,T.operationId,[N],t.remainingMs(z))}catch{let F=await lt(e.env,T.operationId,[N],t.remainingMs());x.push({recipient:N,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 jn(o,N,ne(h)),W=await t.run(()=>R.send(F),z),ie=typeof W?.messageId=="string"?W.messageId:"";try{await k(e.env,T.operationId,[N],"provider_accepted",{providerReference:ie},t.remainingMs())}catch{x.push({recipient:N,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider accepted email but outcome could not be recorded"}});continue}x.push({recipient:N,ok:!0,state:"provider_accepted",messageId:ie})}catch{try{await k(e.env,T.operationId,[N],"outcome_unknown",{errorCode:"OUTCOME_UNKNOWN"},t.remainingMs())}catch{}x.push({recipient:N,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"}})}}return Nr(r,a,x),x.some(S=>!S.ok)?e.json({ok:!1,operationId:T.operationId,deliveries:x},200):e.json({ok:!0,operationId:T.operationId,ids:x.map(S=>({recipient:S.recipient,messageId:S.messageId,state:"provider_accepted"}))})});var Ar=64*1024;async function ut(e,t=3e4){let r=new AbortController,n=Date.now()+Math.min(3e4,t),o=JSON.stringify({from:e.from,recipients:e.recipients,mime_message:e.mimeMessage}),i=l(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,b)=>{h=setTimeout(()=>{r.abort(),b(new Error("email sending request timed out"))},p)})])}finally{h!==void 0&&clearTimeout(h)}},"beforeDeadline"),s=await i(()=>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:o,signal:r.signal}));if(!s.ok)return s.body?.cancel().catch(()=>{}),{ok:!1,status:s.status};let a=s.headers.get("content-length");if(a!==null&&(!/^\d+$/.test(a)||Number(a)>Ar))throw s.body?.cancel().catch(()=>{}),new Error("email sending API response too large");let c=s.body?.getReader();if(!c)throw new Error("email sending API response unreadable");let d=new Uint8Array(Ar),u=0;try{for(;;){let m=await i(()=>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(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}l(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),o=Pe(t.queued),i=Pe(t.suppressed_recipients);return!r||!n||!o||!i||typeof t.message_id!="string"||t.message_id===""?null:{delivered:r,messageId:t.message_id,permanentBounces:n,queued:o,suppressedRecipients:i}}l(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"}l(mt,"classifySendRawRecipient");async function Qn(e,t,r,n,o,i,s,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=Sr(e,s,r);if(u)return u;let m;try{m=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(s)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"mime must be valid UTF-8"}},400)}let p=await Mr(e,d,{projectId:t,operationKey:c,from:r,recipients:i,raw:s,transport:"send_raw"});if(p instanceof Response)return p;let{admission:f,deliveries:h}=p;if(i=f.recipients.filter(E=>E.state==="reserved").map(E=>E.recipient),i.length===0)return ct(e,f.operationId,h);let y=await be(e.env,n,t,d.remainingMs(z));if(!y)return await k(e.env,f.operationId,i,"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,i,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"email domain changed during admission"}},503);try{await Q(e.env,f.operationId,i,d.remainingMs(z))}catch{let E=await lt(e.env,f.operationId,i,d.remainingMs());for(let _ of i)h.push({recipient:_,ok:!1,state:E?"cancelled":"outcome_unknown",error:E?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return ct(e,f.operationId,h)}let b=null,R="failed",w=null,A=null;try{A=await ut({accountId:y.accountId,bearer:ye(y),from:r,recipients:i,mimeMessage:m},d.remainingMs(z))}catch{b={code:"UPSTREAM_ERROR",message:"email sending request failed"},R="outcome_unknown"}if(A)if(!A.ok)b={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 E=A.data,_=typeof E=="object"&&E!==null?E.success:void 0;_===!1?b={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:_!==!0?(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"):(w=ft(E.result),w||(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"))}for(let E of i){if(b){h.push({recipient:E,ok:!1,state:R,error:b});continue}let _=mt(w,E);_==="permanent_bounce"?h.push({recipient:E,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${E}' permanently bounced`}}):_==="suppressed"?h.push({recipient:E,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${E}' is on the suppression list`}}):_==="outcome_unknown"?h.push({recipient:E,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):h.push({recipient:E,ok:!0,state:"provider_accepted",messageId:w.messageId})}for(let E of h.filter(_=>f.recipients.some(M=>M.recipient===_.recipient&&M.state==="reserved")))try{await k(e.env,f.operationId,[E.recipient],E.ok?"provider_accepted":E.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:E.messageId,errorCode:E.ok?void 0:E.state==="outcome_unknown"?"OUTCOME_UNKNOWN":b?.code??E.error?.code},d.remainingMs()),E.state=E.ok?"provider_accepted":E.state==="outcome_unknown"?"outcome_unknown":"failed",E.state==="outcome_unknown"&&!E.ok&&(E.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{E.ok=!1,E.state="outcome_unknown",E.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return Nr(t,a,h),h.some(E=>!E.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:h},200):e.json({ok:!0,operationId:f.operationId,ids:h.map(E=>({recipient:E.recipient,messageId:E.messageId,state:"provider_accepted"}))})}l(Qn,"sendViaCustomDomain");async function vr(e,t){console.log(`[email-recv] ${e} ${I(t.from,320)} -> ${I(t.to,320)} ${t.status} (${t.byteSize}B) @${Date.now()}`)}l(vr,"recordInboundDelivery");function Sr(e,t,r){let n=dt(t);if(n.ok&&n.addrSpec.toLowerCase()===r.toLowerCase())return null;let o=n.ok?"the From header address does not match the envelope sender":Yn[n.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${o}`}},403)}l(Sr,"refuseMimeFromMismatch");async function Mr(e,t,r){let{projectId:n,operationKey:o,from:i,recipients:s,raw:a,transport:c}=r,d;try{d=await he(e.env,{projectId:n,kind:"direct",key:o,digest:await ge("direct",i,s,a),from:i,recipients:s,transport:c},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 ct(e,d.operationId,u)}return{admission:d,deliveries:u}}l(Mr,"admitDirectSend");async function lt(e,t,r,n){try{let o=await k(e,t,r,"cancelled",{},n);return r.every(i=>o.recipients.some(s=>s.recipient===i&&s.state==="cancelled"))}catch{return!1}}l(lt,"cancelUnstartedRecipients");function ct(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(ct,"emailActionResponse");function Nr(e,t,r){for(let n of r){let o=n.ok?"sent":n.error?.code??"unknown_error",i=n.messageId??"";console.log(`[email-log] ${e} ${t} ${I(n.recipient,320)} ${o} ${i} @${Date.now()}`)}}l(Nr,"logSend");function Zn(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(Zn,"base64Decode");function oe(e,t){switch(typeof e){case"string":return I(e,t);case"number":case"boolean":case"undefined":return String(e);case"object":return e===null?"null":I(Object.prototype.toString.call(e),64);default:return`[${typeof e}]`}}l(oe,"describeUntrusted");function Cr(e){let t=[e.slug,e.alias,e.mailbox].filter(r=>typeof r=="string").map(r=>r.toLowerCase());return[...new Set(t)]}l(Cr,"mailboxNames");function eo(e){return{routeId:e.routeId,routeGeneration:e.routeGeneration,connectionId:e.connectionId,addressing:e.addressing,domain:e.domain,projectSlug:e.slug}}l(eo,"receiptRouteFence");var D=10*1024*1024,se=1024,ht=128*1024,to=1e3,Tr=100,jr=320,xr=32,Le=1024,Or=5*1024*1024,kr=8*1024*1024,ro=15e3,Ce=class extends Error{constructor(r){super(`inbound message exceeds ${D} bytes (got ${r})`);this.size=r;this.name="InboundTooLargeError"}size;static{l(this,"InboundTooLargeError")}},je=class extends Error{static{l(this,"InboundTooManyHeadersError")}constructor(){super(`inbound message carries more than ${se} headers`),this.name="InboundTooManyHeadersError"}},$e=class extends Error{static{l(this,"InboundHeadersTooLargeError")}constructor(){super(`inbound headers exceed ${ht} bytes`),this.name="InboundHeadersTooLargeError"}};function pt(e){return typeof e=="string"&&e.length<=jr&&(0,Lr.validate)(e)}l(pt,"isValidEmailAddress");function $(e){return oe(e,jr)}l($,"logAddress");function no(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>xr)return console.error(`[email-router] action list dropped: forward has ${r.length} headers (max ${xr})`),!1;for(let n of r){let o=e[n];if(n.length>Le)return console.error(`[email-router] action list dropped: forward header name exceeds ${Le} characters`),!1;if(typeof o!="string")return console.error(`[email-router] action list dropped: forward header "${I(n,64)}" value is not a string`),!1;if(o.length>Le)return console.error(`[email-router] action list dropped: forward header "${I(n,64)}" value exceeds ${Le} characters`),!1}return!0}l(no,"forwardHeadersWithinBounds");function oo(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:t.names.includes(r.slice(0,n).split("+")[0])}l(oo,"isPermittedReplySender");async function $r(e,t,r,n){let o=re(t)??"void email",i=String(e.to??"").toLowerCase(),s=i.split("@")[0]??"",a=s.indexOf("+"),c=a===-1?s:s.slice(0,a),d=(n.mailbox??n.slug).toLowerCase(),u=i.indexOf("@"),m=u===-1?"":i.slice(u+1);if(!c){e.setReject(`${o}: missing project slug in recipient`);return}if(n.addressing!=="custom"&&Pt(c)){e.setReject(`${o}: "${I(c,64)}" is a reserved platform address`);return}if(!n.projectId||!n.workerName||!n.deploymentId||n.domain?.toLowerCase()!==m||n.addressing==="shared"&&d!==c){e.setReject(`${o}: authoritative route mismatch`);return}let p=n.workerName,f=n.projectId,h;try{h=n.limits?t.DISPATCH.get(p,{},{limits:n.limits}):t.DISPATCH.get(p)}catch(A){throw console.error(`[email-router] DISPATCH.get(${I(p,320)}) failed:`,A),new Error("email worker temporarily unavailable")}if(typeof e.rawSize=="number"&&e.rawSize>D){e.setReject(`${o}: message too large (max ${D} bytes)`);return}let y;try{y=await ao(e),n.addressing==="custom"&&(y.viaDomain=m)}catch(A){if(A instanceof Ce){e.setReject(`${o}: message too large (max ${D} bytes)`);return}if(A instanceof je){e.setReject(`${o}: too many headers (max ${se})`);return}if(A instanceof $e){e.setReject(`${o}: headers too large (max ${ht} bytes)`);return}console.error(`[email-router] failed to read message body for ${I(c,64)}:`,A),e.setReject(`${o}: could not read inbound message body`);return}let b=crypto.randomUUID(),R={projectId:f,receiptId:b,transport:"native"},w;try{await G(t,b,f,"received",eo(n))}catch{throw new Error("email admission temporarily unavailable")}try{w=(await qe(h,t,{projectId:f,deploymentId:n.deploymentId,envelope:y,receiptId:b})).actions}catch(A){await G(t,b,f,"handler_failed").catch(()=>{});let E=A instanceof Error?A.message.slice(0,320):oe(A,320);throw console.error(`[email-router] dispatch to ${I(p,320)} failed:`,E),new Error("email handler execution unresolved")}try{await G(t,b,f,"handler_completed")}catch{console.error("[email-router] handler completed but receipt status could not be saved");return}try{await Fr(t,e,w,R,{customDomain:n.addressing==="custom",names:Cr(n),domain:m})}catch{console.error("[email-router] action execution unresolved",b);return}r.waitUntil(gt(t,f,e,w))}l($r,"routeInbound");async function Ur(e,t,r){let{stub:n,projectId:o,domain:i,envelope:s,authoritative:a,receiptId:c}=r;if(a.projectId!==o||!a.workerName||!a.slug||a.domain?.toLowerCase()!==i)return{reject:!0};let d=a.slug,u=a.workerName,m=so(s),p={projectId:o,receiptId:c,transport:"relay"},f;try{f=(await qe(n,e,{projectId:o,deploymentId:a.deploymentId,envelope:s,receiptId:c})).actions}catch(h){await G(e,c,o,"handler_failed").catch(()=>{});let y=h instanceof Error?h.message.slice(0,320):oe(h,320);return console.error(`[email-relay] dispatch to ${I(u,320)} failed:`,y),t.waitUntil(gt(e,o,m.message,[{type:"reject",reason:"dispatch-error"}])),{reject:!0,temporary:!0}}try{await G(e,c,o,"handler_completed")}catch{return console.error("[email-relay] handler completed but receipt status could not be saved"),{reject:!1}}try{await Fr(e,m.message,f,p,{customDomain:a.addressing==="custom",names:Cr(a),domain:i})}catch{return console.error("[email-relay] action execution unresolved",c),{reject:!1}}return t.waitUntil(gt(e,o,m.message,f)),{reject:m.rejectedReason()!==null}}l(Ur,"routeRelayed");function so(e){let t=null;return{message:{from:e.from,to:e.to,rawSize:e.rawSize,headers:new Headers(e.headers),raw:ne(e.raw),setReject(n){t=n},async forward(n,o){throw new U("relayed forward requires a native email event")}},rejectedReason:l(()=>t,"rejectedReason")}}l(so,"createRelayedMessage");async function io(e,t,r,n,o){let i=r.slice(r.indexOf("@")+1).toLowerCase();if(i===re(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 Dr(r,d,ne(n))))?.messageId}let s=await be(e,i,t);if(!s||o&&s.accountId!==o)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 ut({accountId:s.accountId,bearer:ye(s),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=ft(m.result);if(!p)throw new Error("email sending API response invalid");let f=mt(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(io,"prepareRelayedReply");async function gt(e,t,r,n){if(!t){console.error(`[email-router] cannot log inbound delivery: routing entry has no projectId (to=${I(String(r.to??""),320)})`);return}let o=n.some(i=>i&&typeof i=="object"&&i.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:o})}catch(i){console.error("[email-router] log-recv failed:",i)}}l(gt,"logRecv");async function ao(e){let t=[],r=0,n=new TextEncoder;for(let s of e.headers){if(t.length>=se)throw new je;if(r+=n.encode(s[0]).byteLength+n.encode(s[1]).byteLength,r>ht)throw new $e;t.push(s)}let o=await lo(e.raw),i=Object.fromEntries(t);return{from:String(e.from??""),to:String(e.to??""),headers:i,raw:o,rawSize:e.rawSize??o.byteLength}}l(ao,"buildEnvelope");async function lo(e){let t=e.getReader(),r=[],n=0,o=Date.now()+ro;try{for(;;){let a=o-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>D)throw new Ce(n);r.push(d)}}catch(a){throw t.cancel().catch(()=>{}),a}finally{try{t.releaseLock()}catch{}}let i=new Uint8Array(n),s=0;for(let a of r)i.set(a,s),s+=a.byteLength;return i}l(lo,"readStreamToBytes");var U=class extends Error{static{l(this,"DefinitiveEmailActionError")}};async function co(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 o of e){if(!o||typeof o!="object")return console.error(`[email-router] dropping non-object action: ${oe(o,320)}`),null;if(o.type==="reject"){let i=typeof o.reason=="string"?o.reason:"",s=i.length>0?I(i,to):"rejected by handler";return r.push({type:"reject",reason:s}),r}if(o.type==="forward"){if(!pt(o.to))return console.error(`[email-router] forward dropped: invalid "to" address ${$(o.to)}`),null;let i;if(o.headers){if(!no(o.headers))return null;try{i=new Headers(o.headers)}catch(s){return console.error("[email-router] action list dropped: forward headers invalid:",s instanceof Error?I(s.message,320):I(String(s),320)),null}}r.push({type:"forward",to:o.to,headers:i})}else if(o.type==="reply"){if(!pt(o.from)||!pt(o.to))return console.error(`[email-router] reply dropped: invalid address (from=${$(o.from)} to=${$(o.to)})`),null;if(!oo(o.from,t))return console.error(`[email-router] reply dropped: sender not owned by project "${I(t.names[0]??"",64)}" (from=${$(o.from)})`),null;if(!(o.raw instanceof Uint8Array))return console.error(`[email-router] reply dropped: raw is not a Uint8Array (from=${$(o.from)})`),null;let i=o.raw.byteLength;if(i>Or)return console.error(`[email-router] reply dropped: raw is ${i} bytes (max ${Or}) (from=${$(o.from)})`),null;if(n+i>kr)return console.error(`[email-router] reply dropped: cumulative reply bytes ${n+i} exceed this delivery's budget of ${kr} (from=${$(o.from)})`),null;let s=dt(o.raw);if(!s.ok||s.addrSpec.toLowerCase()!==o.from.toLowerCase())return console.error(`[email-router] reply dropped: MIME From is not the envelope sender (from=${$(o.from)}, ${s.ok?"header names another address":s.reason})`),null;n+=i,r.push({type:"reply",from:o.from,to:o.to,raw:o.raw})}else return console.warn(`[email-router] dropping unknown action type: ${oe(o.type,320)}`),null}return r}l(co,"validateActions");async function Fr(e,t,r,n,o){let i=await co(r,o);if(i===null){await G(e,n.receiptId,n.projectId,"actions_rejected").catch(()=>{console.error("[email-router] could not record rejected actions")});return}await uo(e,t,i,n)}l(Fr,"enactActions");async function uo(e,t,r,n){if(!n.projectId||!n.receiptId){console.error("[email-router] action admission unavailable: missing project or receipt identity");return}let o=we();for(let[i,s]of r.entries()){if(s.type==="reject"){t.setReject(s.reason);return}if(o.expired()){console.error("[email-router] action batch deadline elapsed before admission");break}let a=s.to.toLowerCase(),c=s.type==="reply"?s.from:t.to,d=await ge(s.type,c,[a],s.type==="reply"?s.raw:new TextEncoder().encode(JSON.stringify([...s.headers?.entries()??[]].sort()))),u;try{u=await he(e,{projectId:n.projectId,kind:s.type,key:`${n.receiptId}:${i}:${d.slice(0,16)}`,digest:d,from:c,recipients:[a],transport:n.transport==="relay"?s.type==="reply"&&s.from.slice(s.from.indexOf("@")+1).toLowerCase()===re(e)?"binding":"send_raw":s.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"&&s.type==="reply")try{p=await io(e,n.projectId,s.from,s.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(o.expired()){let f=await Pr(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 Q(e,u.operationId,[a])}catch{let f=await Pr(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;s.type==="forward"?await o.run(()=>t.forward(a,s.headers)):p?f=await o.run(()=>p(a,o.remainingMs())):await o.run(()=>t.reply(new Dr(s.from,a,ne(s.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")}}}l(uo,"enactSanitized");async function Pr(e,t,r){try{return(await k(e,t,[r],"cancelled")).recipients.some(o=>o.recipient===r&&o.state==="cancelled")}catch{return!1}}l(Pr,"cancelUnstartedAction");var Fe=new TextEncoder,Rt=new TextDecoder,yt=128*1024,wt=320,fo=2,zr="/email/destinations/confirm",mo=4*1024,Hr=32*1024,Br=5e3,bt=0,L=class extends Error{constructor(r,n){super(r);this.status=n;this.name="MimeHeaderError"}status;static{l(this,"MimeHeaderError")}};function At(e){return e.PLATFORM_TRAFFIC_STATE==="staging"||e.PLATFORM_TRAFFIC_STATE==="sandbox-drain"}l(At,"isTrafficPaused");async function Gr(e){if(bt>=fo)throw new Error("email gateway busy");bt++;try{return await e()}finally{bt--}}l(Gr,"withDeliverySlot");async function Vr(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))),o="";for(let i of n)o+=String.fromCharCode(i);return btoa(o).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}l(Vr,"sign");async function qr(e,t){let r=Date.now()+5e3,n=new AbortController,o=l(async b=>{let R=r-Date.now();if(R<=0)throw n.abort(),new Error("ingress resolution timeout");let w;try{return await Promise.race([b(),new Promise((A,E)=>{w=setTimeout(()=>{n.abort(),E(new Error("ingress resolution timeout"))},R)})])}finally{w!==void 0&&clearTimeout(w)}},"beforeDeadline"),i=await Vr(`email-ingress-v1
|
|
3
|
+
${t.toLowerCase()}`,e.EMAIL_SIGNING_SECRET);l=await s(()=>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:o.signal}))}catch{return null}if(!l.ok)return l.body?.cancel().catch(()=>{}),null;let c=l.headers.get("content-length");if(c!==null&&(!/^\d+$/.test(c)||Number(c)>Ht))return l.body?.cancel().catch(()=>{}),null;let d=l.body?.getReader();if(!d)return null;let u=new Uint8Array(Ht),f=0;try{for(;;){let m=await s(()=>d.read());if(m.done)break;if(f+m.value.byteLength>u.byteLength)throw new Error("email credential lease response too large");u.set(m.value,f),f+=m.value.byteLength}if(c!==null&&f!==Number(c))return null;let p=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,f)));return yn(p)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}a(be,"leaseEmailDomainCredential");function yn(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}a(yn,"parseLease");g();var we=class extends Error{static{a(this,"EmailProviderTimeoutError")}constructor(){super("email provider outcome unknown after timeout"),this.name="EmailProviderTimeoutError"}};function Ee(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 o=Math.min(3e4,t-Date.now()-n);if(o<=0)throw new we;let i=r(),s;try{return await Promise.race([i,new Promise((l,c)=>{s=setTimeout(()=>c(new we),o)})])}finally{s!==void 0&&clearTimeout(s)}}}}a(Ee,"createEmailProviderDeadline");g();import{EmailMessage as Fn}from"cloudflare:email";g();g();g();g();g();var Re=Symbol();g();g();g();var Bt=a((e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData(),"bufferToFormData");var bn=1e4,Ae=a(e=>"headers"in e,"isRawRequest"),qt=a(async(e,t=Object.create(null))=>{let{all:r=!1,dot:n=!1}=t,o=(Ae(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();return o==="multipart/form-data"||o==="application/x-www-form-urlencoded"?wn(e,{all:r,dot:n}):{}},"parseBody");async function wn(e,t){if(!Ae(e)&&e.bodyCache.formData)return Gt(await e.bodyCache.formData,t);let r=Ae(e)?e.headers:e.raw.headers,n=await e.arrayBuffer(),o=Bt(n,r.get("Content-Type")||"");Ae(e)||(e.bodyCache.formData=o);let i=await o;return i?Gt(i,t):{}}a(wn,"parseFormData");function Gt(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,i)=>{t.all||i.endsWith("[]")?En(r,i,o):r[i]=o}),t.dot&&Object.entries(r).forEach(([o,i])=>{o.includes(".")&&(Rn(r,o,i,n),delete r[o])}),r}a(Gt,"convertFormDataToBodyData");var En=a((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"),Rn=a((e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let o=e,i=t.split(".",34);i.length>33&&zt(),i.forEach((s,l)=>{l===i.length-1?o[s]=r:((!o[s]||typeof o[s]!="object"||Array.isArray(o[s])||o[s]instanceof File)&&(n.count++>=bn&&zt(),o[s]=Object.create(null)),o=o[s])})},"handleParsingNestedValues"),zt=a(()=>{throw new Error("Nesting limit exceeded")},"throwNestingLimitExceeded");g();var Xe=a(e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},"splitPath"),ve=a(e=>{let{groups:t,path:r}=An(e),n=Xe(r);return _n(n,t)},"splitRoutingPath"),An=a(e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},"extractGroupsFromPath"),_n=a((e,t)=>{for(let r=t.length-1;r>=0;r--){let[n]=t[r];for(let o=e.length-1;o>=0;o--)if(e[o].includes(n)){e[o]=e[o].replace(n,t[r][1]);break}}return e},"replaceGroupMarks"),_e={},Ie=a((e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return _e[n]||(r[2]?_e[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:_e[n]=[e,r[1],!0]),_e[n]}return null},"getPattern"),Vt=a((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"),vn=a(e=>Vt(e,decodeURI),"tryDecodeURI"),Ye=a(e=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),n=r;for(;n<t.length;n++){let o=t.charCodeAt(n);if(o===37){let i=t.indexOf("?",n),s=t.indexOf("#",n),l=i===-1?s===-1?void 0:s:s===-1?i:Math.min(i,s),c=t.slice(r,l);return vn(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(o===63||o===35)break}return t.slice(r,n)},"getPath");var Wt=a(e=>{let t=Ye(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},"getPathNoStrict"),Xt=a((e,t,r)=>{e.at(-1)==="/"&&t.at(-1)!=="/"&&(e=e.slice(0,-1));let n=0;for(let o=t.indexOf("/");o!==-1&&o<r;o=t.indexOf("/",o+1))if(n=e.indexOf("/",n+1),n===-1)return"/";return e.slice(n)||"/"},"stripPathPrefix"),D=a((e,t,...r)=>(r.length&&(t=D(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),"mergePath"),Se=a(e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(o=>{if(o!==""&&!/\:/.test(o))n+="/"+o;else if(/\:/.test(o))if(o.charCodeAt(o.length-1)===63){r.length===0&&n===""?r.push("/"):r.push(n);let i=o.slice(0,-1);n+="/"+i,r.push(n)}else n+="/"+o}),r.filter((o,i,s)=>s.indexOf(o)===i)},"checkOptionalParameter"),Me=a(e=>e.indexOf("%")!==-1?Vt(e,In):e,"tryDecodeURIComponent"),We=a(e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Me(e)),"_decodeURI"),Yt=a((e,t,r)=>{let n=e.indexOf("#",8);n!==-1&&(e=e.slice(0,n));let o;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let l=e.indexOf("?",8),c=l;if(c===-1)return;for(e.startsWith(t,c+1)||(c=e.indexOf(`&${t}`,c+1));c!==-1;){let d=e.charCodeAt(c+t.length+1);if(d===61||d===38||isNaN(d)){if(c>l&&/(?:^|&)[^=&]*[%+]/.test(e.slice(l+1,c)))break;if(d===61){let u=c+t.length+2,f=e.indexOf("&",u);return We(e.slice(u,f===-1?void 0:f))}return""}c=e.indexOf(`&${t}`,c+1)}if(o=/[%+]/.test(e),!o)return}let i=Object.create(null);o??=/[%+]/.test(e);let s=e.indexOf("?",8);for(;s!==-1;){let l=e.indexOf("&",s+1),c=e.indexOf("=",s);c>l&&l!==-1&&(c=-1);let d=e.slice(s+1,c===-1?l===-1?void 0:l:c);if(o&&(d=We(d)),s=l,d==="")continue;let u;c===-1?u="":(u=e.slice(c+1,l===-1?void 0:l),o&&(u=We(u))),r?(i[d]&&Array.isArray(i[d])||(i[d]=[]),i[d].push(u)):i[d]??=u}return t?i[t]:i},"_getQueryParam"),Jt=Yt,Kt=a((e,t)=>Yt(e,t,!0),"getQueryParams"),In=decodeURIComponent;var Qt=class{static{a(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.#s()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#o(t);return r&&Me(r)}#s(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let n=this.#o(this.#e[0][this.routeIndex][1][r]);n!==void 0&&(e[r]=Me(n))}return e}#o(e){return this.#e[1]?this.#e[1][e]:e}query(e){return Jt(this.url,e)}queries(e){return Kt(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 qt(this,e)}#n=a(e=>{let{bodyCache:t,raw:r}=this,n=t[e];if(n)return n;for(let o in t)return t[o].then(i=>{o==="json"&&(i=JSON.stringify(i));let s=o==="formData"?void 0:r.headers.get("content-type");return new Response(i,{headers:s?{"Content-Type":s}:void 0})[e]()});return t[e]=r[e]()},"#cachedBody");json(){return this.#n("text").then(e=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then(e=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("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[Re](){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 Zt={Stringify:1,BeforeStream:2,Stream:3},Sn=a((e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},"raw");var Je=a(async(e,t,r,n,o)=>{typeof e=="object"&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let i=e.callbacks;if(!i?.length)return Promise.resolve(e);o?o[0]+=e:o=[e];let s=Promise.all(i.map(l=>l({phase:t,buffer:o,context:n}))).then(l=>Promise.all(l.filter(Boolean).map(c=>Je(c,t,!1,n,o))).then(()=>o[0]));return r?Sn(await s,i):s},"resolveCallback");var Mn="text/plain; charset=UTF-8",Ke=a((e,t)=>({"Content-Type":e,...t}),"setDefaultContentType"),ee=a((e,t)=>new Response(e,t),"createResponseInstance"),Qe=class{static{a(this,"Context")}#t;#e;env={};#r;finalized=!1;error;#s;#o;#n;#d;#l;#c;#a;#u;#f;constructor(e,t){this.#t=e,t&&(this.#o=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new Qt(this.#t,this.#f,this.#u),this.#e}get event(){if(this.#o&&"respondWith"in this.#o)return this.#o;throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#o)return this.#o;throw Error("This context has no ExecutionContext")}get res(){return this.#n||=ee(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=ee(e.body,e);for(let[t,r]of this.#n.headers.entries())if(t!=="content-type")if(t==="set-cookie"){let n=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let o of n)e.headers.append("set-cookie",o)}else e.headers.set(t,r)}this.#n=e,this.finalized=!0}render=a((...e)=>(this.#l??=t=>this.html(t),this.#l(...e)),"render");setLayout=a(e=>this.#d=e,"setLayout");getLayout=a(()=>this.#d,"getLayout");setRenderer=a(e=>{this.#l=e},"setRenderer");header=a((e,t,r)=>{this.finalized&&!this.#n.bodyUsed&&(this.#n=ee(this.#n.body,this.#n));let n=this.#n?this.#n.headers:this.#a??=new Headers;t===void 0?n.delete(e):r?.append?n.append(e,t):n.set(e,t)},"header");status=a(e=>{this.#s=e},"status");set=a((e,t)=>{this.#r??=new Map,this.#r.set(e,t)},"set");get=a(e=>this.#r?this.#r.get(e):void 0,"get");get var(){return this.#r?Object.fromEntries(this.#r):{}}#i(e,t,r){let n=this.#n?new Headers(this.#n.headers):this.#a;if(typeof t=="object"&&t.headers){n??=new Headers;for(let[i,s]of new Headers(t.headers))i==="set-cookie"?n.append(i,s):n.set(i,s)}if(r){if(!n){let i=0;for(let s in r)if(++i>1||typeof r[s]!="string"){n=new Headers;break}}if(n)for(let i in r){let s=r[i];if(typeof s=="string")n.set(i,s);else{n.delete(i);for(let l of s)n.append(i,l)}}}let o=typeof t=="number"?t:t?.status??this.#s;return ee(e,{status:o,headers:n??r})}newResponse=a((...e)=>this.#i(...e),"newResponse");body=a((e,t,r)=>this.#i(e,t,r),"body");text=a((e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,Ke(Mn,r)),"text");json=a((e,t,r)=>this.#i(JSON.stringify(e),t,Ke("application/json",r)),"json");html=a((e,t,r)=>{let n=a(o=>this.#i(o,t,Ke("text/html; charset=UTF-8",r)),"res");return typeof e=="object"?Je(e,Zt.Stringify,!1,{}).then(n):n(e)},"html");redirect=a((e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)},"redirect");notFound=a(()=>(this.#c??=()=>ee(),this.#c(this)),"notFound")};g();g();g();var Ze=a((e,t,r)=>(n,o)=>{let i=-1;return s(0);async function s(l){if(l<=i)throw new Error("next() called multiple times");i=l;let c,d=!1,u;if(e[l]?(u=e[l][0][0],n.req.routeIndex=l):u=l===e.length&&o||void 0,u)try{c=await u(n,()=>s(l+1))}catch(f){if(f instanceof Error&&t)n.error=f,c=await t(f,n),d=!0;else throw f}else n.finalized===!1&&r&&(c=await r(n));return c&&(n.finalized===!1||d)&&(n.res=c),n}},"compose");g();var er=["get","post","put","delete","options","patch","query"],Ne="Can not add a route since the matcher is already built.",Te=class extends Error{static{a(this,"UnsupportedPathError")}};g();var tr="__COMPOSED_HANDLER";g();var Nn=a((e,t,r)=>{if(!/[:*]/.test(t))return t.length;let n=e.req.path,o=e.req[Re],i=new Set,s=0;for(let l of ve(t)){let c=Ie(l);if(c&&c!=="*"){let d=c[1];if(i.has(d))throw new Error(`mount(): Duplicate path parameter "${d}" in "${r}".`);i.add(d)}if(c&&c!=="*"&&c[2]!==!0){let d=o.length===2?o[1][o[0][e.req.routeIndex][1][c[1]]]:o[0][e.req.routeIndex][1][c[1]];s+=d.length+1}else if(c||l.endsWith("*")){let d=n.indexOf("/",s+1);s=d===-1?n.length:d}else s+=l.length+1}return s},"getPathPrefixLength"),rr=a((e,t,r)=>{if(/[^/]\*$/.test(r))throw new Error(`mount(): Wildcard must follow "/" in "${r}".`);let n=new URL(e.req.raw.url);return n.pathname=Xt(n.pathname,e.req.path,Nn(e,t,r)),new Request(n,e.req.raw)},"createMountedRequest");var Tn=a(e=>e.text("404 Not Found",404),"notFoundHandler"),nr=a((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 sr{static{a(this,"Hono")}get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...er,"all"].forEach(o=>{this[o]=(i,...s)=>{let l=o.toUpperCase();return typeof i=="string"?this.#t=i:this.#s(l,this.#t,i),s.forEach(c=>{this.#s(l,this.#t,c)}),this}}),this.on=(o,i,...s)=>{for(let l of[i].flat()){this.#t=l;for(let c of[o].flat()){let d=c.toUpperCase();for(let u of s)this.#s(d,this.#t,u)}}return this},this.use=(o,...i)=>(typeof o=="string"?this.#t=o:(this.#t="*",i.unshift(o)),i.forEach(s=>{this.#s("ALL",this.#t,s)}),this);let{strict:r,...n}=t;Object.assign(this,n),this.getPath=r??!0?t.getPath??Ye:Wt}#e(){let t=new sr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Tn;errorHandler=nr;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let i;r.errorHandler===nr?i=o.handler:(i=a(async(s,l)=>(await Ze([],r.errorHandler)(s,()=>o.handler(s,l))).res,"handler"),i[tr]=o.handler),n.#s(o.method,o.path,i,o.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=D(this._basePath,t),r}onError=a(t=>(this.errorHandler=t,this),"onError");notFound=a(t=>(this.#r=t,this),"notFound");mount(t,r,n){let o,i;n&&(typeof n=="function"?i=n:(i=n.optionHandler,n.replaceRequest===!1?o=a(u=>u,"replaceRequest"):o=n.replaceRequest));let s=i?u=>{let f=i(u);return Array.isArray(f)?f:[f]}:u=>{let f;try{f=u.executionCtx}catch{}return[u.env,f]},l=D(this._basePath,t),c=a(u=>rr(u,l.replace(/\/$/,""),D(l,"*")),"defaultReplaceRequest"),d=a(async(u,f)=>{let p=await r(o?o(u.req.raw):c(u),...s(u));if(p)return p;await f()},"handler");return this.#s("ALL",D(t,"*"),d),this}#s(t,r,n,o){r=D(this._basePath,r);let i={basePath:o!==void 0?D(this._basePath,o):this._basePath,path:r,method:t,handler:n};this.router.add(t,r,[n,i]),this.routes.push(i)}#o(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,n,o){if(o==="HEAD")return(async()=>new Response(null,await this.#n(t,r,n,"GET")))();let i=this.getPath(t,{env:n}),s=this.router.match(o,i),l=new Qe(t,{path:i,matchResult:s,env:n,executionCtx:r,notFoundHandler:this.#r});if(s[0].length===1){let d;try{d=s[0][0][0][0](l,async()=>{l.res=await this.#r(l)})}catch(u){return this.#o(u,l)}return d instanceof Promise?d.then(u=>u||(l.finalized?l.res:this.#r(l))).catch(u=>this.#o(u,l)):d??this.#r(l)}let c=Ze(s[0],this.errorHandler,this.#r);return(async()=>{try{let d=await c(l);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.#o(d,l)}})()}fetch=a((t,...r)=>this.#n(t,r[1],r[0],t.method),"fetch");request=a((t,r,n,o)=>t instanceof Request?this.fetch(r?new Request(t,r):t,n,o):(t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${D("/",t)}`,r),n,o)),"request");fire=a(()=>{addEventListener("fetch",t=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})},"fire")};g();g();var x=a(()=>Object.create(null),"createNullObject");g();var et=[];function ir(e,t){let r=this.buildAllMatchers(),n=a(((o,i)=>{let s=r[o]||r.ALL,l=s[2][i];if(l)return l;let c=i.match(s[0]);if(!c)return[[],et];let d=c.indexOf("",1);return[s[1][d],c]}),"match");return this.match=n,n(e,t)}a(ir,"match");g();var xn="[^/]+",On="[^]*",kn="(?:|/[^]*)",j=Symbol(),ar=new Set(".\\+*[^]$()");function Pn(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}a(Pn,"compareKey");var lr=class tt{static{a(this,"Node")}#t;#e;#r=x();insert(t,r,n,o,i){let s=this;for(let l=0,c=t.length;l<c;l++){let d=t[l],u=d.length===1?d==="*"?l===c-1?["","",On]:["","",xn]:null:d==="/*"?["","",kn]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),f;if(u){let p=u[1],m=u[2]||"[^/]+";if(p&&u[2]&&(new RegExp(m).test("")||(m=m.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(m))||m.length===1&&ar.has(m)))throw j;if(i.push(m),f=s.#r[m],!f){if(m!=="[^]*"&&m!=="(?:|/[^]*)"){for(let h in s.#r)if((m.length>1||h.length>1)&&h!=="[^]*"&&h!=="(?:|/[^]*)")throw j}f=s.#r[m]=new tt}p!==""&&(f.#e??=o.varIndex++,n.push([p,f.#e]))}else if(i.push(d),f=s.#r[d],!f){for(let p in s.#r)if(p.length>1&&p!=="[^]*"&&p!=="(?:|/[^]*)")throw j;f=s.#r[d]=new tt}s=f}if(s.#t!==void 0)throw j;s.#t=r}buildRegExpStr(){let t=Object.keys(this.#r).sort(Pn).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:ar.has(r)?`\\${r}`:r)+o}).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 rt=class{static{a(this,"Trie")}#t={varIndex:0};#e=new lr;#r=0;paths=x();insert(e,t){let r=[];if(t){this.#e.insert(e.split(""),-1,[],this.#t,r),this.paths[e]=[-1,[],r];return}let n=[],o=[],i=e;for(let l=0;;){let c=!1;if(i=i.replace(/\{(?:\{[\d,]+\}|[^}])+\}/g,d=>{let u=`@\\${l}`;return o[l]=[u,d],l++,c=!0,u}),!c)break}let s=i.match(/(?::[^\/]+)|(?:\/\*$)|./gs)||[];for(let l=o.length-1;l>=0;l--){let[c]=o[l];for(let d=s.length-1;d>=0;d--)if(s[d].indexOf(c)!==-1){s[d]=s[d].replace(c,o[l][1]);break}}this.#e.insert(s,this.#r,n,this.#t,r),this.paths[e]=[this.#r++,n,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],n=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(o,i,s)=>i!==void 0?(r[++t]=Number(i),"$()"):(s!==void 0&&(n[Number(s)]=++t),"")),[new RegExp(`^${e}`),r,n]}};function Dn(e){let t=e[e.length-1];return t==="[^]*"||t==="(?:|/[^]*)"}a(Dn,"endsWithWildcard");function Ln(e,t){let r=e.length-1;for(let n=0;n<r;n++)if(e[n]!==t[n])return!1;return e[r]==="[^]*"||t.length===r||t[r]==="/"}a(Ln,"covers");var cr=class{static{a(this,"RegExpRouter")}name="RegExpRouter";#t;#e;constructor(){this.#t={ALL:[]},this.#e={ALL:new rt}}#r(e,t){try{this.#e[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===j?new Te(t):r}}add(e,t,r){let n=this.#t;if(!n)throw new Error(Ne);let o=this.#e;if(!n[e]){o[e]=new rt,n[e]=[...n.ALL];for(let l in o.ALL.paths)this.#r(e,l)}t==="/*"&&(t="*");let i=e==="ALL"?Object.keys(n):[e],s=Se(t)||[t];for(let l of s)for(let c of i)o[c].paths[l]||this.#r(c,l),n[c].push([r,l])}match=ir;buildAllMatchers(){let e=x();for(let t of Object.keys(this.#t))e[t]=this.#s(t);return this.#t=this.#e=void 0,e}#s(e){let t=this.#t[e],r=this.#e[e],n=x(),o=[],[i,s,l]=r.buildRegExp(),c=x(),d=t.map(([f,p],m)=>((c[p]??=[]).push(m),[f,r.paths[p][1].reduceRight((h,[y,b])=>(h[y]=l[b],h),x())])),u=Object.keys(c).filter(f=>Dn(r.paths[f][2]));for(let f in r.paths){let[p,,m]=r.paths[f],h=[...c[f]];for(let b of u)b!==f&&Ln(r.paths[b][2],m)&&h.push(...c[b]);let y=h.sort((b,R)=>b-R).map(b=>d[b]);if(p===-1){let b=Math.max(-1,...y.flatMap(([,R])=>Object.values(R)));n[f]=[y,b===-1?et:f.match(i).slice(0,b+1)]}else o[p]=y}return[i,s.map(f=>o[f]),n]}};g();var dr=class{static{a(this,"SmartRouter")}name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(Ne);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw new Error("Fatal error");let r=this.#t,n=this.#e,o=r.length,i=0,s;for(;i<o;i++){let l=r[i];try{for(let c=0,d=n.length;c<d;c++)l.add(...n[c]);s=l.match(e,t)}catch(c){if(c instanceof Te)continue;throw c}this.match=l.match.bind(l),this.#t=[l],this.#e=void 0;break}if(i===o)throw new Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}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 nt=x(),Cn=0,ur=class fr{static{a(this,"Node")}#t=[];#e=x();#r=[];#s;#o=nt;insert(t,r,n){let o=this,i=ve(r),s=new Set,l=0;for(let c of i){let d=i[++l],u=Ie(c,d)||(d===void 0&&c&&c.indexOf("*")===c.length-1?c:null),f=Array.isArray(u),p=f?u[0]:u||c,m=o.#e[p]||=new fr;u&&!m.#s&&(m.#s=u,o.#r.push(m)),o=m,f&&s.add(u[1])}o.#t.push({[t]:{handler:n,possibleKeys:[...s],score:++Cn}})}#n(t,r,n,o,i){for(let s=0,l=r.#t.length;s<l;s++){let c=r.#t[s],d=c[n]||c.ALL;if(d){d.params=x(),t.push(d);for(let u=0,f=d.possibleKeys.length;u<f;u++){let p=d.possibleKeys[u];d.params[p]=i?.[p]&&!u?i[p]:o[p]??i?.[p]}}}}search(t,r){let n=[];this.#o=nt;let o=[this],i=Xe(r),s=[],l=i.length,c=null;for(let d=0;d<l;d++){let u=i[d],f=d===l-1,p=[];for(let h=0,y=o.length;h<y;h++){let b=o[h],R=b.#e[u];R&&(R.#o=b.#o,f?(R.#e["*"]&&this.#n(n,R.#e["*"],t,b.#o),this.#n(n,R,t,b.#o)):p.push(R));for(let E of b.#r){let A=E.#s,w=b.#o===nt?{}:{...b.#o};if(typeof A=="string"){(A==="*"||u.startsWith(A.slice(0,-1)))&&(this.#n(n,E,t,b.#o),A==="*"&&(E.#o=w,p.push(E)));continue}let[,_,S]=A;if(!(!u&&S===!0)){if(S!==!0){if(!c){c=[];let T=r[0]==="/"?1:0;for(let P=0;P<l;P++)c[P]=T,T+=i[P].length+1}let O=r.slice(c[d]),N=S.exec(O);if(N){Object.hasOwn(w,_)||(w[_]=N[0]),this.#n(n,E,t,b.#o,w),N[0].length===O.length&&E.#e["*"]&&this.#n(n,E.#e["*"],t,b.#o,w);for(let T in E.#e){E.#o=w;let P=N[0].match(/\//g)?.length??0;(s[P]||=[]).push(E);break}continue}}(S===!0||S.test(u))&&(Object.hasOwn(w,_)||(w[_]=u),f?(this.#n(n,E,t,w,b.#o),E.#e["*"]&&this.#n(n,E.#e["*"],t,w,b.#o)):(E.#o=w,p.push(E)))}}}let m=s.shift();o=m?p.concat(m):p}return n[1]&&n.sort((d,u)=>d.score-u.score),[n.map(({handler:d,params:u})=>[d,u])]}};var ot=class{static{a(this,"TrieRouter")}name="TrieRouter";#t=new ur;add(e,t,r){for(let n of Se(t)||[t])this.#t.insert(e,n,r)}match(e,t){return this.#t.search(e,t)}};g();var st=class extends or{static{a(this,"Hono")}constructor(e={}){super(e),this.router=e.router??new dr({routers:[new cr,new ot]})}};g();g();g();g();g();g();g();g();g();g();g();function te(e){return typeof e=="string"?e:null}a(te,"asString");var Hn=new st,Bn=5e4,z=5e3,xe=5*1024*1024,Gn=16*1024,zn=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 qn(e){let t=0,r=!1;for(let n=0;n<e.byteLength;){let o=n;for(;o<e.byteLength&&e[o]!==10;)o++;let i=o>n&&e[o-1]===13?o-1:o;if(i===n)return!0;if(e[n]!==32&&e[n]!==9){let s=n;for(;s<i&&e[s]!==58;)s++;let l=new TextDecoder().decode(e.subarray(n,s)).toLowerCase();r=s<i&&!zn.has(l)}if(r&&(t+=i-n+2,t>Gn))return!1;n=o+1}return!0}a(qn,"customMimeHeaderBytesWithinLimit");var pr=50,gr=320,hr=320;function re(e){let t=e.EMAIL_SENDER_DOMAIN;if(typeof t!="string")return null;let r=t.trim().toLowerCase();return r.length>0?r:null}a(re,"readSenderDomain");var Vn=/[.*+?^${}()|[\]\\]/g;function Wn(e){return e.replace(Vn,"\\$&")}a(Wn,"escapeRegExp");var yr=new Map;function Xn(e){let t=yr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${Wn(e)}$`);return yr.set(e,r),r}a(Xn,"strictFromRe");var Yn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function v(e,t=200){return e.slice(0,t).replace(Yn," ")}a(v,"sanitizeForLog");var Jn=128;function ne(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}a(ne,"bytesToStream");var br=10,Oe=13,Er=32,Rr=9,Kn=58,ke=[102,114,111,109];function Qn(e,t,r){if(r-t<=ke.length)return-1;for(let o=0;o<ke.length;o++)if((e[t+o]|32)!==ke[o])return-1;let n=t+ke.length;for(;n<r&&(e[n]===Er||e[n]===Rr);)n++;return n<r&&e[n]===Kn?n+1:-1}a(Qn,"fromValueStart");var Zn={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 lt(e){let t=e.byteLength,r=0,n=-1,o=-1,i=!1,s=!1,l=e.indexOf(Oe),c=0;for(;c<t;){let f=e.indexOf(br,c),m=f===-1?t:f;if(m>c&&e[m-1]===Oe&&m--,m===c)break;if(l!==-1&&l<c&&(l=e.indexOf(Oe,c)),l!==-1&&l<m)return{ok:!1,reason:"malformed"};if(e[c]===Er||e[c]===Rr)s&&(o=m,i=!0);else{let h=Qn(e,c,m);s=h!==-1,s&&(r++,n=h,o=m,i=!1)}c=f===-1?t:f+1}if(r===0)return{ok:!1,reason:"missing"};if(r>1)return{ok:!1,reason:"multiple"};let d=e.subarray(n,o);if(i){d=e.slice(n,o);let f=0;for(let p=0;p<d.length;p++){let m=d[p];m!==Oe&&m!==br&&(d[f++]=m)}d=d.subarray(0,f)}let u=eo(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}a(lt,"readMimeFromAddrSpec");function eo(e){let t=!1,r=!1,n=-1,o=-1,i=-1;for(let l=0;l<e.length;l++){let c=e[l];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=l;break;case">":if(n===-1||o!==-1)return null;o=l;break;case"@":i===-1&&(i=l);break;case",":case";":case":":case"(":case")":case"[":case"]":case"\\":return null;default:break}}if(t)return null;let s;if(n===-1)s=e.trim();else{if(o===-1||e.slice(o+1).trim().length!==0||i!==-1&&i<n)return null;s=e.slice(n+1,o)}return/^[\x21-\x7e]+$/.test(s)?s:null}a(eo,"singleMailboxAddrSpec");Hn.post("/send",async e=>{let t=Ee(Bn),r=e.get("projectId"),n=e.get("body"),o=te(n.from),i=te(n.mimeBase64),s=te(n.requestId),l=s===null?"unknown":v(s,Jn),c=te(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??(s&&s.length<=128&&/^[\x20-\x7e]+$/.test(s)?s:crypto.randomUUID()),u=Array.isArray(n.recipients)?n.recipients:null;if(!o||!i||!u)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"invalid body"}},400);if(u.length>pr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`too many recipients (max ${pr}, got ${u.length})`}},413);if(o.length>hr)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${hr} characters`}},413);let f=re(e.env);if(!f)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sender domain is not configured"}},502);let p=[],m=new Set;for(let I of u){if(typeof I!="string")continue;if(I.length>gr)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${gr} characters`}},413);let M=I.trim().toLowerCase();!M||m.has(M)||(m.add(M),p.push(M))}if(p.length===0)return e.json({ok:!1,error:{code:"INVALID_TO",message:"no recipients"}},200);if(i.length>Math.ceil(xe*4/3)+4)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${xe} bytes (base64 length ${i.length})`}},413);let h;try{h=ro(i)}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(!qn(h))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let y=o.indexOf("@"),b=y===-1?"":o.slice(y+1).toLowerCase();if(b!==""&&b!==f)return to(e,r,o,b,f,p,h,l,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=o.split("@")[0]?.split("+")[0]??"";if(!/^[\x21-\x7e]+$/.test(o))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let A=o.toLowerCase();if(!Xn(f).test(A))return e.json({ok:!1,error:{code:"INVALID_FROM",message:`from address must be <${E}>[+tag]@${f}`}},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]@${f}`}},200);let S=_r(e,h,o);if(S)return S;let O=await vr(e,t,{projectId:r,operationKey:d,from:o,recipients:p,raw:h,transport:"binding"});if(O instanceof Response)return O;let{admission:N,deliveries:T}=O,P=N.recipients.filter(I=>I.state==="reserved").map(I=>I.recipient);for(let I=0;I<P.length;I++){let M=P[I];if(t.expired(z)){let F=P.slice(I),W=await it(e.env,N.operationId,F,t.remainingMs());for(let ie of F)T.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 Q(e.env,N.operationId,[M],t.remainingMs(z))}catch{let F=await it(e.env,N.operationId,[M],t.remainingMs());T.push({recipient:M,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 Fn(o,M,ne(h)),W=await t.run(()=>R.send(F),z),ie=typeof W?.messageId=="string"?W.messageId:"";try{await k(e.env,N.operationId,[M],"provider_accepted",{providerReference:ie},t.remainingMs())}catch{T.push({recipient:M,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider accepted email but outcome could not be recorded"}});continue}T.push({recipient:M,ok:!0,state:"provider_accepted",messageId:ie})}catch{try{await k(e.env,N.operationId,[M],"outcome_unknown",{errorCode:"OUTCOME_UNKNOWN"},t.remainingMs())}catch{}T.push({recipient:M,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"}})}}return Ir(r,l,T),T.some(I=>!I.ok)?e.json({ok:!1,operationId:N.operationId,deliveries:T},200):e.json({ok:!0,operationId:N.operationId,ids:T.map(I=>({recipient:I.recipient,messageId:I.messageId,state:"provider_accepted"}))})});var wr=64*1024;async function ct(e,t=3e4){let r=new AbortController,n=Date.now()+Math.min(3e4,t),o=JSON.stringify({from:e.from,recipients:e.recipients,mime_message:e.mimeMessage}),i=a(async f=>{let p=n-Date.now();if(p<=0)throw r.abort(),new Error("email sending request timed out");let m=f(),h;try{return await Promise.race([m,new Promise((y,b)=>{h=setTimeout(()=>{r.abort(),b(new Error("email sending request timed out"))},p)})])}finally{h!==void 0&&clearTimeout(h)}},"beforeDeadline"),s=await i(()=>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:o,signal:r.signal}));if(!s.ok)return s.body?.cancel().catch(()=>{}),{ok:!1,status:s.status};let l=s.headers.get("content-length");if(l!==null&&(!/^\d+$/.test(l)||Number(l)>wr))throw s.body?.cancel().catch(()=>{}),new Error("email sending API response too large");let c=s.body?.getReader();if(!c)throw new Error("email sending API response unreadable");let d=new Uint8Array(wr),u=0;try{for(;;){let f=await i(()=>c.read());if(f.done)break;if(u+f.value.byteLength>d.byteLength)throw new Error("email sending API response too large");d.set(f.value,u),u+=f.value.byteLength}if(l!==null&&u!==Number(l))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{}}}a(ct,"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}a(Pe,"readSendRawAddressList");function dt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=Pe(t.delivered),n=Pe(t.permanent_bounces),o=Pe(t.queued),i=Pe(t.suppressed_recipients);return!r||!n||!o||!i||typeof t.message_id!="string"||t.message_id===""?null:{delivered:r,messageId:t.message_id,permanentBounces:n,queued:o,suppressedRecipients:i}}a(dt,"parseSendRawResult");function ut(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"}a(ut,"classifySendRawRecipient");async function to(e,t,r,n,o,i,s,l,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(e,s,r);if(u)return u;let f;try{f=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(s)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"mime must be valid UTF-8"}},400)}let p=await vr(e,d,{projectId:t,operationKey:c,from:r,recipients:i,raw:s,transport:"send_raw"});if(p instanceof Response)return p;let{admission:m,deliveries:h}=p;if(i=m.recipients.filter(w=>w.state==="reserved").map(w=>w.recipient),i.length===0)return at(e,m.operationId,h);let y=await be(e.env,n,t,d.remainingMs(z));if(!y)return await k(e.env,m.operationId,i,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:m.operationId,error:{code:"UPSTREAM_ERROR",message:"could not lease the domain credential"}},502);if(m.accountId!==y.accountId)return await k(e.env,m.operationId,i,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:m.operationId,error:{code:"UPSTREAM_ERROR",message:"email domain changed during admission"}},503);try{await Q(e.env,m.operationId,i,d.remainingMs(z))}catch{let w=await it(e.env,m.operationId,i,d.remainingMs());for(let _ of i)h.push({recipient:_,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 at(e,m.operationId,h)}let b=null,R="failed",E=null,A=null;try{A=await ct({accountId:y.accountId,bearer:ye(y),from:r,recipients:i,mimeMessage:f},d.remainingMs(z))}catch{b={code:"UPSTREAM_ERROR",message:"email sending request failed"},R="outcome_unknown"}if(A)if(!A.ok)b={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 w=A.data,_=typeof w=="object"&&w!==null?w.success:void 0;_===!1?b={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:_!==!0?(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"):(E=dt(w.result),E||(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"))}for(let w of i){if(b){h.push({recipient:w,ok:!1,state:R,error:b});continue}let _=ut(E,w);_==="permanent_bounce"?h.push({recipient:w,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${w}' permanently bounced`}}):_==="suppressed"?h.push({recipient:w,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${w}' is on the suppression list`}}):_==="outcome_unknown"?h.push({recipient:w,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):h.push({recipient:w,ok:!0,state:"provider_accepted",messageId:E.messageId})}for(let w of h.filter(_=>m.recipients.some(S=>S.recipient===_.recipient&&S.state==="reserved")))try{await k(e.env,m.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 Ir(t,l,h),h.some(w=>!w.ok)?e.json({ok:!1,operationId:m.operationId,deliveries:h},200):e.json({ok:!0,operationId:m.operationId,ids:h.map(w=>({recipient:w.recipient,messageId:w.messageId,state:"provider_accepted"}))})}a(to,"sendViaCustomDomain");async function Ar(e,t){console.log(`[email-recv] ${e} ${v(t.from,320)} -> ${v(t.to,320)} ${t.status} (${t.byteSize}B) @${Date.now()}`)}a(Ar,"recordInboundDelivery");function _r(e,t,r){let n=lt(t);if(n.ok&&n.addrSpec.toLowerCase()===r.toLowerCase())return null;let o=n.ok?"the From header address does not match the envelope sender":Zn[n.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${o}`}},403)}a(_r,"refuseMimeFromMismatch");async function vr(e,t,r){let{projectId:n,operationKey:o,from:i,recipients:s,raw:l,transport:c}=r,d;try{d=await he(e.env,{projectId:n,kind:"direct",key:o,digest:await ge("direct",i,s,l),from:i,recipients:s,transport:c},t.remainingMs(z))}catch(f){let p=f instanceof Error&&f.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(f=>f.state!=="reserved").map(f=>({recipient:f.recipient,ok:f.state==="provider_accepted",state:f.state,messageId:f.providerReference??void 0,error:f.state==="provider_accepted"?void 0:{code:f.errorCode??(f.state==="outcome_unknown"||f.state==="attempt_started"?"OUTCOME_UNKNOWN":f.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:f.state==="outcome_unknown"||f.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":f.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(d.replay){for(let f of d.recipients.filter(p=>p.state==="reserved"))u.push({recipient:f.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return at(e,d.operationId,u)}return{admission:d,deliveries:u}}a(vr,"admitDirectSend");async function it(e,t,r,n){try{let o=await k(e,t,r,"cancelled",{},n);return r.every(i=>o.recipients.some(s=>s.recipient===i&&s.state==="cancelled"))}catch{return!1}}a(it,"cancelUnstartedRecipients");function at(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)}a(at,"emailActionResponse");function Ir(e,t,r){for(let n of r){let o=n.ok?"sent":n.error?.code??"unknown_error",i=n.messageId??"";console.log(`[email-log] ${e} ${t} ${v(n.recipient,320)} ${o} ${i} @${Date.now()}`)}}a(Ir,"logSend");function ro(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}a(ro,"base64Decode");function oe(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}]`}}a(oe,"describeUntrusted");function Pr(e){let t=[e.slug,e.alias,e.mailbox].filter(r=>typeof r=="string").map(r=>r.toLowerCase());return[...new Set(t)]}a(Pr,"mailboxNames");function no(e){return{routeId:e.routeId,routeGeneration:e.routeGeneration,connectionId:e.connectionId,addressing:e.addressing,domain:e.domain,projectSlug:e.slug}}a(no,"receiptRouteFence");var L=10*1024*1024,se=1024,pt=128*1024,oo=1e3,Sr=100,Dr=320,Mr=32,Le=1024,Nr=5*1024*1024,Tr=8*1024*1024,so=15e3,Ce=class extends Error{constructor(r){super(`inbound message exceeds ${L} bytes (got ${r})`);this.size=r;this.name="InboundTooLargeError"}size;static{a(this,"InboundTooLargeError")}},je=class extends Error{static{a(this,"InboundTooManyHeadersError")}constructor(){super(`inbound message carries more than ${se} headers`),this.name="InboundTooManyHeadersError"}},$e=class extends Error{static{a(this,"InboundHeadersTooLargeError")}constructor(){super(`inbound headers exceed ${pt} bytes`),this.name="InboundHeadersTooLargeError"}};function ft(e){return typeof e=="string"&&e.length<=Dr&&(0,kr.validate)(e)}a(ft,"isValidEmailAddress");function $(e){return oe(e,Dr)}a($,"logAddress");function io(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>Mr)return console.error(`[email-router] action list dropped: forward has ${r.length} headers (max ${Mr})`),!1;for(let n of r){let o=e[n];if(n.length>Le)return console.error(`[email-router] action list dropped: forward header name exceeds ${Le} characters`),!1;if(typeof o!="string")return console.error(`[email-router] action list dropped: forward header "${v(n,64)}" value is not a string`),!1;if(o.length>Le)return console.error(`[email-router] action list dropped: forward header "${v(n,64)}" value exceeds ${Le} characters`),!1}return!0}a(io,"forwardHeadersWithinBounds");function ao(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:t.names.includes(r.slice(0,n).split("+")[0])}a(ao,"isPermittedReplySender");async function Lr(e,t,r,n){let o=re(t)??"void email",i=String(e.to??"").toLowerCase(),s=i.split("@")[0]??"",l=s.indexOf("+"),c=l===-1?s:s.slice(0,l),d=(n.mailbox??n.slug).toLowerCase(),u=i.indexOf("@"),f=u===-1?"":i.slice(u+1);if(!c){e.setReject(`${o}: missing project slug in recipient`);return}if(n.addressing!=="custom"&&Ot(c)){e.setReject(`${o}: "${v(c,64)}" is a reserved platform address`);return}if(!n.projectId||!n.workerName||!n.deploymentId||n.domain?.toLowerCase()!==f||n.addressing==="shared"&&d!==c){e.setReject(`${o}: authoritative route mismatch`);return}let p=n.workerName,m=n.projectId,h;try{h=n.limits?t.DISPATCH.get(p,{},{limits:n.limits}):t.DISPATCH.get(p)}catch(A){throw console.error(`[email-router] DISPATCH.get(${v(p,320)}) failed:`,A),new Error("email worker temporarily unavailable")}if(typeof e.rawSize=="number"&&e.rawSize>L){e.setReject(`${o}: message too large (max ${L} bytes)`);return}let y;try{y=await uo(e),n.addressing==="custom"&&(y.viaDomain=f)}catch(A){if(A instanceof Ce){e.setReject(`${o}: message too large (max ${L} bytes)`);return}if(A instanceof je){e.setReject(`${o}: too many headers (max ${se})`);return}if(A instanceof $e){e.setReject(`${o}: headers too large (max ${pt} bytes)`);return}console.error(`[email-router] failed to read message body for ${v(c,64)}:`,A),e.setReject(`${o}: could not read inbound message body`);return}let b=crypto.randomUUID(),R={projectId:m,receiptId:b,transport:"native"},E;try{await G(t,b,m,"received",no(n))}catch{throw new Error("email admission temporarily unavailable")}try{E=(await Ve(h,t,{projectId:m,deploymentId:n.deploymentId,envelope:y,receiptId:b})).actions}catch(A){await G(t,b,m,"handler_failed").catch(()=>{});let w=A instanceof Error?A.message.slice(0,320):oe(A,320);throw console.error(`[email-router] dispatch to ${v(p,320)} failed:`,w),new Error("email handler execution unresolved")}try{await G(t,b,m,"handler_completed")}catch{console.error("[email-router] handler completed but receipt status could not be saved");return}try{await jr(t,e,E,R,{customDomain:n.addressing==="custom",names:Pr(n),domain:f})}catch{console.error("[email-router] action execution unresolved",b);return}r.waitUntil(mt(t,m,e,E))}a(Lr,"routeInbound");async function Cr(e,t,r){let{stub:n,projectId:o,domain:i,envelope:s,authoritative:l,receiptId:c}=r;if(l.projectId!==o||!l.workerName||!l.slug||l.domain?.toLowerCase()!==i)return{reject:!0};let d=l.slug,u=l.workerName,f=lo(s),p={projectId:o,receiptId:c,transport:"relay"},m;try{m=(await Ve(n,e,{projectId:o,deploymentId:l.deploymentId,envelope:s,receiptId:c})).actions}catch(h){await G(e,c,o,"handler_failed").catch(()=>{});let y=h instanceof Error?h.message.slice(0,320):oe(h,320);return console.error(`[email-relay] dispatch to ${v(u,320)} failed:`,y),t.waitUntil(mt(e,o,f.message,[{type:"reject",reason:"dispatch-error"}])),{reject:!0,temporary:!0}}try{await G(e,c,o,"handler_completed")}catch{return console.error("[email-relay] handler completed but receipt status could not be saved"),{reject:!1}}try{await jr(e,f.message,m,p,{customDomain:l.addressing==="custom",names:Pr(l),domain:i})}catch{return console.error("[email-relay] action execution unresolved",c),{reject:!1}}return t.waitUntil(mt(e,o,f.message,m)),{reject:f.rejectedReason()!==null}}a(Cr,"routeRelayed");function lo(e){let t=null;return{message:{from:e.from,to:e.to,rawSize:e.rawSize,headers:new Headers(e.headers),raw:ne(e.raw),setReject(n){t=n},async forward(n,o){throw new U("relayed forward requires a native email event")}},rejectedReason:a(()=>t,"rejectedReason")}}a(lo,"createRelayedMessage");async function co(e,t,r,n,o){let i=r.slice(r.indexOf("@")+1).toLowerCase();if(i===re(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 Or(r,d,ne(n))))?.messageId}let s=await be(e,i,t);if(!s||o&&s.accountId!==o)throw new Error("could not lease the domain credential");let l=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(n);return async(c,d=3e4)=>{let u;try{u=await ct({accountId:s.accountId,bearer:ye(s),from:r,recipients:[c],mimeMessage:l},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 f=u.data;if(typeof f!="object"||f===null||!("success"in f))throw new Error("email sending API response invalid");if(f.success===!1)throw new U("email sending API refused the message");if(f.success!==!0)throw new Error("email sending API response invalid");let p=dt(f.result);if(!p)throw new Error("email sending API response invalid");let m=ut(p,c);if(m==="permanent_bounce")throw new U("recipient permanently bounced");if(m==="suppressed")throw new U("recipient is on the suppression list");if(m==="outcome_unknown")throw new Error("email sending API did not classify the recipient");return p.messageId}}a(co,"prepareRelayedReply");async function mt(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 o=n.some(i=>i&&typeof i=="object"&&i.type==="reject")?"rejected":n.length===0?"accepted":"handled";try{await Ar(t,{from:String(r.from??""),to:String(r.to??""),byteSize:r.rawSize??0,status:o})}catch(i){console.error("[email-router] log-recv failed:",i)}}a(mt,"logRecv");async function uo(e){let t=[],r=0,n=new TextEncoder;for(let s of e.headers){if(t.length>=se)throw new je;if(r+=n.encode(s[0]).byteLength+n.encode(s[1]).byteLength,r>pt)throw new $e;t.push(s)}let o=await fo(e.raw),i=Object.fromEntries(t);return{from:String(e.from??""),to:String(e.to??""),headers:i,raw:o,rawSize:e.rawSize??o.byteLength}}a(uo,"buildEnvelope");async function fo(e){let t=e.getReader(),r=[],n=0,o=Date.now()+so;try{for(;;){let l=o-Date.now();if(l<=0)throw new Error("inbound message stream timed out");let c,{value:d,done:u}=await Promise.race([t.read(),new Promise((f,p)=>{c=setTimeout(()=>p(new Error("inbound message stream timed out")),l)})]).finally(()=>{c!==void 0&&clearTimeout(c)});if(u)break;if(n+=d.byteLength,n>L)throw new Ce(n);r.push(d)}}catch(l){throw t.cancel().catch(()=>{}),l}finally{try{t.releaseLock()}catch{}}let i=new Uint8Array(n),s=0;for(let l of r)i.set(l,s),s+=l.byteLength;return i}a(fo,"readStreamToBytes");var U=class extends Error{static{a(this,"DefinitiveEmailActionError")}};async function mo(e,t){if(e.length>Sr)return console.error(`[email-router] action list dropped: ${e.length} actions returned (max ${Sr})`),null;let r=[],n=0;for(let o of e){if(!o||typeof o!="object")return console.error(`[email-router] dropping non-object action: ${oe(o,320)}`),null;if(o.type==="reject"){let i=typeof o.reason=="string"?o.reason:"",s=i.length>0?v(i,oo):"rejected by handler";return r.push({type:"reject",reason:s}),r}if(o.type==="forward"){if(!ft(o.to))return console.error(`[email-router] forward dropped: invalid "to" address ${$(o.to)}`),null;let i;if(o.headers){if(!io(o.headers))return null;try{i=new Headers(o.headers)}catch(s){return console.error("[email-router] action list dropped: forward headers invalid:",s instanceof Error?v(s.message,320):v(String(s),320)),null}}r.push({type:"forward",to:o.to,headers:i})}else if(o.type==="reply"){if(!ft(o.from)||!ft(o.to))return console.error(`[email-router] reply dropped: invalid address (from=${$(o.from)} to=${$(o.to)})`),null;if(!ao(o.from,t))return console.error(`[email-router] reply dropped: sender not owned by project "${v(t.names[0]??"",64)}" (from=${$(o.from)})`),null;if(!(o.raw instanceof Uint8Array))return console.error(`[email-router] reply dropped: raw is not a Uint8Array (from=${$(o.from)})`),null;let i=o.raw.byteLength;if(i>Nr)return console.error(`[email-router] reply dropped: raw is ${i} bytes (max ${Nr}) (from=${$(o.from)})`),null;if(n+i>Tr)return console.error(`[email-router] reply dropped: cumulative reply bytes ${n+i} exceed this delivery's budget of ${Tr} (from=${$(o.from)})`),null;let s=lt(o.raw);if(!s.ok||s.addrSpec.toLowerCase()!==o.from.toLowerCase())return console.error(`[email-router] reply dropped: MIME From is not the envelope sender (from=${$(o.from)}, ${s.ok?"header names another address":s.reason})`),null;n+=i,r.push({type:"reply",from:o.from,to:o.to,raw:o.raw})}else return console.warn(`[email-router] dropping unknown action type: ${oe(o.type,320)}`),null}return r}a(mo,"validateActions");async function jr(e,t,r,n,o){let i=await mo(r,o);if(i===null){await G(e,n.receiptId,n.projectId,"actions_rejected").catch(()=>{console.error("[email-router] could not record rejected actions")});return}await po(e,t,i,n)}a(jr,"enactActions");async function po(e,t,r,n){if(!n.projectId||!n.receiptId){console.error("[email-router] action admission unavailable: missing project or receipt identity");return}let o=Ee();for(let[i,s]of r.entries()){if(s.type==="reject"){t.setReject(s.reason);return}if(o.expired()){console.error("[email-router] action batch deadline elapsed before admission");break}let l=s.to.toLowerCase(),c=s.type==="reply"?s.from:t.to,d=await ge(s.type,c,[l],s.type==="reply"?s.raw:new TextEncoder().encode(JSON.stringify([...s.headers?.entries()??[]].sort()))),u;try{u=await he(e,{projectId:n.projectId,kind:s.type,key:`${n.receiptId}:${i}:${d.slice(0,16)}`,digest:d,from:c,recipients:[l],transport:n.transport==="relay"?s.type==="reply"&&s.from.slice(s.from.indexOf("@")+1).toLowerCase()===re(e)?"binding":"send_raw":s.type==="forward"?"native_forward":"native_reply",receiptId:n.receiptId})}catch(m){console.error("[email-router] action admission unavailable:",m instanceof Error?m.message:"unknown");continue}let f=u.recipients.find(m=>m.recipient===l);if(u.replay||f?.state!=="reserved")continue;let p;if(n.transport==="relay"&&s.type==="reply")try{p=await co(e,n.projectId,s.from,s.raw,u.accountId)}catch{await k(e,u.operationId,[l],"cancelled").catch(()=>{console.error("[email-router] could not cancel unsubmitted relayed reply")}),console.error("[email-router] relayed reply could not be prepared");continue}if(o.expired()){let m=await xr(e,u.operationId,l);console.error(m?"[email-router] action batch deadline elapsed; reservation cancelled":"[email-router] action batch deadline elapsed; cancellation unresolved");break}try{await Q(e,u.operationId,[l])}catch{let m=await xr(e,u.operationId,l);console.error(m?"[email-router] attempt did not start; reservation cancelled":"[email-router] could not confirm attempt status");continue}try{let m;s.type==="forward"?await o.run(()=>t.forward(l,s.headers)):p?m=await o.run(()=>p(l,o.remainingMs())):await o.run(()=>t.reply(new Or(s.from,l,ne(s.raw))));try{await k(e,u.operationId,[l],"provider_accepted",{providerReference:m})}catch{console.error("[email-router] provider accepted action but outcome ledger write failed")}}catch(m){let h=m instanceof U;try{await k(e,u.operationId,[l],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")}}}a(po,"enactSanitized");async function xr(e,t,r){try{return(await k(e,t,[r],"cancelled")).recipients.some(o=>o.recipient===r&&o.state==="cancelled")}catch{return!1}}a(xr,"cancelUnstartedAction");var Fe=new TextEncoder,wt=new TextDecoder,gt=128*1024,bt=320,go=2,Hr="/email/destinations/confirm",ho=4*1024,$r=32*1024,Ur=5e3,ht=0,C=class extends Error{constructor(r,n){super(r);this.status=n;this.name="MimeHeaderError"}status;static{a(this,"MimeHeaderError")}};function Et(e){return e.PLATFORM_TRAFFIC_STATE==="staging"||e.PLATFORM_TRAFFIC_STATE==="sandbox-drain"}a(Et,"isTrafficPaused");async function Fr(e){if(ht>=go)throw new Error("email gateway busy");ht++;try{return await e()}finally{ht--}}a(Fr,"withDeliverySlot");async function Br(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))),o="";for(let i of n)o+=String.fromCharCode(i);return btoa(o).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}a(Br,"sign");async function Gr(e,t){let r=Date.now()+5e3,n=new AbortController,o=a(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((A,w)=>{E=setTimeout(()=>{n.abort(),w(new Error("ingress resolution timeout"))},R)})])}finally{E!==void 0&&clearTimeout(E)}},"beforeDeadline"),i=await Br(`email-ingress-v1
|
|
4
4
|
${t.accountId}
|
|
5
5
|
${t.zoneId}
|
|
6
6
|
${t.ingressName}
|
|
7
|
-
${t.to.toLowerCase()}`,e.EMAIL_SIGNING_SECRET),s=await o(()=>e.API.fetch("https://api/internal/email/resolve-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":i},body:JSON.stringify(t),signal:n.signal}));if(!s.ok){if(s.body?.cancel().catch(()=>{}),s.status>=500||s.status===429)throw new Error("email routing unavailable");return null}let
|
|
8
|
-
`),n=Object.create(null),o="",i=0;for(let s of r){if(++i>se)throw new
|
|
7
|
+
${t.to.toLowerCase()}`,e.EMAIL_SIGNING_SECRET),s=await o(()=>e.API.fetch("https://api/internal/email/resolve-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":i},body:JSON.stringify(t),signal:n.signal}));if(!s.ok){if(s.body?.cancel().catch(()=>{}),s.status>=500||s.status===429)throw new Error("email routing unavailable");return null}let l=Number(s.headers.get("content-length"));if(Number.isFinite(l)&&l>4096)throw s.body?.cancel().catch(()=>{}),new Error("invalid email routing response");let c=s.body?.getReader();if(!c)throw new Error("invalid email routing response");let d=[],u=0;try{for(;;){let b=await o(()=>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 f=new Uint8Array(u),p=0;for(let b of d)f.set(b,p),p+=b.byteLength;let m=wt.decode(f),h;try{h=JSON.parse(m)}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"||y.mailbox!==void 0&&typeof y.mailbox!="string"||y.alias!==void 0&&typeof y.alias!="string"||typeof y.domain!="string"||y.addressing!=="shared"&&y.addressing!=="custom")throw new Error("invalid email routing response");return y}a(Gr,"resolveIngress");async function yo(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),o=0,i=Date.now()+15e3;try{for(;;){let s=i-Date.now();if(s<=0)throw new Error("MIME timeout");let l,c=await Promise.race([r.read(),new Promise((d,u)=>{l=setTimeout(()=>u(new Error("MIME timeout")),s)})]).finally(()=>{l!==void 0&&clearTimeout(l)});if(c.done)break;if(o+=c.value.byteLength,o>t||o>L)throw new Error("MIME too large");n.set(c.value,o-c.value.byteLength)}if(o!==t)throw new Error("truncated MIME");return n}catch(s){throw r.cancel().catch(()=>{}),s}finally{try{r.releaseLock()}catch{}}}a(yo,"readMime");function bo(e){let t=-1;for(let s=0;s<e.length-3&&s<gt+4;s++)if(e[s]===13&&e[s+1]===10&&e[s+2]===13&&e[s+3]===10){t=s;break}if(t<0)throw new C("invalid MIME headers",e.byteLength>gt?413:400);if(t>gt)throw new C("MIME headers too large",413);let r=wt.decode(e.subarray(0,t)).split(`\r
|
|
8
|
+
`),n=Object.create(null),o="",i=0;for(let s of r){if(++i>se)throw new C("too many MIME headers",413);if(/^[ \t]/.test(s)){if(!o)throw new C("invalid MIME header fold",400);n[o]+=` ${s.trim()}`;continue}let l=s.indexOf(":");if(l<=0)throw new C("invalid MIME header",400);let c=s.slice(0,l).toLowerCase();if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(c))throw new C("invalid MIME header name",400);n[c]=n[c]?`${n[c]}, ${s.slice(l+1).trim()}`:s.slice(l+1).trim(),o=c}return n}a(bo,"parseHeaders");async function wo(e,t,r){if(Et(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")??"",o=e.headers.get("x-void-email-zone")??"",i=e.headers.get("x-void-email-ingress")??"",s=e.headers.get("x-void-email-request-id")??"",l=e.headers.get("x-void-email-from")??"",c=e.headers.get("x-void-email-to")??"",d=e.headers.get("authorization")??"";if([n,o,i,l,c,d].some(y=>!y||y.length>bt)||!d.startsWith("Bearer ")||!/^[a-f0-9-]{36}$/.test(s))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 f=Number(u);if(!Number.isSafeInteger(f)||f<0)return new Response(null,{status:411});if(f>L)return new Response(null,{status:413});let p;try{p=await Gr(t,{accountId:n,zoneId:o,ingressName:i,from:l,to:c,secret:d.slice(7)})}catch{return new Response(null,{status:503})}if(!p)return new Response(null,{status:403});let m;try{m=await yo(e.body,f)}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=bo(m)}catch(y){if(y instanceof C)return new Response(null,{status:y.status});throw y}try{let y=c.slice(c.lastIndexOf("@")+1).toLowerCase();if(y!==p.domain)return new Response(null,{status:403});let b={from:l,to:c,raw:m,rawSize:m.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 yt(Fe.encode(JSON.stringify([p.connectionId,s]))),A=await yt(Fe.encode(JSON.stringify([l,c,await yt(m)]))),w={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 Tt(t,w)}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 S=await Cr(t,r,{stub:R,projectId:p.projectId,domain:y,envelope:b,authoritative:p,receiptId:E});if(S.temporary)return new Response(null,{status:503});try{await xt(t,w,S.reject)}catch{console.error("[email-gateway] receipt completion remains unresolved",E)}return new Response(null,{status:S.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})}}a(wo,"ingress");async function yt(e){return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e)),t=>t.toString(16).padStart(2,"0")).join("")}a(yt,"sha256");async function Eo(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 o=e.body?.getReader();if(!o)return new Response(null,{status:400});let i=new Uint8Array(1024),s=0,l=Date.now()+5e3;try{for(;;){let b=l-Date.now();if(b<=0)return new Response(null,{status:400});let R,E=await Promise.race([o.read(),new Promise((A,w)=>{R=setTimeout(()=>w(new Error("probe timeout")),b)})]).finally(()=>{R!==void 0&&clearTimeout(R)});if(E.done)break;if(s+=E.value.byteLength,s>i.byteLength)return new Response(null,{status:400});i.set(E.value,s-E.value.byteLength)}}catch{return new Response(null,{status:400})}finally{o.cancel().catch(()=>{});try{o.releaseLock()}catch{}}if(s===0||r&&s!==Number(r))return new Response(null,{status:400});let c;try{c=JSON.parse(wt.decode(i.subarray(0,s)))}catch{return new Response(null,{status:400})}if(!c||typeof c!="object")return new Response(null,{status:400});let{accountId:d,zoneId:u,ingressName:f}=c;if([d,u,f].some(b=>typeof b!="string"||!b||b.length>bt))return new Response(null,{status:400});let p=await Br(`email-probe-v1
|
|
9
9
|
${d}
|
|
10
10
|
${u}
|
|
11
|
-
${
|
|
11
|
+
${f}`,t.EMAIL_SIGNING_SECRET),m=new AbortController,h=Date.now()+5e3,y;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:f,secret:n.slice(7)}),signal:m.signal}),new Promise((R,E)=>{y=setTimeout(()=>{m.abort(),E(new Error("email probe timeout"))},Math.max(0,h-Date.now()))})]);return b.body?.cancel().catch(()=>{}),new Response(null,{status:b.status===204?204:403})}catch{return new Response(null,{status:503})}finally{y!==void 0&&clearTimeout(y)}}a(Eo,"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})}a(Ue,"confirmationResponse");async function Ro(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>$r)throw new Error("confirmation response too large");let o=e.body?.getReader();if(!o)return null;let i=new Uint8Array($r),s=0;try{for(;;){let l=t-Date.now();if(l<=0)throw new Error("confirmation response timeout");let c,d=await Promise.race([o.read(),new Promise((u,f)=>{c=setTimeout(()=>{r.abort(),f(new Error("confirmation response timeout"))},l)})]).finally(()=>{c!==void 0&&clearTimeout(c)});if(d.done)return i.slice(0,s);if(s+=d.value.byteLength,s>i.byteLength)throw new Error("confirmation response too large");i.set(d.value,s-d.value.byteLength)}}finally{o.cancel().catch(()=>{});try{o.releaseLock()}catch{}}}a(Ro,"readConfirmationResponse");async function Ao(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>ho||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(n[0][1]))return Ue(null,400);if(Et(t))return Ue(null,503);let o=Date.now()+Ur,i=new AbortController,s,l;try{let c=new URL(`https://api${Hr}`);c.searchParams.set("token",n[0][1]);let d=t.API.fetch(c.toString(),{method:e.method,redirect:"manual",signal:i.signal});d.then(f=>{i.signal.aborted&&f!==s&&f.body?.cancel().catch(()=>{})},()=>{}),s=await Promise.race([d,new Promise((f,p)=>{l=setTimeout(()=>{i.abort(),p(new Error("confirmation request timeout"))},Ur)})]),l!==void 0&&(clearTimeout(l),l=void 0);let u=await Ro(s,o,i);return Ue(u,s.status,s.headers.get("content-type"))}catch{return Ue(null,503)}finally{i.abort(),l!==void 0&&clearTimeout(l),s?.body?.cancel().catch(()=>{})}}a(Ao,"confirmDestination");var tc={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===Hr)return Ao(e,t);if(e.method!=="POST")return new Response(null,{status:404});if(n.pathname==="/email/probe")return Eo(e,t);if(n.pathname==="/email/ingress")try{return await Fr(()=>wo(e,t,r))}catch{return new Response(null,{status:503})}return new Response(null,{status:404})},async email(e,t,r){if(Et(t))throw new Error("Email gateway temporarily unavailable");let n=t.EMAIL_SHARED_ACCOUNT_ID,o=t.EMAIL_SHARED_ZONE_ID,i=t.EMAIL_SHARED_INGRESS_NAME;if(!n||!o||!i){e.setReject("Email routing is not configured");return}let s;try{s=await Gr(t,{accountId:n,zoneId:o,ingressName:i,from:e.from,to:e.to,native:!0})}catch{throw new Error("Email route temporarily unavailable")}if(!s){e.setReject("Email route unavailable");return}await Fr(()=>Lr(e,t,r,s))}};export{tc as default};
|
|
@@ -2,18 +2,18 @@
|
|
|
2
2
|
"artifacts": {
|
|
3
3
|
"api": {
|
|
4
4
|
"path": "api/index.js",
|
|
5
|
-
"sha256": "
|
|
6
|
-
"size":
|
|
5
|
+
"sha256": "45f3ecca2a4ee8dc578a8945a9fa18a057d2672ab93ffae2d357da757a00ee9a",
|
|
6
|
+
"size": 3942893
|
|
7
7
|
},
|
|
8
8
|
"dispatch": {
|
|
9
9
|
"path": "dispatch/index.js",
|
|
10
|
-
"sha256": "
|
|
11
|
-
"size":
|
|
10
|
+
"sha256": "97154b5dced18088d6b0e712beb906d4458f55d40e11c4e8bc2c77036d81f3be",
|
|
11
|
+
"size": 87656
|
|
12
12
|
},
|
|
13
13
|
"proxy": {
|
|
14
14
|
"path": "proxy/index.js",
|
|
15
|
-
"sha256": "
|
|
16
|
-
"size":
|
|
15
|
+
"sha256": "8403c5c96be9d2787382c1e9ae25e332a5e4d71a77c13f494c22e2cfdc92602e",
|
|
16
|
+
"size": 84449
|
|
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": "
|
|
26
|
-
"size":
|
|
25
|
+
"sha256": "9b0ef34e9d9998ada50655d00a0af9646afcc567011f0bb1c7fc1fb30c9a02d1",
|
|
26
|
+
"size": 81932
|
|
27
27
|
}
|
|
28
28
|
},
|
|
29
29
|
"appAccessSetup": 1,
|
|
@@ -31,13 +31,13 @@
|
|
|
31
31
|
"assets": {
|
|
32
32
|
"adminClient": {
|
|
33
33
|
"path": "api/assets/admin/client.js",
|
|
34
|
-
"sha256": "
|
|
35
|
-
"size":
|
|
34
|
+
"sha256": "3ad1767a6f0dced91eafb8ec5dd4ef2946f2678162e8bed3dc9001c8a575176e",
|
|
35
|
+
"size": 1457591
|
|
36
36
|
},
|
|
37
37
|
"adminStyle": {
|
|
38
38
|
"path": "api/assets/admin/style.css",
|
|
39
|
-
"sha256": "
|
|
40
|
-
"size":
|
|
39
|
+
"sha256": "03d780fc7c3dadfeebb0f610212399dab933443f1bec5ccaf5fe124d6c6cd811",
|
|
40
|
+
"size": 255978
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
43
|
"authenticationProtocolVersion": 1,
|
|
@@ -486,11 +486,11 @@
|
|
|
486
486
|
],
|
|
487
487
|
"schemaDigest": "8bde0b5b35b98112498be2954726223a6a059cbf92302990437e582f57a1fc98"
|
|
488
488
|
},
|
|
489
|
-
"platformVersion": "1.
|
|
489
|
+
"platformVersion": "1.5.0",
|
|
490
490
|
"safetyProtocols": {
|
|
491
491
|
"sandboxDrain": 3
|
|
492
492
|
},
|
|
493
493
|
"schemaVersion": 2,
|
|
494
|
-
"sourceRevision": "
|
|
494
|
+
"sourceRevision": "afeeff6a4d72682f6cfb6c947e9a2c29393c00a6",
|
|
495
495
|
"usageProtocolVersion": 2
|
|
496
496
|
}
|