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