@void/platform 1.1.11 → 1.1.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +12 -2
- package/dist/index.mjs +17 -1
- package/dist/runtime/api/assets/admin/client.js +42 -42
- package/dist/runtime/api/assets/admin/style.css +1 -1
- package/dist/runtime/api/index.js +243 -237
- package/dist/runtime/dispatch/index.js +1 -1
- package/dist/runtime/emailGateway/index.js +3 -3
- package/dist/runtime/manifest.json +12 -12
- package/dist/runtime/proxy/index.js +3 -3
- package/package.json +1 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var qr=Object.create;var He=Object.defineProperty;var Wr=Object.getOwnPropertyDescriptor;var Xr=Object.getOwnPropertyNames;var Jr=Object.getPrototypeOf,Yr=Object.prototype.hasOwnProperty;var c=(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 Kr=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Qr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xr(t))!Yr.call(e,o)&&o!==r&&He(e,o,{get:()=>t[o],enumerable:!(n=Wr(t,o))||n.enumerable});return e};var Zr=(e,t,r)=>(r=e!=null?qr(Jr(e)):{},Qr(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();c(H,"createNotImplementedError")});var Be,Ge,en,B,ze,X,J,ce,V,le,Y,It=ae(()=>{g();_t();Be=globalThis.performance?.timeOrigin??Date.now(),Ge=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-Be,en={name:"node",entryType:"node",startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},B=class{static{c(this,"PerformanceEntry")}__unenv__=!0;detail;entryType="event";name;startTime;constructor(t,r){this.name=t,this.startTime=r?.startTime||Ge(),this.detail=r?.detail}get duration(){return Ge()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},ze=class extends B{static{c(this,"PerformanceMark")}entryType="mark";constructor(){super(...arguments)}get duration(){return 0}},X=class extends B{static{c(this,"PerformanceMeasure")}entryType="measure"},J=class extends B{static{c(this,"PerformanceResourceTiming")}entryType="resource";serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType="";name="";nextHopProtocol="";redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},ce=class{static{c(this,"PerformanceObserverEntryList")}__unenv__=!0;getEntries(){return[]}getEntriesByName(t,r){return[]}getEntriesByType(t){return[]}},V=class{static{c(this,"Performance")}__unenv__=!0;timeOrigin=Be;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(t,r){throw H("Performance.timerify")}get nodeTiming(){return en}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}},le=class{static{c(this,"PerformanceObserver")}__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(t){this._callback=t}takeRecords(){return[]}disconnect(){throw H("PerformanceObserver.disconnect")}observe(t){throw H("PerformanceObserver.observe")}bind(t){return t}runInAsyncScope(t,r,...n){return t.call(r,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},Y=globalThis.performance&&"addEventListener"in globalThis.performance?globalThis.performance:new V});var 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=le;globalThis.PerformanceObserverEntryList=ce;globalThis.PerformanceResourceTiming=J});var Lt=Kr(Dt=>{"use strict";g();var dn=/^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;Dt.validate=function(e){if(!e||e.length>254)return!1;var t=dn.test(e);if(!t)return!1;var r=e.split("@");if(r[0].length>64)return!1;var n=r[1].split(".");return!n.some(function(o){return o.length>63})}});g();g();g();var Mt=new TextEncoder,de,St;async function tn(e){return de&&St===e||(de=await crypto.subtle.importKey("raw",Mt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),St=e),de}c(tn,"getSignKey");async function ue(e,t){let r=await tn(t),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,Mt.encode(e)));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(ue,"hmacSign");var fe=new TextEncoder,K=new TextDecoder,rn=5e3,me=15e3,Nt=15e3,nn=65536;async function on(e,t){if(!t)throw new Error("Email signing key is not configured");return ue(e,t)}c(on,"sign");async function q(e,t,r,n=rn){let o=new AbortController,i=Date.now()+n,s=c(async f=>{let h=i-Date.now();if(h<=0)throw o.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let y=f(),E;try{return await Promise.race([y,new Promise((R,w)=>{E=setTimeout(()=>{o.abort(),w(new Error("EMAIL_ADMISSION_TIMEOUT"))},h)})])}finally{E!==void 0&&clearTimeout(E)}},"beforeDeadline"),a=JSON.stringify(r),l=await on(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":l},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(nn),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{}}}c(q,"call");function Ot(e,t){return q(e,"/receipts/claim",t)}c(Ot,"claimRelayedReceipt");function Pt(e,t,r){return q(e,"/receipts/complete",{receiptId:t.receiptId,projectId:t.projectId,payloadDigest:t.payloadDigest,reject:r})}c(Pt,"completeRelayedReceipt");function sn(e){if(an(e)===-1)return e;let t=new Map,r=[],n=0,o=0,i=!1,s=!0,a=!0,l=c(f=>{f.byteLength!==0&&(r.push(f),n+=f.byteLength)},"append"),d=c((f,h,y)=>{l(e.subarray(o,f)),l(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,E=h,R=K.decode(e.subarray(u,y));for(;e[E]===32||e[E]===9;)y=Tt(e,E),R+=` ${K.decode(e.subarray(E,y)).replace(/^[ \t]+/,"")}`,E=y===e.byteLength?e.byteLength:y+2;let w=R.replace(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(A,b)=>{let _=t.get(b);return _||(_=`<void-boundary-${t.size}>`,t.set(b,_)),`boundary="${_}"`});w!==R&&d(u,y,fe.encode(w)),u=E;continue}}else if(e[u]===45&&e[u+1]===45){let y=u+2,E=xt(e,y,f)?K.decode(e.subarray(y,f)):void 0,R=E===void 0?void 0:t.get(E);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;l(e.subarray(o));let m=new Uint8Array(n),p=0;for(let f of r)m.set(f,p),p+=f.byteLength;return m}c(sn,"canonicalizeVoidMime");function an(e){for(let t=0;t+3<e.byteLength;t++)if(e[t]===13&&e[t+1]===10&&e[t+2]===13&&e[t+3]===10)return t;return-1}c(an,"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}c(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}c(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/")}c(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}c(xt,"isBoundaryToken");async function ge(e,t,r,n){let o=sn(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("")}c(ge,"emailPayloadDigest");function he(e,t,r=Nt){return q(e,"/admit",t,Math.min(r,Nt))}c(he,"admitEmail");function Q(e,t,r,n=me){return q(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Math.min(n,me))}c(Q,"startEmailAttempt");function P(e,t,r,n,o={},i=me){return q(e,`/${encodeURIComponent(t)}/finish`,{recipients:r,state:n,...o},Math.min(i,me))}c(P,"finishEmailAttempt");function G(e,t,r,n,o){return q(e,"/receipts",{receiptId:t,projectId:r,status:n,...o?{route:o}:{}})}c(G,"recordEmailReceipt");g();g();var ln=new Set(["abuse","bounce","noreply","postmaster","security"]);function kt(e){return ln.has(e)}c(kt,"isReservedEmailSlug");var Lr=Zr(Lt(),1);import{EmailMessage as Dr}from"cloudflare:email";g();g();var jt="/__void/email/receipt/v1";var Ve=new TextEncoder,un=new TextDecoder("utf-8",{fatal:!0});function fn(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")}c(fn,"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}c($t,"encodeEmailEnvelope");function Ct(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}c(Ct,"base64url");async function mn(e,t){if(!e)throw new Error("Email signing key is not configured");return crypto.subtle.importKey("raw",Ve.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t])}c(mn,"receiptKey");async function Ut(e,t){let r=Ve.encode(JSON.stringify(e)),n=new Uint8Array(await crypto.subtle.sign("HMAC",await mn(t,"sign"),r));return`${Ct(r)}.${Ct(n)}`}c(Ut,"signEmailReceipt");async function Ft(e,t=15e3){return gn(e,async r=>{let n=[],o=new Uint8Array(0),i=0,s=Date.now()+t,a=c(()=>pn(r,s,"email response timeout"),"readChunk");async function l(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(c(l,"exact");;){let d=await l(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 l(u);fn(p,2,40);let f=JSON.parse(un.decode(p));if(!f||typeof f!="object"||Array.isArray(f))throw new Error("invalid email action");let h=f;if(h.type==="reply"){if(typeof h.from!="string"||typeof h.to!="string"||Object.keys(h).length!==3)throw new Error("invalid email reply");let y=await l(5),E=new DataView(y.buffer).getUint32(0);if(y[4]!==2||E>5242880)throw new Error("invalid email reply frame");n.push({type:"reply",from:h.from,to:h.to,raw:await l(E)})}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(E=>typeof E!="string")))throw new Error("invalid email headers");n.push({type:"forward",to:h.to,...y?{headers:y}:{}})}else if(h.type==="reject"){if(typeof h.reason!="string"||Object.keys(h).length!==2)throw new Error("invalid email reject");n.push({type:"reject",reason:h.reason})}else throw new Error("unknown email action")}})}c(Ft,"readEmailActions");async function pn(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)})}c(pn,"readBeforeDeadline");async function gn(e,t){let r=e.getReader();try{return await t(r)}catch(n){throw r.cancel().catch(()=>{}),n}finally{try{r.releaseLock()}catch{}}}c(gn,"withReader");var hn=8,yn=2e4,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>=hn)throw new Error("email project concurrency exceeded");Z.set(r.projectId,o+1);let i=Date.now()+yn,s=new AbortController,a;try{let l=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":l,"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 l=(Z.get(r.projectId)??1)-1;l===0?Z.delete(r.projectId):Z.set(r.projectId,l)}}c(qe,"dispatchBoundedEmailToTenant");g();var Bt=5e3,Gt=4*1024;function ye(e){return e.token}c(ye,"leaseBearer");async function Ee(e,t,r,n=Bt){if(!e.EMAIL_SIGNING_SECRET)return null;let o=new AbortController,i=Date.now()+Math.min(n,Bt),s=c(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((E,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 qr=Object.create;var He=Object.defineProperty;var Wr=Object.getOwnPropertyDescriptor;var Xr=Object.getOwnPropertyNames;var Jr=Object.getPrototypeOf,Yr=Object.prototype.hasOwnProperty;var c=(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 Kr=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Qr=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xr(t))!Yr.call(e,o)&&o!==r&&He(e,o,{get:()=>t[o],enumerable:!(n=Wr(t,o))||n.enumerable});return e};var Zr=(e,t,r)=>(r=e!=null?qr(Jr(e)):{},Qr(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();c(H,"createNotImplementedError")});var Be,Ge,en,B,ze,X,J,ce,V,le,Y,It=ae(()=>{g();_t();Be=globalThis.performance?.timeOrigin??Date.now(),Ge=globalThis.performance?.now?globalThis.performance.now.bind(globalThis.performance):()=>Date.now()-Be,en={name:"node",entryType:"node",startTime:0,duration:0,nodeStart:0,v8Start:0,bootstrapComplete:0,environment:0,loopStart:0,loopExit:0,idleTime:0,uvMetricsInfo:{loopCount:0,events:0,eventsWaiting:0},detail:void 0,toJSON(){return this}},B=class{static{c(this,"PerformanceEntry")}__unenv__=!0;detail;entryType="event";name;startTime;constructor(t,r){this.name=t,this.startTime=r?.startTime||Ge(),this.detail=r?.detail}get duration(){return Ge()-this.startTime}toJSON(){return{name:this.name,entryType:this.entryType,startTime:this.startTime,duration:this.duration,detail:this.detail}}},ze=class extends B{static{c(this,"PerformanceMark")}entryType="mark";constructor(){super(...arguments)}get duration(){return 0}},X=class extends B{static{c(this,"PerformanceMeasure")}entryType="measure"},J=class extends B{static{c(this,"PerformanceResourceTiming")}entryType="resource";serverTiming=[];connectEnd=0;connectStart=0;decodedBodySize=0;domainLookupEnd=0;domainLookupStart=0;encodedBodySize=0;fetchStart=0;initiatorType="";name="";nextHopProtocol="";redirectEnd=0;redirectStart=0;requestStart=0;responseEnd=0;responseStart=0;secureConnectionStart=0;startTime=0;transferSize=0;workerStart=0;responseStatus=0},ce=class{static{c(this,"PerformanceObserverEntryList")}__unenv__=!0;getEntries(){return[]}getEntriesByName(t,r){return[]}getEntriesByType(t){return[]}},V=class{static{c(this,"Performance")}__unenv__=!0;timeOrigin=Be;eventCounts=new Map;_entries=[];_resourceTimingBufferSize=0;navigation=void 0;timing=void 0;timerify(t,r){throw H("Performance.timerify")}get nodeTiming(){return en}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}},le=class{static{c(this,"PerformanceObserver")}__unenv__=!0;static supportedEntryTypes=[];_callback=null;constructor(t){this._callback=t}takeRecords(){return[]}disconnect(){throw H("PerformanceObserver.disconnect")}observe(t){throw H("PerformanceObserver.observe")}bind(t){return t}runInAsyncScope(t,r,...n){return t.call(r,...n)}asyncId(){return 0}triggerAsyncId(){return 0}emitDestroy(){return this}},Y=globalThis.performance&&"addEventListener"in globalThis.performance?globalThis.performance:new V});var 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=le;globalThis.PerformanceObserverEntryList=ce;globalThis.PerformanceResourceTiming=J});var Lt=Kr(Dt=>{"use strict";g();var dn=/^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;Dt.validate=function(e){if(!e||e.length>254)return!1;var t=dn.test(e);if(!t)return!1;var r=e.split("@");if(r[0].length>64)return!1;var n=r[1].split(".");return!n.some(function(o){return o.length>63})}});g();g();g();var Mt=new TextEncoder,de,St;async function tn(e){return de&&St===e||(de=await crypto.subtle.importKey("raw",Mt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),St=e),de}c(tn,"getSignKey");async function ue(e,t){let r=await tn(t),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,Mt.encode(e)));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(ue,"hmacSign");var fe=new TextEncoder,K=new TextDecoder,rn=5e3,me=15e3,Nt=15e3,nn=65536;async function on(e,t){if(!t)throw new Error("Email signing key is not configured");return ue(e,t)}c(on,"sign");async function q(e,t,r,n=rn){let o=new AbortController,i=Date.now()+n,s=c(async f=>{let h=i-Date.now();if(h<=0)throw o.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let y=f(),E;try{return await Promise.race([y,new Promise((R,w)=>{E=setTimeout(()=>{o.abort(),w(new Error("EMAIL_ADMISSION_TIMEOUT"))},h)})])}finally{E!==void 0&&clearTimeout(E)}},"beforeDeadline"),a=JSON.stringify(r),l=await on(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":l},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(nn),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{}}}c(q,"call");function Ot(e,t){return q(e,"/receipts/claim",t)}c(Ot,"claimRelayedReceipt");function kt(e,t,r){return q(e,"/receipts/complete",{receiptId:t.receiptId,projectId:t.projectId,payloadDigest:t.payloadDigest,reject:r})}c(kt,"completeRelayedReceipt");function sn(e){if(an(e)===-1)return e;let t=new Map,r=[],n=0,o=0,i=!1,s=!0,a=!0,l=c(f=>{f.byteLength!==0&&(r.push(f),n+=f.byteLength)},"append"),d=c((f,h,y)=>{l(e.subarray(o,f)),l(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,E=h,R=K.decode(e.subarray(u,y));for(;e[E]===32||e[E]===9;)y=Tt(e,E),R+=` ${K.decode(e.subarray(E,y)).replace(/^[ \t]+/,"")}`,E=y===e.byteLength?e.byteLength:y+2;let w=R.replace(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(A,b)=>{let _=t.get(b);return _||(_=`<void-boundary-${t.size}>`,t.set(b,_)),`boundary="${_}"`});w!==R&&d(u,y,fe.encode(w)),u=E;continue}}else if(e[u]===45&&e[u+1]===45){let y=u+2,E=xt(e,y,f)?K.decode(e.subarray(y,f)):void 0,R=E===void 0?void 0:t.get(E);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;l(e.subarray(o));let m=new Uint8Array(n),p=0;for(let f of r)m.set(f,p),p+=f.byteLength;return m}c(sn,"canonicalizeVoidMime");function an(e){for(let t=0;t+3<e.byteLength;t++)if(e[t]===13&&e[t+1]===10&&e[t+2]===13&&e[t+3]===10)return t;return-1}c(an,"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}c(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}c(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/")}c(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}c(xt,"isBoundaryToken");async function ge(e,t,r,n){let o=sn(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("")}c(ge,"emailPayloadDigest");function he(e,t,r=Nt){return q(e,"/admit",t,Math.min(r,Nt))}c(he,"admitEmail");function Q(e,t,r,n=me){return q(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Math.min(n,me))}c(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))}c(k,"finishEmailAttempt");function G(e,t,r,n,o){return q(e,"/receipts",{receiptId:t,projectId:r,status:n,...o?{route:o}:{}})}c(G,"recordEmailReceipt");g();g();var ln=new Set(["abuse","bounce","noreply","postmaster","security"]);function Pt(e){return ln.has(e)}c(Pt,"isReservedEmailSlug");var Lr=Zr(Lt(),1);import{EmailMessage as Dr}from"cloudflare:email";g();g();var jt="/__void/email/receipt/v1";var Ve=new TextEncoder,un=new TextDecoder("utf-8",{fatal:!0});function fn(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")}c(fn,"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}c($t,"encodeEmailEnvelope");function Ct(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}c(Ct,"base64url");async function mn(e,t){if(!e)throw new Error("Email signing key is not configured");return crypto.subtle.importKey("raw",Ve.encode(e),{name:"HMAC",hash:"SHA-256"},!1,[t])}c(mn,"receiptKey");async function Ut(e,t){let r=Ve.encode(JSON.stringify(e)),n=new Uint8Array(await crypto.subtle.sign("HMAC",await mn(t,"sign"),r));return`${Ct(r)}.${Ct(n)}`}c(Ut,"signEmailReceipt");async function Ft(e,t=15e3){return gn(e,async r=>{let n=[],o=new Uint8Array(0),i=0,s=Date.now()+t,a=c(()=>pn(r,s,"email response timeout"),"readChunk");async function l(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(c(l,"exact");;){let d=await l(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 l(u);fn(p,2,40);let f=JSON.parse(un.decode(p));if(!f||typeof f!="object"||Array.isArray(f))throw new Error("invalid email action");let h=f;if(h.type==="reply"){if(typeof h.from!="string"||typeof h.to!="string"||Object.keys(h).length!==3)throw new Error("invalid email reply");let y=await l(5),E=new DataView(y.buffer).getUint32(0);if(y[4]!==2||E>5242880)throw new Error("invalid email reply frame");n.push({type:"reply",from:h.from,to:h.to,raw:await l(E)})}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(E=>typeof E!="string")))throw new Error("invalid email headers");n.push({type:"forward",to:h.to,...y?{headers:y}:{}})}else if(h.type==="reject"){if(typeof h.reason!="string"||Object.keys(h).length!==2)throw new Error("invalid email reject");n.push({type:"reject",reason:h.reason})}else throw new Error("unknown email action")}})}c(Ft,"readEmailActions");async function pn(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)})}c(pn,"readBeforeDeadline");async function gn(e,t){let r=e.getReader();try{return await t(r)}catch(n){throw r.cancel().catch(()=>{}),n}finally{try{r.releaseLock()}catch{}}}c(gn,"withReader");var hn=8,yn=2e4,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>=hn)throw new Error("email project concurrency exceeded");Z.set(r.projectId,o+1);let i=Date.now()+yn,s=new AbortController,a;try{let l=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":l,"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 l=(Z.get(r.projectId)??1)-1;l===0?Z.delete(r.projectId):Z.set(r.projectId,l)}}c(qe,"dispatchBoundedEmailToTenant");g();var Bt=5e3,Gt=4*1024;function ye(e){return e.token}c(ye,"leaseBearer");async function Ee(e,t,r,n=Bt){if(!e.EMAIL_SIGNING_SECRET)return null;let o=new AbortController,i=Date.now()+Math.min(n,Bt),s=c(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((E,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
|
|
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 l=a.headers.get("content-length");if(l!==null&&(!/^\d+$/.test(l)||Number(l)>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(l!==null&&m!==Number(l))return null;let p=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,m)));return bn(p)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}c(Ee,"leaseEmailDomainCredential");function bn(e){if(typeof e!="object"||e===null)return null;let t=e.kind,r=e.accountId;if(typeof r!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(r))return null;if(t==="api_token"){let n=e.token;return typeof n=="string"&&n.length>0?{kind:t,token:n,accountId:r}:null}return null}c(bn,"parseLease");g();var be=class extends Error{static{c(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 be;let i=r(),s;try{return await Promise.race([i,new Promise((a,l)=>{s=setTimeout(()=>l(new be),o)})])}finally{s!==void 0&&clearTimeout(s)}}}}c(we,"createEmailProviderDeadline");g();import{EmailMessage as Cn}from"cloudflare:email";g();g();g();g();g();var zt=Symbol();g();g();g();var Vt=c((e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData(),"bufferToFormData");var wn=1e4,Re=c(e=>"headers"in e,"isRawRequest"),Xt=c(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"?Rn(e,{all:r,dot:n}):{}},"parseBody");async function Rn(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):{}}c(Rn,"parseFormData");function qt(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,i)=>{t.all||i.endsWith("[]")?An(r,i,o):r[i]=o}),t.dot&&Object.entries(r).forEach(([o,i])=>{o.includes(".")&&(_n(r,o,i,n),delete r[o])}),r}c(qt,"convertFormDataToBodyData");var An=c((e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},"handleParsingAllValues"),_n=c((e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let 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++>=wn&&Wt(),o[s]=Object.create(null)),o=o[s])})},"handleParsingNestedValues"),Wt=c(()=>{throw new Error("Nesting limit exceeded")},"throwNestingLimitExceeded");g();var Xe=c(e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},"splitPath"),Jt=c(e=>{let{groups:t,path:r}=In(e),n=Xe(r);return vn(n,t)},"splitRoutingPath"),In=c(e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},"extractGroupsFromPath"),vn=c((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=c((e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Ae[n]||(r[2]?Ae[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Ae[n]=[e,r[1],!0]),Ae[n]}return null},"getPattern"),Kt=c((e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},"tryDecode"),Sn=c(e=>Kt(e,decodeURI),"tryDecodeURI"),Je=c(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),l=t.slice(r,a);return Sn(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(o===63||o===35)break}return t.slice(r,n)},"getPath");var Qt=c(e=>{let t=Je(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},"getPathNoStrict"),C=c((e,t,...r)=>(r.length&&(t=C(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),"mergePath"),_e=c(e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(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=c(e=>e.indexOf("%")!==-1?Kt(e,Mn):e,"tryDecodeURIComponent"),We=c(e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Ie(e)),"_decodeURI"),Zt=c((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 l=e.charCodeAt(a+t.length+1);if(l===61){let d=a+t.length+2,u=e.indexOf("&",d);return We(e.slice(d,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";a=e.indexOf(`&${t}`,a+1)}if(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),l=e.indexOf("=",s);l>a&&a!==-1&&(l=-1);let d=e.slice(s+1,l===-1?a===-1?void 0:a:l);if(o&&(d=We(d)),s=a,d==="")continue;let u;l===-1?u="":(u=e.slice(l+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=c((e,t)=>Zt(e,t,!0),"getQueryParams"),Mn=decodeURIComponent;var rr=class{static{c(this,"HonoRequest")}raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#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=c(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},Nn=c((e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},"raw");var Ye=c(async(e,t,r,n,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(l=>Ye(l,t,!1,n,o))).then(()=>o[0]));return r?Nn(await s,i):s},"resolveCallback");var Tn="text/plain; charset=UTF-8",Ke=c((e,t)=>({"Content-Type":e,...t}),"setDefaultContentType"),ee=c((e,t)=>new Response(e,t),"createResponseInstance"),Qe=class{static{c(this,"Context")}#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#d;#c;#l;#a;#u;#f;constructor(e,t){this.#t=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new 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=c((...e)=>(this.#c??=t=>this.html(t),this.#c(...e)),"render");setLayout=c(e=>this.#d=e,"setLayout");getLayout=c(()=>this.#d,"getLayout");setRenderer=c(e=>{this.#c=e},"setRenderer");header=c((e,t,r)=>{this.finalized&&(this.#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=c(e=>{this.#s=e},"status");set=c((e,t)=>{this.#r??=new Map,this.#r.set(e,t)},"set");get=c(e=>this.#r?this.#r.get(e):void 0,"get");get var(){return this.#r?Object.fromEntries(this.#r):{}}#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=c((...e)=>this.#i(...e),"newResponse");body=c((e,t,r)=>this.#i(e,t,r),"body");text=c((e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,Ke(Tn,r)),"text");json=c((e,t,r)=>this.#i(JSON.stringify(e),t,Ke("application/json",r)),"json");html=c((e,t,r)=>{let n=c(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=c((e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)},"redirect");notFound=c(()=>(this.#l??=()=>ee(),this.#l(this)),"notFound")};g();g();g();var Ze=c((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 l,d=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{l=await u(n,()=>s(a+1))}catch(m){if(m instanceof Error&&t)n.error=m,l=await t(m,n),d=!0;else throw m}else n.finalized===!1&&r&&(l=await r(n));return l&&(n.finalized===!1||d)&&(n.res=l),n}},"compose");g();var 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{c(this,"UnsupportedPathError")}};g();var sr="__COMPOSED_HANDLER";var xn=c(e=>e.text("404 Not Found",404),"notFoundHandler"),ir=c((e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},"errorHandler"),ar=class cr{static{c(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(l=>{this.#s(a,this.#t,l)}),this}}),this.on=(o,i,...s)=>{for(let a of[i].flat()){this.#t=a;for(let l of[o].flat()){let d=l.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 cr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=xn;errorHandler=ir;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let i;r.errorHandler===ir?i=o.handler:(i=c(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=c(t=>(this.errorHandler=t,this),"onError");notFound=c(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=c(l=>l,"replaceRequest"):o=n.replaceRequest));let s=i?l=>{let d=i(l);return Array.isArray(d)?d:[d]}:l=>{let d;try{d=l.executionCtx}catch{}return[l.env,d]};o||=(()=>{let l=C(this._basePath,t),d=l==="/"?0:l.length;return u=>{let m=new URL(u.url);return m.pathname=this.getPath(u).slice(d)||"/",new Request(m,u)}})();let a=c(async(l,d)=>{let u=await r(o(l.req.raw),...s(l));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 l=Ze(s[0],this.errorHandler,this.#r);return(async()=>{try{let d=await l(a);if(!d.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return d.res}catch(d){return this.#n(d,a)}})()}fetch=c((t,...r)=>this.#o(t,r[1],r[0],t.method),"fetch");request=c((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=c(()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})},"fire")};g();g();var v=c(()=>Object.create(null),"createNullObject");g();var Me=[];function et(e,t){let r=this.buildAllMatchers(),n=c(((o,i)=>{let s=r[o]||r.ALL,a=s[2][i];if(a)return a;let l=i.match(s[0]);if(!l)return[[],Me];let d=l.indexOf("",1);return[s[1][d],l]}),"match");return this.match=n,n(e,t)}c(et,"match");g();var rt="[^/]+";var nt="(?:|/.*)",j=Symbol(),lr=new Set(".\\+*[^]$()");function On(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===".*"||e==="(?:|/.*)"?t==="(?:|/.*)"?-1:1:t===".*"||t==="(?:|/.*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}c(On,"compareKey");var dr=class tt{static{c(this,"Node")}#t;#e;#r=v();insert(t,r,n,o,i){let s=this;for(let a=0,l=t.length;a<l;a++){let d=t[a],u=d.length===1?d==="*"?a===l-1?["","",".*"]:["","",rt]:null:d==="/*"?["","",nt]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),m;if(u){let p=u[1],f=u[2]||"[^/]+";if(p&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&lr.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(On).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:lr.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{c(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,l=>{let d=`@\\${s}`;return n[s]=[d,l],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 l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].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}`)}$`)}c(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]]}c(Ne,"findMiddleware");var Te=class{static{c(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 l in a.ALL)a[e][l]=[...a.ALL[l]],this.#s(e,l)}}t==="/*"&&(t="*");let i=e==="ALL"?Object.keys(n):[e];if(/\*$/.test(t)){let a=fr(t);for(let l of i)n[l][t]||(this.#s(l,t),n[l][t]=Ne(n[l],t)||Ne(n.ALL,t)||[]);for(let l of[n,o])for(let d of i)for(let u in l[d])a.test(u)&&l[d][u].push([r,t]);return}let s=_e(t)||[t];for(let a of s)for(let l of i)o[l][a]||(this.#s(l,a),o[l][a]=Ne(n[l],a)||Ne(n.ALL,a)||[]),o[l][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,l]=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,[E],R)=>(y[E]=l[p[1][R][1]],y),v())])}return[s,a.map(d=>i[d]),o]}};g();g();g();var mr=class{static{c(this,"SmartRouter")}name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(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 l=0,d=n.length;l<d;l++)a.add(...n[l]);s=a.match(e,t)}catch(l){if(l instanceof Se)continue;throw l}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(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{c(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 l of i){let d=i[++a],u=Yt(l,d)||(d===void 0&&l&&l.indexOf("*")===l.length-1?l:null),m=Array.isArray(u),p=m?u[0]:u||l,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 l=r.#t[s],d=l[n]||l.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,l=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 E=o[h],R=E.#e[u];R&&(R.#n=E.#n,m?(R.#e["*"]&&this.#o(n,R.#e["*"],t,E.#n),this.#o(n,R,t,E.#n)):p.push(R));for(let w of E.#r){let A=w.#s,b=E.#n===st?{}:{...E.#n};if(typeof A=="string"){(A==="*"||u.startsWith(A.slice(0,-1)))&&(this.#o(n,w,t,E.#n),A==="*"&&(w.#n=b,p.push(w)));continue}let[,_,M]=A;if(!(!u&&M===!0)){if(M!==!0){if(!l){l=[];let x=r[0]==="/"?1:0;for(let k=0;k<a;k++)l[k]=x,x+=i[k].length+1}let O=r.slice(l[d]),T=M.exec(O);if(T){b[_]=T[0],this.#o(n,w,t,E.#n,b),T[0].length===O.length&&w.#e["*"]&&this.#o(n,w.#e["*"],t,E.#n,b);for(let x in w.#e){w.#n=b;let k=T[0].match(/\//g)?.length??0;(s[k]||=[]).push(w);break}continue}}(M===!0||M.test(u))&&(b[_]=u,m?(this.#o(n,w,t,b,E.#n),w.#e["*"]&&this.#o(n,w.#e["*"],t,b,E.#n)):(w.#n=b,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{c(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{c(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}c(te,"asString");var jn=new at,$n=5e4,z=5e3,xe=5*1024*1024,Un=16*1024,Fn=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 Hn(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&&!Fn.has(a)}if(r&&(t+=i-n+2,t>Un))return!1;n=o+1}return!0}c(Hn,"customMimeHeaderBytesWithinLimit");var yr=50,Er=320,br=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}c(re,"readSenderDomain");var Bn=/[.*+?^${}()|[\]\\]/g;function Gn(e){return e.replace(Bn,"\\$&")}c(Gn,"escapeRegExp");var wr=new Map;function zn(e){let t=wr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${Gn(e)}$`);return wr.set(e,r),r}c(zn,"strictFromRe");var Vn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function I(e,t=200){return e.slice(0,t).replace(Vn," ")}c(I,"sanitizeForLog");var qn=128;function ne(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}c(ne,"bytesToStream");var Rr=10,Oe=13,_r=32,Ir=9,Wn=58,Pe=[102,114,111,109];function Xn(e,t,r){if(r-t<=Pe.length)return-1;for(let o=0;o<Pe.length;o++)if((e[t+o]|32)!==Pe[o])return-1;let n=t+Pe.length;for(;n<r&&(e[n]===_r||e[n]===Ir);)n++;return n<r&&e[n]===Wn?n+1:-1}c(Xn,"fromValueStart");var Jn={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),l=0;for(;l<t;){let m=e.indexOf(Rr,l),f=m===-1?t:m;if(f>l&&e[f-1]===Oe&&f--,f===l)break;if(a!==-1&&a<l&&(a=e.indexOf(Oe,l)),a!==-1&&a<f)return{ok:!1,reason:"malformed"};if(e[l]===_r||e[l]===Ir)s&&(o=f,i=!0);else{let h=Xn(e,l,f);s=h!==-1,s&&(r++,n=h,o=f,i=!1)}l=m===-1?t:m+1}if(r===0)return{ok:!1,reason:"missing"};if(r>1)return{ok:!1,reason:"multiple"};let d=e.subarray(n,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=Yn(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}c(dt,"readMimeFromAddrSpec");function Yn(e){let t=!1,r=!1,n=-1,o=-1,i=-1;for(let a=0;a<e.length;a++){let l=e[a];if(t){r?r=!1:l==="\\"?r=!0:l==='"'&&(t=!1);continue}switch(l){case'"':if(n!==-1)return null;t=!0;break;case"<":if(n!==-1)return null;n=a;break;case">":if(n===-1||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}c(Yn,"singleMailboxAddrSpec");jn.post("/send",async e=>{let t=we($n),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,qn),l=te(n.idempotencyKey);if(l!==null&&(l.length===0||l.length>128||!/^[\x20-\x7e]+$/.test(l)))return e.json({ok:!1,error:{code:"INVALID_TO",message:"invalid idempotency key"}},400);let d=l??(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>br)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${br} 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>Er)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${Er} 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=Qn(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(!Hn(h))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let y=o.indexOf("@"),E=y===-1?"":o.slice(y+1).toLowerCase();if(E!==""&&E!==m)return Kn(e,r,o,E,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(!zn(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,k=T.recipients.filter(S=>S.state==="reserved").map(S=>S.recipient);for(let S=0;S<k.length;S++){let N=k[S];if(t.expired(z)){let F=k.slice(S),W=await ct(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 ct(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 Cn(o,N,ne(h)),W=await t.run(()=>R.send(F),z),ie=typeof W?.messageId=="string"?W.messageId:"";try{await P(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 P(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=c(async m=>{let p=n-Date.now();if(p<=0)throw r.abort(),new Error("email sending request timed out");let f=m(),h;try{return await Promise.race([f,new Promise((y,E)=>{h=setTimeout(()=>{r.abort(),E(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 l=s.body?.getReader();if(!l)throw new Error("email sending API response unreadable");let d=new Uint8Array(Ar),u=0;try{for(;;){let m=await i(()=>l.read());if(m.done)break;if(u+m.value.byteLength>d.byteLength)throw new Error("email sending API response too large");d.set(m.value,u),u+=m.value.byteLength}if(a!==null&&u!==Number(a))throw new Error("email sending API response length mismatch");return{ok:!0,data:JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(d.subarray(0,u)))}}finally{l.cancel().catch(()=>{});try{l.releaseLock()}catch{}}}c(ut,"requestSendRaw");function ke(e){if(!Array.isArray(e))return null;let t=new Set;for(let r of e){if(typeof r!="string")return null;t.add(r.toLowerCase())}return t}c(ke,"readSendRawAddressList");function ft(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=ke(t.delivered),n=ke(t.permanent_bounces),o=ke(t.queued),i=ke(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}}c(ft,"parseSendRawResult");function mt(e,t){let r=t.toLowerCase(),n=[e.delivered.has(r),e.queued.has(r),e.permanentBounces.has(r),e.suppressedRecipients.has(r)];return n.filter(Boolean).length!==1?"outcome_unknown":n[0]||n[1]?"provider_accepted":n[2]?"permanent_bounce":"suppressed"}c(mt,"classifySendRawRecipient");async function Kn(e,t,r,n,o,i,s,a,l,d){if(!/^[\x21-\x7e]+$/.test(r))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let u=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:l,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(b=>b.state==="reserved").map(b=>b.recipient),i.length===0)return lt(e,f.operationId,h);let y=await Ee(e.env,n,t,d.remainingMs(z));if(!y)return await P(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 P(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 b=await ct(e.env,f.operationId,i,d.remainingMs());for(let _ of i)h.push({recipient:_,ok:!1,state:b?"cancelled":"outcome_unknown",error:b?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return lt(e,f.operationId,h)}let E=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{E={code:"UPSTREAM_ERROR",message:"email sending request failed"},R="outcome_unknown"}if(A)if(!A.ok)E={code:A.status===429?"QUOTA_EXCEEDED":"UPSTREAM_ERROR",message:`email sending API returned ${A.status}`},R=A.status>=500||A.status===408?"outcome_unknown":"failed";else{let b=A.data,_=typeof b=="object"&&b!==null?b.success:void 0;_===!1?E={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:_!==!0?(E={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"):(w=ft(b.result),w||(E={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"))}for(let b of i){if(E){h.push({recipient:b,ok:!1,state:R,error:E});continue}let _=mt(w,b);_==="permanent_bounce"?h.push({recipient:b,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${b}' permanently bounced`}}):_==="suppressed"?h.push({recipient:b,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${b}' is on the suppression list`}}):_==="outcome_unknown"?h.push({recipient:b,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):h.push({recipient:b,ok:!0,state:"provider_accepted",messageId:w.messageId})}for(let b of h.filter(_=>f.recipients.some(M=>M.recipient===_.recipient&&M.state==="reserved")))try{await P(e.env,f.operationId,[b.recipient],b.ok?"provider_accepted":b.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:b.messageId,errorCode:b.ok?void 0:b.state==="outcome_unknown"?"OUTCOME_UNKNOWN":E?.code??b.error?.code},d.remainingMs()),b.state=b.ok?"provider_accepted":b.state==="outcome_unknown"?"outcome_unknown":"failed",b.state==="outcome_unknown"&&!b.ok&&(b.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{b.ok=!1,b.state="outcome_unknown",b.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return Nr(t,a,h),h.some(b=>!b.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:h},200):e.json({ok:!0,operationId:f.operationId,ids:h.map(b=>({recipient:b.recipient,messageId:b.messageId,state:"provider_accepted"}))})}c(Kn,"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()}`)}c(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":Jn[n.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${o}`}},403)}c(Sr,"refuseMimeFromMismatch");async function Mr(e,t,r){let{projectId:n,operationKey:o,from:i,recipients:s,raw:a,transport:l}=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:l},t.remainingMs(z))}catch(m){let p=m instanceof Error&&m.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:p?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:p?"idempotency key has different content":"email admission unavailable"}},p?409:503)}let u=d.recipients.filter(m=>m.state!=="reserved").map(m=>({recipient:m.recipient,ok:m.state==="provider_accepted",state:m.state,messageId:m.providerReference??void 0,error:m.state==="provider_accepted"?void 0:{code:m.errorCode??(m.state==="outcome_unknown"||m.state==="attempt_started"?"OUTCOME_UNKNOWN":m.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:m.state==="outcome_unknown"||m.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":m.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(d.replay){for(let m of d.recipients.filter(p=>p.state==="reserved"))u.push({recipient:m.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return lt(e,d.operationId,u)}return{admission:d,deliveries:u}}c(Mr,"admitDirectSend");async function ct(e,t,r,n){try{let o=await P(e,t,r,"cancelled",{},n);return r.every(i=>o.recipients.some(s=>s.recipient===i&&s.state==="cancelled"))}catch{return!1}}c(ct,"cancelUnstartedRecipients");function lt(e,t,r){return r.length===0?e.json({ok:!1,operationId:t,error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved"}},200):r.some(n=>!n.ok)?e.json({ok:!1,operationId:t,deliveries:r},200):e.json({ok:!0,operationId:t,ids:r.map(n=>({recipient:n.recipient,messageId:n.messageId??"",state:n.state}))},200)}c(lt,"emailActionResponse");function 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()}`)}}c(Nr,"logSend");function Qn(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}c(Qn,"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}]`}}c(oe,"describeUntrusted");function Zn(e){return{routeId:e.routeId,routeGeneration:e.routeGeneration,connectionId:e.connectionId,addressing:e.addressing,domain:e.domain,projectSlug:e.slug}}c(Zn,"receiptRouteFence");var D=10*1024*1024,se=1024,ht=128*1024,eo=1e3,Tr=100,Cr=320,xr=32,Le=1024,Or=5*1024*1024,Pr=8*1024*1024,to=15e3,Ce=class extends Error{constructor(r){super(`inbound message exceeds ${D} bytes (got ${r})`);this.size=r;this.name="InboundTooLargeError"}size;static{c(this,"InboundTooLargeError")}},je=class extends Error{static{c(this,"InboundTooManyHeadersError")}constructor(){super(`inbound message carries more than ${se} headers`),this.name="InboundTooManyHeadersError"}},$e=class extends Error{static{c(this,"InboundHeadersTooLargeError")}constructor(){super(`inbound headers exceed ${ht} bytes`),this.name="InboundHeadersTooLargeError"}};function pt(e){return typeof e=="string"&&e.length<=Cr&&(0,Lr.validate)(e)}c(pt,"isValidEmailAddress");function $(e){return oe(e,Cr)}c($,"logAddress");function ro(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}c(ro,"forwardHeadersWithinBounds");function no(e,t){if(!/^[\x21-\x7e]+$/.test(e))return!1;let r=e.toLowerCase(),n=r.indexOf("@");return n<=0?!1:r.slice(n+1)!==t.domain||t.customDomain?!0:r.slice(0,n).split("+")[0]===t.slug}c(no,"isPermittedReplySender");async function jr(e,t,r,n){let o=re(t)??"void email",i=String(e.to??"").toLowerCase(),s=i.split("@")[0]??"",a=s.indexOf("+"),l=a===-1?s:s.slice(0,a),d=i.indexOf("@"),u=d===-1?"":i.slice(d+1);if(!l){e.setReject(`${o}: missing project slug in recipient`);return}if(n.addressing!=="custom"&&kt(l)){e.setReject(`${o}: "${I(l,64)}" is a reserved platform address`);return}if(!n.projectId||!n.workerName||!n.deploymentId||n.domain?.toLowerCase()!==u||n.addressing==="shared"&&n.slug.toLowerCase()!==l){e.setReject(`${o}: authoritative route mismatch`);return}let m=n.workerName,p=n.projectId,f;try{f=n.limits?t.DISPATCH.get(m,{},{limits:n.limits}):t.DISPATCH.get(m)}catch(w){throw console.error(`[email-router] DISPATCH.get(${I(m,320)}) failed:`,w),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 h;try{h=await io(e),n.addressing==="custom"&&(h.viaDomain=u)}catch(w){if(w instanceof Ce){e.setReject(`${o}: message too large (max ${D} bytes)`);return}if(w instanceof je){e.setReject(`${o}: too many headers (max ${se})`);return}if(w instanceof $e){e.setReject(`${o}: headers too large (max ${ht} bytes)`);return}console.error(`[email-router] failed to read message body for ${I(l,64)}:`,w),e.setReject(`${o}: could not read inbound message body`);return}let y=crypto.randomUUID(),E={projectId:p,receiptId:y,transport:"native"},R;try{await G(t,y,p,"received",Zn(n))}catch{throw new Error("email admission temporarily unavailable")}try{R=(await qe(f,t,{projectId:p,deploymentId:n.deploymentId,envelope:h,receiptId:y})).actions}catch(w){await G(t,y,p,"handler_failed").catch(()=>{});let A=w instanceof Error?w.message.slice(0,320):oe(w,320);throw console.error(`[email-router] dispatch to ${I(m,320)} failed:`,A),new Error("email handler execution unresolved")}try{await G(t,y,p,"handler_completed")}catch{console.error("[email-router] handler completed but receipt status could not be saved");return}try{await Ur(t,e,R,E,{customDomain:n.addressing==="custom",slug:n.slug.toLowerCase(),domain:u})}catch{console.error("[email-router] action execution unresolved",y);return}r.waitUntil(gt(t,p,e,R))}c(jr,"routeInbound");async function $r(e,t,r){let{stub:n,projectId:o,domain:i,envelope:s,authoritative:a,receiptId:l}=r;if(a.projectId!==o||!a.workerName||!a.slug||a.domain?.toLowerCase()!==i)return{reject:!0};let d=a.slug,u=a.workerName,m=oo(s),p={projectId:o,receiptId:l,transport:"relay"},f;try{f=(await qe(n,e,{projectId:o,deploymentId:a.deploymentId,envelope:s,receiptId:l})).actions}catch(h){await G(e,l,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,l,o,"handler_completed")}catch{return console.error("[email-relay] handler completed but receipt status could not be saved"),{reject:!1}}try{await Ur(e,m.message,f,p,{customDomain:a.addressing==="custom",slug:d.toLowerCase(),domain:i})}catch{return console.error("[email-relay] action execution unresolved",l),{reject:!1}}return t.waitUntil(gt(e,o,m.message,f)),{reject:m.rejectedReason()!==null}}c($r,"routeRelayed");function oo(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:c(()=>t,"rejectedReason")}}c(oo,"createRelayedMessage");async function so(e,t,r,n,o){let i=r.slice(r.indexOf("@")+1).toLowerCase();if(i===re(e)){let l=e.SEND_EMAIL;if(!l||typeof l.send!="function")throw new Error("shared email binding is unavailable");return async d=>(await l.send(new Dr(r,d,ne(n))))?.messageId}let s=await Ee(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(l,d=3e4)=>{let u;try{u=await ut({accountId:s.accountId,bearer:ye(s),from:r,recipients:[l],mimeMessage:a},d)}catch{throw new Error("email sending request failed")}if(!u.ok)throw u.status>=500||u.status===408?new Error("email sending API outcome unknown"):new U(`email sending API returned ${u.status}`);let m=u.data;if(typeof m!="object"||m===null||!("success"in m))throw new Error("email sending API response invalid");if(m.success===!1)throw new U("email sending API refused the message");if(m.success!==!0)throw new Error("email sending API response invalid");let p=ft(m.result);if(!p)throw new Error("email sending API response invalid");let f=mt(p,l);if(f==="permanent_bounce")throw new U("recipient permanently bounced");if(f==="suppressed")throw new U("recipient is on the suppression list");if(f==="outcome_unknown")throw new Error("email sending API did not classify the recipient");return p.messageId}}c(so,"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)}}c(gt,"logRecv");async function io(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 ao(e.raw),i=Object.fromEntries(t);return{from:String(e.from??""),to:String(e.to??""),headers:i,raw:o,rawSize:e.rawSize??o.byteLength}}c(io,"buildEnvelope");async function ao(e){let t=e.getReader(),r=[],n=0,o=Date.now()+to;try{for(;;){let a=o-Date.now();if(a<=0)throw new Error("inbound message stream timed out");let l,{value:d,done:u}=await Promise.race([t.read(),new Promise((m,p)=>{l=setTimeout(()=>p(new Error("inbound message stream timed out")),a)})]).finally(()=>{l!==void 0&&clearTimeout(l)});if(u)break;if(n+=d.byteLength,n>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}c(ao,"readStreamToBytes");var U=class extends Error{static{c(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,eo):"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(!ro(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(!no(o.from,t))return console.error(`[email-router] reply dropped: sender not owned by project "${I(t.slug,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>Pr)return console.error(`[email-router] reply dropped: cumulative reply bytes ${n+i} exceed this delivery's budget of ${Pr} (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}c(co,"validateActions");async function Ur(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 lo(e,t,i,n)}c(Ur,"enactActions");async function lo(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(),l=s.type==="reply"?s.from:t.to,d=await ge(s.type,l,[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:l,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 so(e,n.projectId,s.from,s.raw,u.accountId)}catch{await P(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 kr(e,u.operationId,a);console.error(f?"[email-router] action batch deadline elapsed; reservation cancelled":"[email-router] action batch deadline elapsed; cancellation unresolved");break}try{await Q(e,u.operationId,[a])}catch{let f=await kr(e,u.operationId,a);console.error(f?"[email-router] attempt did not start; reservation cancelled":"[email-router] could not confirm attempt status");continue}try{let f;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 P(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 P(e,u.operationId,[a],h?"failed":"outcome_unknown",{errorCode:h?"UPSTREAM_ERROR":"OUTCOME_UNKNOWN"})}catch{}console.error(h?"[email-router] action provider refused":"[email-router] action provider outcome unknown")}}}c(lo,"enactSanitized");async function kr(e,t,r){try{return(await P(e,t,[r],"cancelled")).recipients.some(o=>o.recipient===r&&o.state==="cancelled")}catch{return!1}}c(kr,"cancelUnstartedAction");var Fe=new TextEncoder,Rt=new TextDecoder,yt=128*1024,wt=320,uo=2,Gr="/email/destinations/confirm",fo=4*1024,Fr=32*1024,Hr=5e3,Et=0,L=class extends Error{constructor(r,n){super(r);this.status=n;this.name="MimeHeaderError"}status;static{c(this,"MimeHeaderError")}};function At(e){return e.PLATFORM_TRAFFIC_STATE==="staging"||e.PLATFORM_TRAFFIC_STATE==="sandbox-drain"}c(At,"isTrafficPaused");async function Br(e){if(Et>=uo)throw new Error("email gateway busy");Et++;try{return await e()}finally{Et--}}c(Br,"withDeliverySlot");async function zr(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("=","")}c(zr,"sign");async function Vr(e,t){let r=Date.now()+5e3,n=new AbortController,o=c(async E=>{let R=r-Date.now();if(R<=0)throw n.abort(),new Error("ingress resolution timeout");let w;try{return await Promise.race([E(),new Promise((A,b)=>{w=setTimeout(()=>{n.abort(),b(new Error("ingress resolution timeout"))},R)})])}finally{w!==void 0&&clearTimeout(w)}},"beforeDeadline"),i=await zr(`email-ingress-v1
|
|
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 l=a.headers.get("content-length");if(l!==null&&(!/^\d+$/.test(l)||Number(l)>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(l!==null&&m!==Number(l))return null;let p=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,m)));return bn(p)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}c(Ee,"leaseEmailDomainCredential");function bn(e){if(typeof e!="object"||e===null)return null;let t=e.kind,r=e.accountId;if(typeof r!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(r))return null;if(t==="api_token"){let n=e.token;return typeof n=="string"&&n.length>0?{kind:t,token:n,accountId:r}:null}return null}c(bn,"parseLease");g();var be=class extends Error{static{c(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 be;let i=r(),s;try{return await Promise.race([i,new Promise((a,l)=>{s=setTimeout(()=>l(new be),o)})])}finally{s!==void 0&&clearTimeout(s)}}}}c(we,"createEmailProviderDeadline");g();import{EmailMessage as Cn}from"cloudflare:email";g();g();g();g();g();var zt=Symbol();g();g();g();var Vt=c((e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,r=>r.toLowerCase())}}).formData(),"bufferToFormData");var wn=1e4,Re=c(e=>"headers"in e,"isRawRequest"),Xt=c(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"?Rn(e,{all:r,dot:n}):{}},"parseBody");async function Rn(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):{}}c(Rn,"parseFormData");function qt(e,t){let r=Object.create(null),n={count:0};return e.forEach((o,i)=>{t.all||i.endsWith("[]")?An(r,i,o):r[i]=o}),t.dot&&Object.entries(r).forEach(([o,i])=>{o.includes(".")&&(_n(r,o,i,n),delete r[o])}),r}c(qt,"convertFormDataToBodyData");var An=c((e,t,r)=>{e[t]!==void 0?Array.isArray(e[t])?e[t].push(r):e[t]=[e[t],r]:t.endsWith("[]")?e[t]=[r]:e[t]=r},"handleParsingAllValues"),_n=c((e,t,r,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let 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++>=wn&&Wt(),o[s]=Object.create(null)),o=o[s])})},"handleParsingNestedValues"),Wt=c(()=>{throw new Error("Nesting limit exceeded")},"throwNestingLimitExceeded");g();var Xe=c(e=>{let t=e.split("/");return t[0]===""&&t.shift(),t},"splitPath"),Jt=c(e=>{let{groups:t,path:r}=In(e),n=Xe(r);return vn(n,t)},"splitRoutingPath"),In=c(e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,n)=>{let o=`@${n}`;return t.push([o,r]),o}),{groups:t,path:e}},"extractGroupsFromPath"),vn=c((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=c((e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let n=`${e}#${t}`;return Ae[n]||(r[2]?Ae[n]=t&&t[0]!==":"&&t[0]!=="*"?[n,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)]:Ae[n]=[e,r[1],!0]),Ae[n]}return null},"getPattern"),Kt=c((e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,r=>{try{return t(r)}catch{return r}})}},"tryDecode"),Sn=c(e=>Kt(e,decodeURI),"tryDecodeURI"),Je=c(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),l=t.slice(r,a);return Sn(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(o===63||o===35)break}return t.slice(r,n)},"getPath");var Qt=c(e=>{let t=Je(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},"getPathNoStrict"),C=c((e,t,...r)=>(r.length&&(t=C(t,...r)),`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`),"mergePath"),_e=c(e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],n="";return t.forEach(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=c(e=>e.indexOf("%")!==-1?Kt(e,Mn):e,"tryDecodeURIComponent"),We=c(e=>(e.indexOf("+")!==-1&&(e=e.replace(/\+/g," ")),Ie(e)),"_decodeURI"),Zt=c((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 l=e.charCodeAt(a+t.length+1);if(l===61){let d=a+t.length+2,u=e.indexOf("&",d);return We(e.slice(d,u===-1?void 0:u))}else if(l==38||isNaN(l))return"";a=e.indexOf(`&${t}`,a+1)}if(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),l=e.indexOf("=",s);l>a&&a!==-1&&(l=-1);let d=e.slice(s+1,l===-1?a===-1?void 0:a:l);if(o&&(d=We(d)),s=a,d==="")continue;let u;l===-1?u="":(u=e.slice(l+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=c((e,t)=>Zt(e,t,!0),"getQueryParams"),Mn=decodeURIComponent;var rr=class{static{c(this,"HonoRequest")}raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#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=c(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},Nn=c((e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r},"raw");var Ye=c(async(e,t,r,n,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(l=>Ye(l,t,!1,n,o))).then(()=>o[0]));return r?Nn(await s,i):s},"resolveCallback");var Tn="text/plain; charset=UTF-8",Ke=c((e,t)=>({"Content-Type":e,...t}),"setDefaultContentType"),ee=c((e,t)=>new Response(e,t),"createResponseInstance"),Qe=class{static{c(this,"Context")}#t;#e;env={};#r;finalized=!1;error;#s;#n;#o;#d;#c;#l;#a;#u;#f;constructor(e,t){this.#t=e,t&&(this.#n=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#f=t.path,this.#u=t.matchResult)}get req(){return this.#e??=new 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=c((...e)=>(this.#c??=t=>this.html(t),this.#c(...e)),"render");setLayout=c(e=>this.#d=e,"setLayout");getLayout=c(()=>this.#d,"getLayout");setRenderer=c(e=>{this.#c=e},"setRenderer");header=c((e,t,r)=>{this.finalized&&(this.#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=c(e=>{this.#s=e},"status");set=c((e,t)=>{this.#r??=new Map,this.#r.set(e,t)},"set");get=c(e=>this.#r?this.#r.get(e):void 0,"get");get var(){return this.#r?Object.fromEntries(this.#r):{}}#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=c((...e)=>this.#i(...e),"newResponse");body=c((e,t,r)=>this.#i(e,t,r),"body");text=c((e,t,r)=>!this.#a&&!this.#s&&!t&&!r&&!this.finalized?new Response(e):this.#i(e,t,Ke(Tn,r)),"text");json=c((e,t,r)=>this.#i(JSON.stringify(e),t,Ke("application/json",r)),"json");html=c((e,t,r)=>{let n=c(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=c((e,t)=>{let r=String(e);return this.header("Location",/[^\x00-\xFF]/.test(r)?encodeURI(r):r),this.newResponse(null,t??302)},"redirect");notFound=c(()=>(this.#l??=()=>ee(),this.#l(this)),"notFound")};g();g();g();var Ze=c((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 l,d=!1,u;if(e[a]?(u=e[a][0][0],n.req.routeIndex=a):u=a===e.length&&o||void 0,u)try{l=await u(n,()=>s(a+1))}catch(m){if(m instanceof Error&&t)n.error=m,l=await t(m,n),d=!0;else throw m}else n.finalized===!1&&r&&(l=await r(n));return l&&(n.finalized===!1||d)&&(n.res=l),n}},"compose");g();var 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{c(this,"UnsupportedPathError")}};g();var sr="__COMPOSED_HANDLER";var xn=c(e=>e.text("404 Not Found",404),"notFoundHandler"),ir=c((e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},"errorHandler"),ar=class cr{static{c(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(l=>{this.#s(a,this.#t,l)}),this}}),this.on=(o,i,...s)=>{for(let a of[i].flat()){this.#t=a;for(let l of[o].flat()){let d=l.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 cr({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=xn;errorHandler=ir;route(t,r){let n=this.basePath(t);return r.routes.map(o=>{let i;r.errorHandler===ir?i=o.handler:(i=c(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=c(t=>(this.errorHandler=t,this),"onError");notFound=c(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=c(l=>l,"replaceRequest"):o=n.replaceRequest));let s=i?l=>{let d=i(l);return Array.isArray(d)?d:[d]}:l=>{let d;try{d=l.executionCtx}catch{}return[l.env,d]};o||=(()=>{let l=C(this._basePath,t),d=l==="/"?0:l.length;return u=>{let m=new URL(u.url);return m.pathname=this.getPath(u).slice(d)||"/",new Request(m,u)}})();let a=c(async(l,d)=>{let u=await r(o(l.req.raw),...s(l));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 l=Ze(s[0],this.errorHandler,this.#r);return(async()=>{try{let d=await l(a);if(!d.finalized)throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return d.res}catch(d){return this.#n(d,a)}})()}fetch=c((t,...r)=>this.#o(t,r[1],r[0],t.method),"fetch");request=c((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=c(()=>{addEventListener("fetch",t=>{t.respondWith(this.#o(t.request,t,void 0,t.request.method))})},"fire")};g();g();var v=c(()=>Object.create(null),"createNullObject");g();var Me=[];function et(e,t){let r=this.buildAllMatchers(),n=c(((o,i)=>{let s=r[o]||r.ALL,a=s[2][i];if(a)return a;let l=i.match(s[0]);if(!l)return[[],Me];let d=l.indexOf("",1);return[s[1][d],l]}),"match");return this.match=n,n(e,t)}c(et,"match");g();var rt="[^/]+";var nt="(?:|/.*)",j=Symbol(),lr=new Set(".\\+*[^]$()");function On(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1?1:e===".*"||e==="(?:|/.*)"?t==="(?:|/.*)"?-1:1:t===".*"||t==="(?:|/.*)"?-1:e==="[^/]+"?1:t==="[^/]+"?-1:e.length===t.length?e<t?-1:1:t.length-e.length}c(On,"compareKey");var dr=class tt{static{c(this,"Node")}#t;#e;#r=v();insert(t,r,n,o,i){let s=this;for(let a=0,l=t.length;a<l;a++){let d=t[a],u=d.length===1?d==="*"?a===l-1?["","",".*"]:["","",rt]:null:d==="/*"?["","",nt]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),m;if(u){let p=u[1],f=u[2]||"[^/]+";if(p&&u[2]&&(f===".*"||(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))||f.length===1&&lr.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(On).map(r=>{let n=this.#r[r],o=n.buildRegExpStr();return o===""?"":(typeof n.#e=="number"?`(${r})@${n.#e}`:lr.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{c(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,l=>{let d=`@\\${s}`;return n[s]=[d,l],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 l=i.length-1;l>=0;l--)if(i[l].indexOf(a)!==-1){i[l]=i[l].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}`)}$`)}c(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]]}c(Ne,"findMiddleware");var Te=class{static{c(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 l in a.ALL)a[e][l]=[...a.ALL[l]],this.#s(e,l)}}t==="/*"&&(t="*");let i=e==="ALL"?Object.keys(n):[e];if(/\*$/.test(t)){let a=fr(t);for(let l of i)n[l][t]||(this.#s(l,t),n[l][t]=Ne(n[l],t)||Ne(n.ALL,t)||[]);for(let l of[n,o])for(let d of i)for(let u in l[d])a.test(u)&&l[d][u].push([r,t]);return}let s=_e(t)||[t];for(let a of s)for(let l of i)o[l][a]||(this.#s(l,a),o[l][a]=Ne(n[l],a)||Ne(n.ALL,a)||[]),o[l][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,l]=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,[E],R)=>(y[E]=l[p[1][R][1]],y),v())])}return[s,a.map(d=>i[d]),o]}};g();g();g();var mr=class{static{c(this,"SmartRouter")}name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw new Error(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 l=0,d=n.length;l<d;l++)a.add(...n[l]);s=a.match(e,t)}catch(l){if(l instanceof Se)continue;throw l}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(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(),kn=0,pr=class gr{static{c(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 l of i){let d=i[++a],u=Yt(l,d)||(d===void 0&&l&&l.indexOf("*")===l.length-1?l:null),m=Array.isArray(u),p=m?u[0]:u||l,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:++kn}})}#o(t,r,n,o,i){for(let s=0,a=r.#t.length;s<a;s++){let l=r.#t[s],d=l[n]||l.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,l=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 E=o[h],R=E.#e[u];R&&(R.#n=E.#n,m?(R.#e["*"]&&this.#o(n,R.#e["*"],t,E.#n),this.#o(n,R,t,E.#n)):p.push(R));for(let w of E.#r){let A=w.#s,b=E.#n===st?{}:{...E.#n};if(typeof A=="string"){(A==="*"||u.startsWith(A.slice(0,-1)))&&(this.#o(n,w,t,E.#n),A==="*"&&(w.#n=b,p.push(w)));continue}let[,_,M]=A;if(!(!u&&M===!0)){if(M!==!0){if(!l){l=[];let x=r[0]==="/"?1:0;for(let P=0;P<a;P++)l[P]=x,x+=i[P].length+1}let O=r.slice(l[d]),T=M.exec(O);if(T){b[_]=T[0],this.#o(n,w,t,E.#n,b),T[0].length===O.length&&w.#e["*"]&&this.#o(n,w.#e["*"],t,E.#n,b);for(let x in w.#e){w.#n=b;let P=T[0].match(/\//g)?.length??0;(s[P]||=[]).push(w);break}continue}}(M===!0||M.test(u))&&(b[_]=u,m?(this.#o(n,w,t,b,E.#n),w.#e["*"]&&this.#o(n,w.#e["*"],t,b,E.#n)):(w.#n=b,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{c(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{c(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}c(te,"asString");var jn=new at,$n=5e4,z=5e3,xe=5*1024*1024,Un=16*1024,Fn=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 Hn(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&&!Fn.has(a)}if(r&&(t+=i-n+2,t>Un))return!1;n=o+1}return!0}c(Hn,"customMimeHeaderBytesWithinLimit");var yr=50,Er=320,br=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}c(re,"readSenderDomain");var Bn=/[.*+?^${}()|[\]\\]/g;function Gn(e){return e.replace(Bn,"\\$&")}c(Gn,"escapeRegExp");var wr=new Map;function zn(e){let t=wr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${Gn(e)}$`);return wr.set(e,r),r}c(zn,"strictFromRe");var Vn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function I(e,t=200){return e.slice(0,t).replace(Vn," ")}c(I,"sanitizeForLog");var qn=128;function ne(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}c(ne,"bytesToStream");var Rr=10,Oe=13,_r=32,Ir=9,Wn=58,ke=[102,114,111,109];function Xn(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]===Wn?n+1:-1}c(Xn,"fromValueStart");var Jn={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),l=0;for(;l<t;){let m=e.indexOf(Rr,l),f=m===-1?t:m;if(f>l&&e[f-1]===Oe&&f--,f===l)break;if(a!==-1&&a<l&&(a=e.indexOf(Oe,l)),a!==-1&&a<f)return{ok:!1,reason:"malformed"};if(e[l]===_r||e[l]===Ir)s&&(o=f,i=!0);else{let h=Xn(e,l,f);s=h!==-1,s&&(r++,n=h,o=f,i=!1)}l=m===-1?t:m+1}if(r===0)return{ok:!1,reason:"missing"};if(r>1)return{ok:!1,reason:"multiple"};let d=e.subarray(n,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=Yn(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}c(dt,"readMimeFromAddrSpec");function Yn(e){let t=!1,r=!1,n=-1,o=-1,i=-1;for(let a=0;a<e.length;a++){let l=e[a];if(t){r?r=!1:l==="\\"?r=!0:l==='"'&&(t=!1);continue}switch(l){case'"':if(n!==-1)return null;t=!0;break;case"<":if(n!==-1)return null;n=a;break;case">":if(n===-1||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}c(Yn,"singleMailboxAddrSpec");jn.post("/send",async e=>{let t=we($n),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,qn),l=te(n.idempotencyKey);if(l!==null&&(l.length===0||l.length>128||!/^[\x20-\x7e]+$/.test(l)))return e.json({ok:!1,error:{code:"INVALID_TO",message:"invalid idempotency key"}},400);let d=l??(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>br)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${br} 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>Er)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${Er} 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=Qn(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(!Hn(h))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let y=o.indexOf("@"),E=y===-1?"":o.slice(y+1).toLowerCase();if(E!==""&&E!==m)return Kn(e,r,o,E,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(!zn(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 ct(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 ct(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 Cn(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=c(async m=>{let p=n-Date.now();if(p<=0)throw r.abort(),new Error("email sending request timed out");let f=m(),h;try{return await Promise.race([f,new Promise((y,E)=>{h=setTimeout(()=>{r.abort(),E(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 l=s.body?.getReader();if(!l)throw new Error("email sending API response unreadable");let d=new Uint8Array(Ar),u=0;try{for(;;){let m=await i(()=>l.read());if(m.done)break;if(u+m.value.byteLength>d.byteLength)throw new Error("email sending API response too large");d.set(m.value,u),u+=m.value.byteLength}if(a!==null&&u!==Number(a))throw new Error("email sending API response length mismatch");return{ok:!0,data:JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(d.subarray(0,u)))}}finally{l.cancel().catch(()=>{});try{l.releaseLock()}catch{}}}c(ut,"requestSendRaw");function Pe(e){if(!Array.isArray(e))return null;let t=new Set;for(let r of e){if(typeof r!="string")return null;t.add(r.toLowerCase())}return t}c(Pe,"readSendRawAddressList");function ft(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=Pe(t.delivered),n=Pe(t.permanent_bounces),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}}c(ft,"parseSendRawResult");function mt(e,t){let r=t.toLowerCase(),n=[e.delivered.has(r),e.queued.has(r),e.permanentBounces.has(r),e.suppressedRecipients.has(r)];return n.filter(Boolean).length!==1?"outcome_unknown":n[0]||n[1]?"provider_accepted":n[2]?"permanent_bounce":"suppressed"}c(mt,"classifySendRawRecipient");async function Kn(e,t,r,n,o,i,s,a,l,d){if(!/^[\x21-\x7e]+$/.test(r))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let u=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:l,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(b=>b.state==="reserved").map(b=>b.recipient),i.length===0)return lt(e,f.operationId,h);let y=await Ee(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 b=await ct(e.env,f.operationId,i,d.remainingMs());for(let _ of i)h.push({recipient:_,ok:!1,state:b?"cancelled":"outcome_unknown",error:b?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return lt(e,f.operationId,h)}let E=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{E={code:"UPSTREAM_ERROR",message:"email sending request failed"},R="outcome_unknown"}if(A)if(!A.ok)E={code:A.status===429?"QUOTA_EXCEEDED":"UPSTREAM_ERROR",message:`email sending API returned ${A.status}`},R=A.status>=500||A.status===408?"outcome_unknown":"failed";else{let b=A.data,_=typeof b=="object"&&b!==null?b.success:void 0;_===!1?E={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:_!==!0?(E={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"):(w=ft(b.result),w||(E={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},R="outcome_unknown"))}for(let b of i){if(E){h.push({recipient:b,ok:!1,state:R,error:E});continue}let _=mt(w,b);_==="permanent_bounce"?h.push({recipient:b,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${b}' permanently bounced`}}):_==="suppressed"?h.push({recipient:b,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${b}' is on the suppression list`}}):_==="outcome_unknown"?h.push({recipient:b,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):h.push({recipient:b,ok:!0,state:"provider_accepted",messageId:w.messageId})}for(let b of h.filter(_=>f.recipients.some(M=>M.recipient===_.recipient&&M.state==="reserved")))try{await k(e.env,f.operationId,[b.recipient],b.ok?"provider_accepted":b.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:b.messageId,errorCode:b.ok?void 0:b.state==="outcome_unknown"?"OUTCOME_UNKNOWN":E?.code??b.error?.code},d.remainingMs()),b.state=b.ok?"provider_accepted":b.state==="outcome_unknown"?"outcome_unknown":"failed",b.state==="outcome_unknown"&&!b.ok&&(b.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{b.ok=!1,b.state="outcome_unknown",b.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return Nr(t,a,h),h.some(b=>!b.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:h},200):e.json({ok:!0,operationId:f.operationId,ids:h.map(b=>({recipient:b.recipient,messageId:b.messageId,state:"provider_accepted"}))})}c(Kn,"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()}`)}c(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":Jn[n.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${o}`}},403)}c(Sr,"refuseMimeFromMismatch");async function Mr(e,t,r){let{projectId:n,operationKey:o,from:i,recipients:s,raw:a,transport:l}=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:l},t.remainingMs(z))}catch(m){let p=m instanceof Error&&m.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:p?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:p?"idempotency key has different content":"email admission unavailable"}},p?409:503)}let u=d.recipients.filter(m=>m.state!=="reserved").map(m=>({recipient:m.recipient,ok:m.state==="provider_accepted",state:m.state,messageId:m.providerReference??void 0,error:m.state==="provider_accepted"?void 0:{code:m.errorCode??(m.state==="outcome_unknown"||m.state==="attempt_started"?"OUTCOME_UNKNOWN":m.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:m.state==="outcome_unknown"||m.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":m.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(d.replay){for(let m of d.recipients.filter(p=>p.state==="reserved"))u.push({recipient:m.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return lt(e,d.operationId,u)}return{admission:d,deliveries:u}}c(Mr,"admitDirectSend");async function ct(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}}c(ct,"cancelUnstartedRecipients");function lt(e,t,r){return r.length===0?e.json({ok:!1,operationId:t,error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved"}},200):r.some(n=>!n.ok)?e.json({ok:!1,operationId:t,deliveries:r},200):e.json({ok:!0,operationId:t,ids:r.map(n=>({recipient:n.recipient,messageId:n.messageId??"",state:n.state}))},200)}c(lt,"emailActionResponse");function 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()}`)}}c(Nr,"logSend");function Qn(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}c(Qn,"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}]`}}c(oe,"describeUntrusted");function Zn(e){return{routeId:e.routeId,routeGeneration:e.routeGeneration,connectionId:e.connectionId,addressing:e.addressing,domain:e.domain,projectSlug:e.slug}}c(Zn,"receiptRouteFence");var D=10*1024*1024,se=1024,ht=128*1024,eo=1e3,Tr=100,Cr=320,xr=32,Le=1024,Or=5*1024*1024,kr=8*1024*1024,to=15e3,Ce=class extends Error{constructor(r){super(`inbound message exceeds ${D} bytes (got ${r})`);this.size=r;this.name="InboundTooLargeError"}size;static{c(this,"InboundTooLargeError")}},je=class extends Error{static{c(this,"InboundTooManyHeadersError")}constructor(){super(`inbound message carries more than ${se} headers`),this.name="InboundTooManyHeadersError"}},$e=class extends Error{static{c(this,"InboundHeadersTooLargeError")}constructor(){super(`inbound headers exceed ${ht} bytes`),this.name="InboundHeadersTooLargeError"}};function pt(e){return typeof e=="string"&&e.length<=Cr&&(0,Lr.validate)(e)}c(pt,"isValidEmailAddress");function $(e){return oe(e,Cr)}c($,"logAddress");function ro(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}c(ro,"forwardHeadersWithinBounds");function no(e,t){if(!/^[\x21-\x7e]+$/.test(e))return!1;let r=e.toLowerCase(),n=r.indexOf("@");return n<=0?!1:r.slice(n+1)!==t.domain||t.customDomain?!0:r.slice(0,n).split("+")[0]===t.slug}c(no,"isPermittedReplySender");async function jr(e,t,r,n){let o=re(t)??"void email",i=String(e.to??"").toLowerCase(),s=i.split("@")[0]??"",a=s.indexOf("+"),l=a===-1?s:s.slice(0,a),d=i.indexOf("@"),u=d===-1?"":i.slice(d+1);if(!l){e.setReject(`${o}: missing project slug in recipient`);return}if(n.addressing!=="custom"&&Pt(l)){e.setReject(`${o}: "${I(l,64)}" is a reserved platform address`);return}if(!n.projectId||!n.workerName||!n.deploymentId||n.domain?.toLowerCase()!==u||n.addressing==="shared"&&n.slug.toLowerCase()!==l){e.setReject(`${o}: authoritative route mismatch`);return}let m=n.workerName,p=n.projectId,f;try{f=n.limits?t.DISPATCH.get(m,{},{limits:n.limits}):t.DISPATCH.get(m)}catch(w){throw console.error(`[email-router] DISPATCH.get(${I(m,320)}) failed:`,w),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 h;try{h=await io(e),n.addressing==="custom"&&(h.viaDomain=u)}catch(w){if(w instanceof Ce){e.setReject(`${o}: message too large (max ${D} bytes)`);return}if(w instanceof je){e.setReject(`${o}: too many headers (max ${se})`);return}if(w instanceof $e){e.setReject(`${o}: headers too large (max ${ht} bytes)`);return}console.error(`[email-router] failed to read message body for ${I(l,64)}:`,w),e.setReject(`${o}: could not read inbound message body`);return}let y=crypto.randomUUID(),E={projectId:p,receiptId:y,transport:"native"},R;try{await G(t,y,p,"received",Zn(n))}catch{throw new Error("email admission temporarily unavailable")}try{R=(await qe(f,t,{projectId:p,deploymentId:n.deploymentId,envelope:h,receiptId:y})).actions}catch(w){await G(t,y,p,"handler_failed").catch(()=>{});let A=w instanceof Error?w.message.slice(0,320):oe(w,320);throw console.error(`[email-router] dispatch to ${I(m,320)} failed:`,A),new Error("email handler execution unresolved")}try{await G(t,y,p,"handler_completed")}catch{console.error("[email-router] handler completed but receipt status could not be saved");return}try{await Ur(t,e,R,E,{customDomain:n.addressing==="custom",slug:n.slug.toLowerCase(),domain:u})}catch{console.error("[email-router] action execution unresolved",y);return}r.waitUntil(gt(t,p,e,R))}c(jr,"routeInbound");async function $r(e,t,r){let{stub:n,projectId:o,domain:i,envelope:s,authoritative:a,receiptId:l}=r;if(a.projectId!==o||!a.workerName||!a.slug||a.domain?.toLowerCase()!==i)return{reject:!0};let d=a.slug,u=a.workerName,m=oo(s),p={projectId:o,receiptId:l,transport:"relay"},f;try{f=(await qe(n,e,{projectId:o,deploymentId:a.deploymentId,envelope:s,receiptId:l})).actions}catch(h){await G(e,l,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,l,o,"handler_completed")}catch{return console.error("[email-relay] handler completed but receipt status could not be saved"),{reject:!1}}try{await Ur(e,m.message,f,p,{customDomain:a.addressing==="custom",slug:d.toLowerCase(),domain:i})}catch{return console.error("[email-relay] action execution unresolved",l),{reject:!1}}return t.waitUntil(gt(e,o,m.message,f)),{reject:m.rejectedReason()!==null}}c($r,"routeRelayed");function oo(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:c(()=>t,"rejectedReason")}}c(oo,"createRelayedMessage");async function so(e,t,r,n,o){let i=r.slice(r.indexOf("@")+1).toLowerCase();if(i===re(e)){let l=e.SEND_EMAIL;if(!l||typeof l.send!="function")throw new Error("shared email binding is unavailable");return async d=>(await l.send(new Dr(r,d,ne(n))))?.messageId}let s=await Ee(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(l,d=3e4)=>{let u;try{u=await ut({accountId:s.accountId,bearer:ye(s),from:r,recipients:[l],mimeMessage:a},d)}catch{throw new Error("email sending request failed")}if(!u.ok)throw u.status>=500||u.status===408?new Error("email sending API outcome unknown"):new U(`email sending API returned ${u.status}`);let m=u.data;if(typeof m!="object"||m===null||!("success"in m))throw new Error("email sending API response invalid");if(m.success===!1)throw new U("email sending API refused the message");if(m.success!==!0)throw new Error("email sending API response invalid");let p=ft(m.result);if(!p)throw new Error("email sending API response invalid");let f=mt(p,l);if(f==="permanent_bounce")throw new U("recipient permanently bounced");if(f==="suppressed")throw new U("recipient is on the suppression list");if(f==="outcome_unknown")throw new Error("email sending API did not classify the recipient");return p.messageId}}c(so,"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)}}c(gt,"logRecv");async function io(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 ao(e.raw),i=Object.fromEntries(t);return{from:String(e.from??""),to:String(e.to??""),headers:i,raw:o,rawSize:e.rawSize??o.byteLength}}c(io,"buildEnvelope");async function ao(e){let t=e.getReader(),r=[],n=0,o=Date.now()+to;try{for(;;){let a=o-Date.now();if(a<=0)throw new Error("inbound message stream timed out");let l,{value:d,done:u}=await Promise.race([t.read(),new Promise((m,p)=>{l=setTimeout(()=>p(new Error("inbound message stream timed out")),a)})]).finally(()=>{l!==void 0&&clearTimeout(l)});if(u)break;if(n+=d.byteLength,n>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}c(ao,"readStreamToBytes");var U=class extends Error{static{c(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,eo):"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(!ro(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(!no(o.from,t))return console.error(`[email-router] reply dropped: sender not owned by project "${I(t.slug,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}c(co,"validateActions");async function Ur(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 lo(e,t,i,n)}c(Ur,"enactActions");async function lo(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(),l=s.type==="reply"?s.from:t.to,d=await ge(s.type,l,[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:l,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 so(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")}}}c(lo,"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}}c(Pr,"cancelUnstartedAction");var Fe=new TextEncoder,Rt=new TextDecoder,yt=128*1024,wt=320,uo=2,Gr="/email/destinations/confirm",fo=4*1024,Fr=32*1024,Hr=5e3,Et=0,L=class extends Error{constructor(r,n){super(r);this.status=n;this.name="MimeHeaderError"}status;static{c(this,"MimeHeaderError")}};function At(e){return e.PLATFORM_TRAFFIC_STATE==="staging"||e.PLATFORM_TRAFFIC_STATE==="sandbox-drain"}c(At,"isTrafficPaused");async function Br(e){if(Et>=uo)throw new Error("email gateway busy");Et++;try{return await e()}finally{Et--}}c(Br,"withDeliverySlot");async function zr(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("=","")}c(zr,"sign");async function Vr(e,t){let r=Date.now()+5e3,n=new AbortController,o=c(async E=>{let R=r-Date.now();if(R<=0)throw n.abort(),new Error("ingress resolution timeout");let w;try{return await Promise.race([E(),new Promise((A,b)=>{w=setTimeout(()=>{n.abort(),b(new Error("ingress resolution timeout"))},R)})])}finally{w!==void 0&&clearTimeout(w)}},"beforeDeadline"),i=await zr(`email-ingress-v1
|
|
4
4
|
${t.accountId}
|
|
5
5
|
${t.zoneId}
|
|
6
6
|
${t.ingressName}
|
|
7
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 a=Number(s.headers.get("content-length"));if(Number.isFinite(a)&&a>4096)throw s.body?.cancel().catch(()=>{}),new Error("invalid email routing response");let l=s.body?.getReader();if(!l)throw new Error("invalid email routing response");let d=[],u=0;try{for(;;){let E=await o(()=>l.read());if(E.done)break;if(u+=E.value.byteLength,u>4096)throw new Error("invalid email routing response");d.push(E.value)}}finally{l.cancel().catch(()=>{});try{l.releaseLock()}catch{}}let m=new Uint8Array(u),p=0;for(let E of d)m.set(E,p),p+=E.byteLength;let f=Rt.decode(m),h;try{h=JSON.parse(f)}catch{throw new Error("invalid email routing response")}if(!h||typeof h!="object")throw new Error("invalid email routing response");let y=h;if(typeof y.routeId!="string"||!Number.isSafeInteger(y.routeGeneration)||y.routeGeneration<1||typeof y.projectId!="string"||typeof y.connectionId!="string"||typeof y.workerName!="string"||typeof y.deploymentId!="string"||typeof y.slug!="string"||typeof y.domain!="string"||y.addressing!=="shared"&&y.addressing!=="custom")throw new Error("invalid email routing response");return y}c(Vr,"resolveIngress");async function mo(e,t){if(!e||!Number.isSafeInteger(t)||t<0||t>D)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 a,l=await Promise.race([r.read(),new Promise((d,u)=>{a=setTimeout(()=>u(new Error("MIME timeout")),s)})]).finally(()=>{a!==void 0&&clearTimeout(a)});if(l.done)break;if(o+=l.value.byteLength,o>t||o>D)throw new Error("MIME too large");n.set(l.value,o-l.value.byteLength)}if(o!==t)throw new Error("truncated MIME");return n}catch(s){throw r.cancel().catch(()=>{}),s}finally{try{r.releaseLock()}catch{}}}c(mo,"readMime");function po(e){let t=-1;for(let s=0;s<e.length-3&&s<yt+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 L("invalid MIME headers",e.byteLength>yt?413:400);if(t>yt)throw new L("MIME headers too large",413);let r=Rt.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 L("too many MIME headers",413);if(/^[ \t]/.test(s)){if(!o)throw new L("invalid MIME header fold",400);n[o]+=` ${s.trim()}`;continue}let a=s.indexOf(":");if(a<=0)throw new L("invalid MIME header",400);let l=s.slice(0,a).toLowerCase();if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(l))throw new L("invalid MIME header name",400);n[l]=n[l]?`${n[l]}, ${s.slice(a+1).trim()}`:s.slice(a+1).trim(),o=l}return n}c(po,"parseHeaders");async function go(e,t,r){if(At(t))return new Response(null,{status:503});if(e.headers.get("content-encoding"))return new Response(null,{status:415});let n=e.headers.get("x-void-email-account")??"",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")??"",a=e.headers.get("x-void-email-from")??"",l=e.headers.get("x-void-email-to")??"",d=e.headers.get("authorization")??"";if([n,o,i,a,l,d].some(y=>!y||y.length>wt)||!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 m=Number(u);if(!Number.isSafeInteger(m)||m<0)return new Response(null,{status:411});if(m>D)return new Response(null,{status:413});let p;try{p=await Vr(t,{accountId:n,zoneId:o,ingressName:i,from:a,to:l,secret:d.slice(7)})}catch{return new Response(null,{status:503})}if(!p)return new Response(null,{status:403});let f;try{f=await mo(e.body,m)}catch(y){return console.error("[email-gateway] ingress failed:",y instanceof Error?y.message.slice(0,200):"unknown"),new Response(null,{status:502})}let h;try{h=po(f)}catch(y){if(y instanceof L)return new Response(null,{status:y.status});throw y}try{let y=l.slice(l.lastIndexOf("@")+1).toLowerCase();if(y!==p.domain)return new Response(null,{status:403});let E={from:a,to:l,raw:f,rawSize:f.byteLength,headers:h,...p.addressing==="custom"?{viaDomain:y}:{}},R;try{R=p.limits?t.DISPATCH.get(p.workerName,{},{limits:p.limits}):t.DISPATCH.get(p.workerName)}catch(O){return console.error("[email-gateway] tenant dispatch stub unavailable:",O),new Response(null,{status:503})}let w=await bt(Fe.encode(JSON.stringify([p.connectionId,s]))),A=await bt(Fe.encode(JSON.stringify([a,l,await bt(f)]))),b={receiptId:w,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 Ot(t,b)}catch(O){if(O instanceof Error&&O.message==="IDEMPOTENCY_CONFLICT")return new Response(null,{status:409});throw O}if(_.state==="completed"&&typeof _.reject=="boolean")return new Response(null,{status:_.reject?403:204,headers:{"x-void-email-receipt":w}});if(_.state!=="claimed")return new Response(null,{status:503,headers:{"x-void-email-receipt":w}});let M=await $r(t,r,{stub:R,projectId:p.projectId,domain:y,envelope:E,authoritative:p,receiptId:w});if(M.temporary)return new Response(null,{status:503});try{await
|
|
8
|
+
`),n=Object.create(null),o="",i=0;for(let s of r){if(++i>se)throw new L("too many MIME headers",413);if(/^[ \t]/.test(s)){if(!o)throw new L("invalid MIME header fold",400);n[o]+=` ${s.trim()}`;continue}let a=s.indexOf(":");if(a<=0)throw new L("invalid MIME header",400);let l=s.slice(0,a).toLowerCase();if(!/^[!#$%&'*+.^_`|~0-9a-z-]+$/.test(l))throw new L("invalid MIME header name",400);n[l]=n[l]?`${n[l]}, ${s.slice(a+1).trim()}`:s.slice(a+1).trim(),o=l}return n}c(po,"parseHeaders");async function go(e,t,r){if(At(t))return new Response(null,{status:503});if(e.headers.get("content-encoding"))return new Response(null,{status:415});let n=e.headers.get("x-void-email-account")??"",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")??"",a=e.headers.get("x-void-email-from")??"",l=e.headers.get("x-void-email-to")??"",d=e.headers.get("authorization")??"";if([n,o,i,a,l,d].some(y=>!y||y.length>wt)||!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 m=Number(u);if(!Number.isSafeInteger(m)||m<0)return new Response(null,{status:411});if(m>D)return new Response(null,{status:413});let p;try{p=await Vr(t,{accountId:n,zoneId:o,ingressName:i,from:a,to:l,secret:d.slice(7)})}catch{return new Response(null,{status:503})}if(!p)return new Response(null,{status:403});let f;try{f=await mo(e.body,m)}catch(y){return console.error("[email-gateway] ingress failed:",y instanceof Error?y.message.slice(0,200):"unknown"),new Response(null,{status:502})}let h;try{h=po(f)}catch(y){if(y instanceof L)return new Response(null,{status:y.status});throw y}try{let y=l.slice(l.lastIndexOf("@")+1).toLowerCase();if(y!==p.domain)return new Response(null,{status:403});let E={from:a,to:l,raw:f,rawSize:f.byteLength,headers:h,...p.addressing==="custom"?{viaDomain:y}:{}},R;try{R=p.limits?t.DISPATCH.get(p.workerName,{},{limits:p.limits}):t.DISPATCH.get(p.workerName)}catch(O){return console.error("[email-gateway] tenant dispatch stub unavailable:",O),new Response(null,{status:503})}let w=await bt(Fe.encode(JSON.stringify([p.connectionId,s]))),A=await bt(Fe.encode(JSON.stringify([a,l,await bt(f)]))),b={receiptId:w,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 Ot(t,b)}catch(O){if(O instanceof Error&&O.message==="IDEMPOTENCY_CONFLICT")return new Response(null,{status:409});throw O}if(_.state==="completed"&&typeof _.reject=="boolean")return new Response(null,{status:_.reject?403:204,headers:{"x-void-email-receipt":w}});if(_.state!=="claimed")return new Response(null,{status:503,headers:{"x-void-email-receipt":w}});let M=await $r(t,r,{stub:R,projectId:p.projectId,domain:y,envelope:E,authoritative:p,receiptId:w});if(M.temporary)return new Response(null,{status:503});try{await kt(t,b,M.reject)}catch{console.error("[email-gateway] receipt completion remains unresolved",w)}return new Response(null,{status:M.reject?403:204,headers:{"x-void-email-receipt":w}})}catch(y){return console.error("[email-gateway] ingress failed:",y instanceof Error?y.message.slice(0,200):"unknown"),new Response(null,{status:502})}}c(go,"ingress");async function bt(e){return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",e)),t=>t.toString(16).padStart(2,"0")).join("")}c(bt,"sha256");async function ho(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>wt)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,a=Date.now()+5e3;try{for(;;){let E=a-Date.now();if(E<=0)return new Response(null,{status:400});let R,w=await Promise.race([o.read(),new Promise((A,b)=>{R=setTimeout(()=>b(new Error("probe timeout")),E)})]).finally(()=>{R!==void 0&&clearTimeout(R)});if(w.done)break;if(s+=w.value.byteLength,s>i.byteLength)return new Response(null,{status:400});i.set(w.value,s-w.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 l;try{l=JSON.parse(Rt.decode(i.subarray(0,s)))}catch{return new Response(null,{status:400})}if(!l||typeof l!="object")return new Response(null,{status:400});let{accountId:d,zoneId:u,ingressName:m}=l;if([d,u,m].some(E=>typeof E!="string"||!E||E.length>wt))return new Response(null,{status:400});let p=await zr(`email-probe-v1
|
|
9
9
|
${d}
|
|
10
10
|
${u}
|
|
11
11
|
${m}`,t.EMAIL_SIGNING_SECRET),f=new AbortController,h=Date.now()+5e3,y;try{let E=await Promise.race([t.API.fetch("https://api/internal/email/probe-ingress",{method:"POST",headers:{"content-type":"application/json","x-void-internal":p},body:JSON.stringify({accountId:d,zoneId:u,ingressName:m,secret:n.slice(7)}),signal:f.signal}),new Promise((R,w)=>{y=setTimeout(()=>{f.abort(),w(new Error("email probe timeout"))},Math.max(0,h-Date.now()))})]);return E.body?.cancel().catch(()=>{}),new Response(null,{status:E.status===204?204:403})}catch{return new Response(null,{status:503})}finally{y!==void 0&&clearTimeout(y)}}c(ho,"probe");function Ue(e,t,r){let n=new Headers({"cache-control":"no-store","content-security-policy":"frame-ancestors 'none'","referrer-policy":"no-referrer","x-content-type-options":"nosniff","x-frame-options":"DENY"});return r&&n.set("content-type",r),new Response(e,{status:t,headers:n})}c(Ue,"confirmationResponse");async function yo(e,t,r){let n=Number(e.headers.get("content-length"));if(Number.isFinite(n)&&n>Fr)throw new Error("confirmation response too large");let o=e.body?.getReader();if(!o)return null;let i=new Uint8Array(Fr),s=0;try{for(;;){let a=t-Date.now();if(a<=0)throw new Error("confirmation response timeout");let l,d=await Promise.race([o.read(),new Promise((u,m)=>{l=setTimeout(()=>{r.abort(),m(new Error("confirmation response timeout"))},a)})]).finally(()=>{l!==void 0&&clearTimeout(l)});if(d.done)return 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{}}}c(yo,"readConfirmationResponse");async function Eo(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>fo||!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(n[0][1]))return Ue(null,400);if(At(t))return Ue(null,503);let o=Date.now()+Hr,i=new AbortController,s,a;try{let l=new URL(`https://api${Gr}`);l.searchParams.set("token",n[0][1]);let d=t.API.fetch(l.toString(),{method:e.method,redirect:"manual",signal:i.signal});d.then(m=>{i.signal.aborted&&m!==s&&m.body?.cancel().catch(()=>{})},()=>{}),s=await Promise.race([d,new Promise((m,p)=>{a=setTimeout(()=>{i.abort(),p(new Error("confirmation request timeout"))},Hr)})]),a!==void 0&&(clearTimeout(a),a=void 0);let u=await yo(s,o,i);return Ue(u,s.status,s.headers.get("content-type"))}catch{return Ue(null,503)}finally{i.abort(),a!==void 0&&clearTimeout(a),s?.body?.cancel().catch(()=>{})}}c(Eo,"confirmDestination");var sl={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===Gr)return Eo(e,t);if(e.method!=="POST")return new Response(null,{status:404});if(n.pathname==="/email/probe")return ho(e,t);if(n.pathname==="/email/ingress")try{return await Br(()=>go(e,t,r))}catch{return new Response(null,{status:503})}return new Response(null,{status:404})},async email(e,t,r){if(At(t))throw new Error("Email gateway temporarily unavailable");let n=t.EMAIL_SHARED_ACCOUNT_ID,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 Vr(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 Br(()=>jr(e,t,r,s))}};export{sl as default};
|
|
@@ -2,17 +2,17 @@
|
|
|
2
2
|
"artifacts": {
|
|
3
3
|
"api": {
|
|
4
4
|
"path": "api/index.js",
|
|
5
|
-
"sha256": "
|
|
6
|
-
"size":
|
|
5
|
+
"sha256": "38d917c1376cf06603843b496450e50d4c2471386656a9e7dda806783f6cf4f7",
|
|
6
|
+
"size": 3755618
|
|
7
7
|
},
|
|
8
8
|
"dispatch": {
|
|
9
9
|
"path": "dispatch/index.js",
|
|
10
|
-
"sha256": "
|
|
11
|
-
"size":
|
|
10
|
+
"sha256": "a9639f37a861bcdc2f4bd2c2578ac37de10716dfe4f28ff3fd044bd1d342aa39",
|
|
11
|
+
"size": 85738
|
|
12
12
|
},
|
|
13
13
|
"proxy": {
|
|
14
14
|
"path": "proxy/index.js",
|
|
15
|
-
"sha256": "
|
|
15
|
+
"sha256": "1cec4168b94db012bd82379d1c120a15db99195c54f95440acae6eb90d4dc03d",
|
|
16
16
|
"size": 83539
|
|
17
17
|
},
|
|
18
18
|
"tail": {
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
},
|
|
23
23
|
"emailGateway": {
|
|
24
24
|
"path": "emailGateway/index.js",
|
|
25
|
-
"sha256": "
|
|
25
|
+
"sha256": "685b50c899c4236dd14740acd343ee91c2bcb165859ba5bcfec36703470918a3",
|
|
26
26
|
"size": 80778
|
|
27
27
|
}
|
|
28
28
|
},
|
|
@@ -31,13 +31,13 @@
|
|
|
31
31
|
"assets": {
|
|
32
32
|
"adminClient": {
|
|
33
33
|
"path": "api/assets/admin/client.js",
|
|
34
|
-
"sha256": "
|
|
35
|
-
"size":
|
|
34
|
+
"sha256": "0ff4242e2bec28a0e15e5f27c80dfc86d9ad89b2c8180f8223af0b273b75ddd1",
|
|
35
|
+
"size": 1300762
|
|
36
36
|
},
|
|
37
37
|
"adminStyle": {
|
|
38
38
|
"path": "api/assets/admin/style.css",
|
|
39
|
-
"sha256": "
|
|
40
|
-
"size":
|
|
39
|
+
"sha256": "015e1d389a5e57b9f2ca8e8ed5db55a6d9a4cf1b544d1b74130aad81a9483b44",
|
|
40
|
+
"size": 233657
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
43
|
"authenticationProtocolVersion": 1,
|
|
@@ -458,11 +458,11 @@
|
|
|
458
458
|
],
|
|
459
459
|
"schemaDigest": "d8e007d2bbe02637f6e77a33c1db152e0c4f21b30439ad512e16bce6726d6b9b"
|
|
460
460
|
},
|
|
461
|
-
"platformVersion": "1.1.
|
|
461
|
+
"platformVersion": "1.1.12",
|
|
462
462
|
"safetyProtocols": {
|
|
463
463
|
"sandboxDrain": 3
|
|
464
464
|
},
|
|
465
465
|
"schemaVersion": 2,
|
|
466
|
-
"sourceRevision": "
|
|
466
|
+
"sourceRevision": "d3ea54d66b1836623c548763e4164d19177cbfa9",
|
|
467
467
|
"usageProtocolVersion": 2
|
|
468
468
|
}
|