@void/platform 0.25.0 → 0.26.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.
|
@@ -2,4 +2,4 @@ var vr=Object.defineProperty;var c=(e,t)=>vr(e,"name",{value:t,configurable:!0})
|
|
|
2
2
|
${e}
|
|
3
3
|
${t}`}c(bn,"ownerVerificationMessage");async function Yt(e,t,r,n,s){try{let o=await Xe(r,t),a=await e.fetch(`https://api/internal/verify-prerender-build/${r}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":o},body:JSON.stringify({userId:n,...s})});return a.status===400&&!s.buildId&&!s.credentialId?(await a.json().catch(()=>null))?.error==="userId and credential provenance required":a.ok}catch{return!1}}c(Yt,"verifyPrerenderAuthority");var Xt=new TextEncoder,we,Kt;async function wn(e){return we&&Kt===e||(we=await crypto.subtle.importKey("raw",Xt.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),Kt=e),we}c(wn,"getSignKey");async function Xe(e,t){let r=await wn(t),n=await crypto.subtle.sign("HMAC",r,Xt.encode(e)),s=String.fromCharCode(...new Uint8Array(n));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(Xe,"hmacSign");var Rn="https://api.cloudflare.com/client/v4",Re=new M;Re.post("/query",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.sql);if(!n||!s)return e.json({error:"binding and sql required"},400);let o=await C(e.env,r,"/d1/query",t);if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"d1",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${Rn}/accounts/${e.env.CF_ACCOUNT_ID}/d1/database/${a}/query`,{method:"POST",headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`,"Content-Type":"application/json"},body:JSON.stringify({sql:s,params:t.params??[]})});if(!i.ok)return e.json({error:"D1 query failed",status:i.status},502);let d=(await i.json()).result?.[0];if(!d)return e.json({error:"unexpected D1 response"},502);switch(t.method){case"first":return e.json(d.results?.[0]??null);case"raw":{let u=d.results?.length?Object.keys(d.results[0]):[],p=(d.results??[]).map(m=>Object.values(m));return e.json({columns:u,results:p,meta:d.meta})}case"run":return e.json({success:!0,meta:d.meta});default:return e.json({results:d.results??[],success:!0,meta:d.meta})}});Re.post("/batch",async e=>{let t=e.get("body"),r=e.get("projectId");if(!h(t.binding)||!Array.isArray(t.statements))return e.json({error:"binding and statements required"},400);let s=await C(e.env,r,"/d1/batch",t);return s||e.json({error:"atomic D1 batch unavailable for active deployment"},503)});import{EmailMessage as Cn}from"cloudflare:email";var Y=new TextEncoder,Ee=new TextDecoder,En=5e3,Ae=15e3,Qt=15e3,An=65536;async function _n(e,t){if(!t)throw new Error("Email signing key is not configured");let r=await crypto.subtle.importKey("raw",Y.encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,Y.encode(e)));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(_n,"sign");async function Qe(e,t,r,n=En){let s=new AbortController,o=Date.now()+n,a=c(async f=>{let y=o-Date.now();if(y<=0)throw s.abort(),new Error("EMAIL_ADMISSION_TIMEOUT");let R=f(),b;try{return await Promise.race([R,new Promise((_,E)=>{b=setTimeout(()=>{s.abort(),E(new Error("EMAIL_ADMISSION_TIMEOUT"))},y)})])}finally{b!==void 0&&clearTimeout(b)}},"beforeDeadline"),i=JSON.stringify(r),l=await _n(i,e.EMAIL_SIGNING_SECRET),d=await a(()=>e.API.fetch(`https://api/internal/email/actions${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":l},body:i,signal:s.signal}));if(!d.ok)throw d.body?.cancel().catch(()=>{}),d.status===409?new Error("IDEMPOTENCY_CONFLICT"):new Error(`EMAIL_ADMISSION_${d.status}`);let u=d.body?.getReader();if(!u)throw new Error("EMAIL_ADMISSION_EMPTY_RESPONSE");let p=new Uint8Array(An),m=0;try{for(;;){let f=await a(()=>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(Ee.decode(p.subarray(0,m)))}finally{u.cancel().catch(()=>{});try{u.releaseLock()}catch{}}}c(Qe,"call");function vn(e){if(Sn(e)===-1)return e;let t=new Map,r=[],n=0,s=0,o=!1,a=!0,i=!0,l=c(f=>{f.byteLength!==0&&(r.push(f),n+=f.byteLength)},"append"),d=c((f,y,R)=>{l(e.subarray(s,f)),l(R),s=y,o=!0},"replace"),u=0;for(;u<e.byteLength;){let f=kn(e,u),y=f===e.byteLength?e.byteLength:f+2;if(a){if(f===u)a=!1,i=!1;else if(i&&(_e(e,u,f,"Date: ")||_e(e,u,f,"Message-ID: ")))d(u,y,new Uint8Array);else if(In(e,u,f)){let R=Ee.decode(e.subarray(u,f)),b=R.replace(/boundary="(=_void_(?:mixed|alternative|related)_[A-Za-z0-9_-]+)"/g,(_,E)=>{let A=t.get(E);return A||(A=`<void-boundary-${t.size}>`,t.set(E,A)),`boundary="${A}"`});b!==R&&d(u,f,Y.encode(b))}}else if(e[u]===45&&e[u+1]===45){let R=u+2,b=Zt(e,R,f)?Ee.decode(e.subarray(R,f)):void 0,_=b===void 0?void 0:t.get(b);if(_!==void 0)d(u,f,Y.encode(`--${_}`)),a=!0;else if(f-R>=2&&e[f-2]===45&&e[f-1]===45&&Zt(e,R,f-2)){let E=Ee.decode(e.subarray(R,f-2)),A=t.get(E);A!==void 0&&d(u,f,Y.encode(`--${A}--`))}}u=y}if(!o)return e;l(e.subarray(s));let p=new Uint8Array(n),m=0;for(let f of r)p.set(f,m),m+=f.byteLength;return p}c(vn,"canonicalizeVoidMime");function Sn(e){for(let t=0;t+3<e.byteLength;t++)if(e[t]===13&&e[t+1]===10&&e[t+2]===13&&e[t+3]===10)return t;return-1}c(Sn,"findCrlfCrlf");function kn(e,t){let r=t;for(;r<e.byteLength;){let n=e.indexOf(13,r);if(n===-1)return e.byteLength;if(e[n+1]===10)return n;r=n+1}return e.byteLength}c(kn,"findCrlf");function _e(e,t,r,n){if(r-t<n.length)return!1;for(let s=0;s<n.length;s++){let o=e[t+s],a=n.charCodeAt(s);if((o>=65&&o<=90?o+32:o)!==(a|32))return!1}return!0}c(_e,"asciiPrefixEquals");function In(e,t,r){let n="Content-Type:";if(!_e(e,t,r,n))return!1;let s=t+n.length;for(;s<r&&(e[s]===32||e[s]===9||e[s]===11||e[s]===12);)s++;return _e(e,s,r,"multipart/")}c(In,"isMultipartContentType");function Zt(e,t,r){if(r<=t)return!1;for(let n=t;n<r;n++){let s=e[n];if(!(s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===95||s===45||s===61))return!1}return!0}c(Zt,"isBoundaryToken");async function Ze(e,t,r,n){let s=vn(n),o=Y.encode(JSON.stringify({kind:e,from:t.toLowerCase(),recipients:[...new Set(r.map(i=>i.toLowerCase()))].sort()})),a=new Uint8Array(o.length+1+s.length);return a.set(o),a[o.length]=0,a.set(s,o.length+1),[...new Uint8Array(await crypto.subtle.digest("SHA-256",a))].map(i=>i.toString(16).padStart(2,"0")).join("")}c(Ze,"emailPayloadDigest");function et(e,t,r=Qt){return Qe(e,"/admit",t,Math.min(r,Qt))}c(et,"admitEmail");function tt(e,t,r,n=Ae){return Qe(e,`/${encodeURIComponent(t)}/start`,{recipients:r},Math.min(n,Ae))}c(tt,"startEmailAttempt");function V(e,t,r,n,s={},o=Ae){return Qe(e,`/${encodeURIComponent(t)}/finish`,{recipients:r,state:n,...s},Math.min(o,Ae))}c(V,"finishEmailAttempt");function tr(e){return e.token}c(tr,"leaseBearer");async function rr(e,t,r,n=5e3){if(!e.EMAIL_SIGNING_SECRET)return null;let s=new AbortController,o=Date.now()+Math.min(n,5e3),a=c(async m=>{let f=o-Date.now();if(f<=0)throw s.abort(),new Error("email credential lease timed out");let y=m(),R;try{return await Promise.race([y,new Promise((b,_)=>{R=setTimeout(()=>{s.abort(),_(new Error("email credential lease timed out"))},f)})])}finally{R!==void 0&&clearTimeout(R)}},"beforeDeadline"),i;try{let m=await Mn(`email-lease-v1
|
|
4
4
|
${r}
|
|
5
|
-
${t.toLowerCase()}`,e.EMAIL_SIGNING_SECRET);i=await a(()=>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:s.signal}))}catch{return null}if(!i.ok)return i.body?.cancel().catch(()=>{}),null;let l=i.headers.get("content-length");if(l!==null&&(!/^\d+$/.test(l)||Number(l)>4096))return i.body?.cancel().catch(()=>{}),null;let d=i.body?.getReader();if(!d)return null;let u=new Uint8Array(4096),p=0;try{for(;;){let f=await a(()=>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(l!==null&&p!==Number(l))return null;let m=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,p)));return Tn(m)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}c(rr,"leaseEmailDomainCredential");function Tn(e){if(typeof e!="object"||e===null)return null;let t=e.kind,r=e.accountId;if(typeof r!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(r))return null;if(t==="api_token"){let n=e.token;return typeof n=="string"&&n.length>0?{kind:t,token:n,accountId:r}:null}return null}c(Tn,"parseLease");var nr=new TextEncoder,ve,er;async function Pn(e){return ve&&er===e||(ve=await crypto.subtle.importKey("raw",nr.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),er=e),ve}c(Pn,"getSignKey");async function Mn(e,t){let r=await Pn(t),n=await crypto.subtle.sign("HMAC",r,nr.encode(e)),s=String.fromCharCode(...new Uint8Array(n));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(Mn,"hmacSign");var Se=class extends Error{static{c(this,"EmailProviderTimeoutError")}constructor(){super("email provider outcome unknown after timeout"),this.name="EmailProviderTimeoutError"}};function sr(e=6e4){let t=Date.now()+e;return{remainingMs(r=0){return Math.max(0,t-Date.now()-r)},expired(r=0){return Date.now()>=t-r},async run(r,n=0){let s=Math.min(3e4,t-Date.now()-n);if(s<=0)throw new Se;let o=r(),a;try{return await Promise.race([o,new Promise((i,l)=>{a=setTimeout(()=>l(new Se),s)})])}finally{a!==void 0&&clearTimeout(a)}}}}c(sr,"createEmailProviderDeadline");var nt=new M,On=5e4,U=5e3,ke=5*1024*1024,Nn=16*1024,Dn=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 Ln(e){let t=0,r=!1;for(let n=0;n<e.byteLength;){let s=n;for(;s<e.byteLength&&e[s]!==10;)s++;let o=s>n&&e[s-1]===13?s-1:s;if(o===n)return!0;if(e[n]!==32&&e[n]!==9){let a=n;for(;a<o&&e[a]!==58;)a++;let i=new TextDecoder().decode(e.subarray(n,a)).toLowerCase();r=a<o&&!Dn.has(i)}if(r&&(t+=o-n+2,t>Nn))return!1;n=s+1}return!0}c(Ln,"customMimeHeaderBytesWithinLimit");var or=50,ar=320,cr=320;function xn(e){let t=e.EMAIL_SENDER_DOMAIN;if(typeof t!="string")return null;let r=t.trim().toLowerCase();return r.length>0?r:null}c(xn,"readSenderDomain");var jn=/[.*+?^${}()|[\]\\]/g;function Un(e){return e.replace(jn,"\\$&")}c(Un,"escapeRegExp");var lr=new Map;function $n(e){let t=lr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${Un(e)}$`);return lr.set(e,r),r}c($n,"strictFromRe");var Hn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function fr(e,t=200){return e.slice(0,t).replace(Hn," ")}c(fr,"sanitizeForLog");var Fn=128;function qn(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}c(qn,"bytesToStream");var dr=10,Ie=13,pr=32,mr=9,Bn=58,Te=[102,114,111,109];function Vn(e,t,r){if(r-t<=Te.length)return-1;for(let s=0;s<Te.length;s++)if((e[t+s]|32)!==Te[s])return-1;let n=t+Te.length;for(;n<r&&(e[n]===pr||e[n]===mr);)n++;return n<r&&e[n]===Bn?n+1:-1}c(Vn,"fromValueStart");var gr={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 yr(e){let t=e.byteLength,r=0,n=-1,s=-1,o=!1,a=!1,i=e.indexOf(Ie),l=0;for(;l<t;){let p=e.indexOf(dr,l),f=p===-1?t:p;if(f>l&&e[f-1]===Ie&&f--,f===l)break;if(i!==-1&&i<l&&(i=e.indexOf(Ie,l)),i!==-1&&i<f)return{ok:!1,reason:"malformed"};if(e[l]===pr||e[l]===mr)a&&(s=f,o=!0);else{let y=Vn(e,l,f);a=y!==-1,a&&(r++,n=y,s=f,o=!1)}l=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,s);if(o){d=e.slice(n,s);let p=0;for(let m=0;m<d.length;m++){let f=d[m];f!==Ie&&f!==dr&&(d[p++]=f)}d=d.subarray(0,p)}let u=Wn(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}c(yr,"readMimeFromAddrSpec");function Wn(e){let t=!1,r=!1,n=-1,s=-1,o=-1;for(let i=0;i<e.length;i++){let l=e[i];if(t){r?r=!1:l==="\\"?r=!0:l==='"'&&(t=!1);continue}switch(l){case'"':if(n!==-1)return null;t=!0;break;case"<":if(n!==-1)return null;n=i;break;case">":if(n===-1||s!==-1)return null;s=i;break;case"@":o===-1&&(o=i);break;case",":case";":case":":case"(":case")":case"[":case"]":case"\\":return null;default:break}}if(t)return null;let a;if(n===-1)a=e.trim();else{if(s===-1||e.slice(s+1).trim().length!==0||o!==-1&&o<n)return null;a=e.slice(n+1,s)}return/^[\x21-\x7e]+$/.test(a)?a:null}c(Wn,"singleMailboxAddrSpec");nt.post("/send",async e=>{let t=sr(On),r=e.get("projectId"),n=e.get("body"),s=h(n.from),o=h(n.mimeBase64),a=h(n.requestId),i=a===null?"unknown":fr(a,Fn),l=h(n.idempotencyKey);if(l!==null&&(l.length===0||l.length>128||!/^[\x20-\x7e]+$/.test(l)))return e.json({ok:!1,error:{code:"INVALID_TO",message:"invalid idempotency key"}},400);let d=l??(a&&a.length<=128&&/^[\x20-\x7e]+$/.test(a)?a:crypto.randomUUID()),u=Array.isArray(n.recipients)?n.recipients:null;if(!s||!o||!u)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"invalid body"}},400);if(u.length>or)return e.json({ok:!1,error:{code:"INVALID_TO",message:`too many recipients (max ${or}, got ${u.length})`}},413);if(s.length>cr)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${cr} characters`}},413);let p=xn(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 w of u){if(typeof w!="string")continue;if(w.length>ar)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${ar} characters`}},413);let S=w.trim().toLowerCase();!S||f.has(S)||(f.add(S),m.push(S))}if(m.length===0)return e.json({ok:!1,error:{code:"INVALID_TO",message:"no recipients"}},200);if(o.length>Math.ceil(ke*4/3)+4)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${ke} bytes (base64 length ${o.length})`}},413);let y;try{y=Yn(o)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"invalid base64 mime"}},400)}if(y.byteLength>ke)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${ke} bytes (got ${y.byteLength})`}},413);if(!Ln(y))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let R=s.indexOf("@"),b=R===-1?"":s.slice(R+1).toLowerCase();if(b!==""&&b!==p)return Jn(e,r,s,b,p,m,y,i,d,t);let _=e.env.SEND_EMAIL;if(typeof _?.send!="function")return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sending is not configured"}},502);let E=s.split("@")[0]?.split("+")[0]??"";if(!/^[\x21-\x7e]+$/.test(s))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let A=s.toLowerCase();if(!$n(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 O=yr(y);if(!O.ok||O.addrSpec.toLowerCase()!==A){let w=O.ok?"the From header address does not match the envelope sender":gr[O.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${s}: ${w}`}},403)}let I;try{I=await et(e.env,{projectId:r,kind:"direct",key:d,digest:await Ze("direct",s,m,y),from:s,recipients:m,transport:"binding"},t.remainingMs(U))}catch(w){let S=w instanceof Error&&w.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:S?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:S?"idempotency key has different content":"email admission unavailable"}},S?409:503)}let T=I.recipients.filter(w=>w.state!=="reserved").map(w=>({recipient:w.recipient,ok:w.state==="provider_accepted",state:w.state,messageId:w.providerReference??void 0,error:w.state==="provider_accepted"?void 0:{code:w.errorCode??(w.state==="outcome_unknown"||w.state==="attempt_started"?"OUTCOME_UNKNOWN":w.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:w.state==="outcome_unknown"||w.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":w.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(I.replay){for(let w of I.recipients.filter(S=>S.state==="reserved"))T.push({recipient:w.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return Me(e,I.operationId,T)}let $=I.recipients.filter(w=>w.state==="reserved").map(w=>w.recipient);for(let w=0;w<$.length;w++){let S=$[w];if(t.expired(U)){let F=$.slice(w),Q=await rt(e.env,I.operationId,F,t.remainingMs());for(let ie of F)T.push({recipient:ie,ok:!1,state:Q?"cancelled":"outcome_unknown",error:Q?{code:"UPSTREAM_ERROR",message:"email batch deadline elapsed before provider submission"}:{code:"OUTCOME_UNKNOWN",message:"could not cancel unstarted email attempt"}});break}try{await tt(e.env,I.operationId,[S],t.remainingMs(U))}catch{let F=await rt(e.env,I.operationId,[S],t.remainingMs());T.push({recipient:S,ok:!1,state:F?"cancelled":"outcome_unknown",error:F?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});continue}try{let F=new Cn(s,S,qn(y)),Q=await t.run(()=>_.send(F),U),ie=typeof Q?.messageId=="string"?Q.messageId:"";try{await V(e.env,I.operationId,[S],"provider_accepted",{providerReference:ie},t.remainingMs())}catch{T.push({recipient:S,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider accepted email but outcome could not be recorded"}});continue}T.push({recipient:S,ok:!0,state:"provider_accepted",messageId:ie})}catch{try{await V(e.env,I.operationId,[S],"outcome_unknown",{errorCode:"OUTCOME_UNKNOWN"},t.remainingMs())}catch{}T.push({recipient:S,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"}})}}return hr(r,i,T),T.some(w=>!w.ok)?e.json({ok:!1,operationId:I.operationId,deliveries:T},200):e.json({ok:!0,operationId:I.operationId,ids:T.map(w=>({recipient:w.recipient,messageId:w.messageId,state:"provider_accepted"}))})});var ur=64*1024;async function zn(e,t=3e4){let r=new AbortController,n=Date.now()+Math.min(3e4,t),s=JSON.stringify({from:e.from,recipients:e.recipients,mime_message:e.mimeMessage}),o=c(async p=>{let m=n-Date.now();if(m<=0)throw r.abort(),new Error("email sending request timed out");let f=p(),y;try{return await Promise.race([f,new Promise((R,b)=>{y=setTimeout(()=>{r.abort(),b(new Error("email sending request timed out"))},m)})])}finally{y!==void 0&&clearTimeout(y)}},"beforeDeadline"),a=await o(()=>fetch(`https://api.cloudflare.com/client/v4/accounts/${e.accountId}/email/sending/send_raw`,{method:"POST",headers:{authorization:`Bearer ${e.bearer}`,"content-type":"application/json"},body:s,signal:r.signal}));if(!a.ok)return a.body?.cancel().catch(()=>{}),{ok:!1,status:a.status};let i=a.headers.get("content-length");if(i!==null&&(!/^\d+$/.test(i)||Number(i)>ur))throw a.body?.cancel().catch(()=>{}),new Error("email sending API response too large");let l=a.body?.getReader();if(!l)throw new Error("email sending API response unreadable");let d=new Uint8Array(ur),u=0;try{for(;;){let p=await o(()=>l.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(i!==null&&u!==Number(i))throw new Error("email sending API response length mismatch");return{ok:!0,data:JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(d.subarray(0,u)))}}finally{l.cancel().catch(()=>{});try{l.releaseLock()}catch{}}}c(zn,"requestSendRaw");function Pe(e){if(!Array.isArray(e))return null;let t=new Set;for(let r of e){if(typeof r!="string")return null;t.add(r.toLowerCase())}return t}c(Pe,"readSendRawAddressList");function Gn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=Pe(t.delivered),n=Pe(t.permanent_bounces),s=Pe(t.queued),o=Pe(t.suppressed_recipients);return!r||!n||!s||!o||typeof t.message_id!="string"||t.message_id===""?null:{delivered:r,messageId:t.message_id,permanentBounces:n,queued:s,suppressedRecipients:o}}c(Gn,"parseSendRawResult");function Kn(e,t){let r=t.toLowerCase(),n=[e.delivered.has(r),e.queued.has(r),e.permanentBounces.has(r),e.suppressedRecipients.has(r)];return n.filter(Boolean).length!==1?"outcome_unknown":n[0]||n[1]?"provider_accepted":n[2]?"permanent_bounce":"suppressed"}c(Kn,"classifySendRawRecipient");async function Jn(e,t,r,n,s,o,a,i,l,d){if(!/^[\x21-\x7e]+$/.test(r))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let u=r.toLowerCase(),p=yr(a);if(!p.ok||p.addrSpec.toLowerCase()!==u){let g=p.ok?"the From header address does not match the envelope sender":gr[p.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${g}`}},403)}let m;try{m=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(a)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"mime must be valid UTF-8"}},400)}let f;try{f=await et(e.env,{projectId:t,kind:"direct",key:l,digest:await Ze("direct",r,o,a),from:r,recipients:o,transport:"send_raw"},d.remainingMs(U))}catch(g){let v=g instanceof Error&&g.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:v?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:v?"idempotency key has different content":"email admission unavailable"}},v?409:503)}let y=f.recipients.filter(g=>g.state!=="reserved").map(g=>({recipient:g.recipient,ok:g.state==="provider_accepted",state:g.state,messageId:g.providerReference??void 0,error:g.state==="provider_accepted"?void 0:{code:g.errorCode??(g.state==="outcome_unknown"||g.state==="attempt_started"?"OUTCOME_UNKNOWN":g.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:g.state==="outcome_unknown"||g.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":g.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(f.replay){for(let g of f.recipients.filter(v=>v.state==="reserved"))y.push({recipient:g.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return Me(e,f.operationId,y)}if(o=f.recipients.filter(g=>g.state==="reserved").map(g=>g.recipient),o.length===0)return Me(e,f.operationId,y);let R=await rr(e.env,n,t,d.remainingMs(U));if(!R)return await V(e.env,f.operationId,o,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"could not lease the domain credential"}},502);if(f.accountId!==R.accountId)return await V(e.env,f.operationId,o,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"email domain changed during admission"}},503);try{await tt(e.env,f.operationId,o,d.remainingMs(U))}catch{let g=await rt(e.env,f.operationId,o,d.remainingMs());for(let v of o)y.push({recipient:v,ok:!1,state:g?"cancelled":"outcome_unknown",error:g?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return Me(e,f.operationId,y)}let b=null,_="failed",E=null,A=null;try{A=await zn({accountId:R.accountId,bearer:tr(R),from:r,recipients:o,mimeMessage:m},d.remainingMs(U))}catch{b={code:"UPSTREAM_ERROR",message:"email sending request failed"},_="outcome_unknown"}if(A)if(!A.ok)b={code:A.status===429?"QUOTA_EXCEEDED":"UPSTREAM_ERROR",message:`email sending API returned ${A.status}`},_=A.status>=500||A.status===408?"outcome_unknown":"failed";else{let g=A.data,v=typeof g=="object"&&g!==null?g.success:void 0;v===!1?b={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:v!==!0?(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},_="outcome_unknown"):(E=Gn(g.result),E||(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},_="outcome_unknown"))}for(let g of o){if(b){y.push({recipient:g,ok:!1,state:_,error:b});continue}let v=Kn(E,g);v==="permanent_bounce"?y.push({recipient:g,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${g}' permanently bounced`}}):v==="suppressed"?y.push({recipient:g,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${g}' is on the suppression list`}}):v==="outcome_unknown"?y.push({recipient:g,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):y.push({recipient:g,ok:!0,state:"provider_accepted",messageId:E.messageId})}for(let g of y.filter(v=>f.recipients.some(O=>O.recipient===v.recipient&&O.state==="reserved")))try{await V(e.env,f.operationId,[g.recipient],g.ok?"provider_accepted":g.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:g.messageId,errorCode:g.ok?void 0:g.state==="outcome_unknown"?"OUTCOME_UNKNOWN":b?.code??g.error?.code},d.remainingMs()),g.state=g.ok?"provider_accepted":g.state==="outcome_unknown"?"outcome_unknown":"failed",g.state==="outcome_unknown"&&!g.ok&&(g.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{g.ok=!1,g.state="outcome_unknown",g.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return hr(t,i,y),y.some(g=>!g.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:y},200):e.json({ok:!0,operationId:f.operationId,ids:y.map(g=>({recipient:g.recipient,messageId:g.messageId,state:"provider_accepted"}))})}c(Jn,"sendViaCustomDomain");async function rt(e,t,r,n){try{let s=await V(e,t,r,"cancelled",{},n);return r.every(o=>s.recipients.some(a=>a.recipient===o&&a.state==="cancelled"))}catch{return!1}}c(rt,"cancelUnstartedRecipients");function Me(e,t,r){return r.length===0?e.json({ok:!1,operationId:t,error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved"}},200):r.some(n=>!n.ok)?e.json({ok:!1,operationId:t,deliveries:r},200):e.json({ok:!0,operationId:t,ids:r.map(n=>({recipient:n.recipient,messageId:n.messageId??"",state:n.state}))},200)}c(Me,"emailActionResponse");function hr(e,t,r){for(let n of r){let s=n.ok?"sent":n.error?.code??"unknown_error",o=n.messageId??"";console.log(`[email-log] ${e} ${t} ${fr(n.recipient,320)} ${s} ${o} @${Date.now()}`)}}c(hr,"logSend");function Yn(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}c(Yn,"base64Decode");function br(e,t,r){let n=e.getReader(),s=!1,o,a,i=c(()=>{s=!0,o!==void 0&&clearTimeout(o),r?.removeEventListener("abort",d)},"cleanup"),l=c(()=>{s||(i(),a.error(new Error("Authentication expired or was revoked. Sign in again.")),n.cancel().catch(()=>{}))},"stop"),d=c(()=>l(),"abort"),u=c(async()=>{if(s)return!1;try{if(await t())return!s}catch{}return l(),!1},"check"),p=c(()=>{o=setTimeout(async()=>{await u()&&p()},15e3)},"schedule");return new ReadableStream({start(m){a=m,r?.addEventListener("abort",d,{once:!0}),r?.aborted?l():p()},async pull(m){try{let f=await n.read();if(s)return;f.done?(i(),m.close()):await u()&&m.enqueue(f.value)}catch(f){s||(i(),m.error(f),n.cancel().catch(()=>{}))}},async cancel(m){i(),await n.cancel(m)}},{highWaterMark:0})}c(br,"guardHumanStream");var Ce="https://api.cloudflare.com/client/v4",X=new M;X.post("/get",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/kv/get",t,{fallbackOnDispatchError:!0});if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"kv",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${Ce}/accounts/${e.env.CF_ACCOUNT_ID}/storage/kv/namespaces/${a}/values/${encodeURIComponent(s)}`,{headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`}});if(i.status===404)return e.json(null);if(!i.ok)return e.json({error:"KV get failed",status:i.status},502);let l=h(t.type)??"text";return l==="json"?e.json(await i.json()):l==="arrayBuffer"?new Response(await i.arrayBuffer(),{headers:{"content-type":"application/octet-stream"}}):l==="stream"?new Response(i.body,{headers:{"content-type":"application/octet-stream"}}):e.json(await i.text())});X.post("/put",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/kv/put",t);if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"kv",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=new URLSearchParams;K(t.expiration)&&i.set("expiration",String(t.expiration)),K(t.expiration_ttl)&&i.set("expiration_ttl",String(t.expiration_ttl));let l=i.toString()?`?${i.toString()}`:"",d,u="text/plain";if(t.base64===!0&&typeof t.value=="string"){let m=atob(t.value),f=new Uint8Array(m.length);for(let y=0;y<m.length;y++)f[y]=m.charCodeAt(y);d=f.buffer,u="application/octet-stream"}else d=typeof t.value=="string"?t.value:JSON.stringify(t.value);let p=await fetch(`${Ce}/accounts/${e.env.CF_ACCOUNT_ID}/storage/kv/namespaces/${a}/values/${encodeURIComponent(s)}${l}`,{method:"PUT",headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`,"Content-Type":u},body:d});return p.ok?e.json({success:!0}):e.json({error:"KV put failed",status:p.status},502)});X.post("/delete",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/kv/delete",t);if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"kv",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${Ce}/accounts/${e.env.CF_ACCOUNT_ID}/storage/kv/namespaces/${a}/values/${encodeURIComponent(s)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`}});return!i.ok&&i.status!==404?e.json({error:"KV delete failed",status:i.status},502):e.json({success:!0})});X.post("/list",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding);if(!n)return e.json({error:"binding required"},400);let s=await C(e.env,r,"/kv/list",t,{fallbackOnDispatchError:!0});if(s)return s;let o;try{o=await N(e.env.API,e.env.JWT_SECRET,r,"kv",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let a=new URLSearchParams,i=h(t.prefix);i&&a.set("prefix",i),K(t.limit)&&a.set("limit",String(t.limit));let l=h(t.cursor);l&&a.set("cursor",l);let d=a.toString()?`?${a.toString()}`:"",u=await fetch(`${Ce}/accounts/${e.env.CF_ACCOUNT_ID}/storage/kv/namespaces/${o}/keys${d}`,{headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`}});if(!u.ok)return e.json({error:"KV list failed",status:u.status},502);let p=await u.json();return e.json({keys:p.result??[],list_complete:!p.result_info?.cursor,cursor:p.result_info?.cursor??null})});var wr="__void/platform/disabled/v1",Rr="disabled";var ne="https://api.cloudflare.com/client/v4",W=new M;function se(e){return{Authorization:`Bearer ${e}`}}c(se,"cfHeaders");W.post("/get",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/r2/get",t,{fallbackOnDispatchError:!0});if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${a}/objects/${encodeURIComponent(s)}`,{headers:se(e.env.CF_API_TOKEN)});if(i.status===404)return e.json(null);if(!i.ok)return e.json({error:"R2 get failed",status:i.status},502);let l=new Headers;return l.set("content-type",i.headers.get("content-type")??"application/octet-stream"),i.headers.has("content-length")&&l.set("content-length",i.headers.get("content-length")),i.headers.has("etag")&&l.set("etag",i.headers.get("etag")),i.headers.has("last-modified")&&l.set("last-modified",i.headers.get("last-modified")),new Response(i.body,{headers:l})});W.on("POST",["/put","/put-conditional"],async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key),o=h(t.base64);if(!n||!s)return e.json({error:"binding and key required"},400);let a=t.onlyIf!==void 0||e.req.path.endsWith("/put-conditional"),i=await C(e.env,r,a?"/r2/put-conditional":"/r2/put",t);if(i)return i;if(a)return e.json({error:"R2 conditional writes require an active deployment with the current Void remote-binding handler. Update your Void platform and redeploy the project."},501);let l;try{l=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let d=o?Uint8Array.from(atob(o),p=>p.charCodeAt(0)):new TextEncoder().encode(t.value??""),u=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${l}/objects/${encodeURIComponent(s)}`,{method:"PUT",headers:{...se(e.env.CF_API_TOKEN),"Content-Type":h(t.contentType)??"application/octet-stream"},body:d});return u.ok?e.json({success:!0}):e.json({error:"R2 put failed",status:u.status},502)});W.post("/delete",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding);if(!n)return e.json({error:"binding required"},400);let s=Array.isArray(t.keys)&&t.keys.every(i=>typeof i=="string")?t.keys:typeof t.key=="string"?[t.key]:[];if(s.length===0)return e.json({error:"key or keys required"},400);let o=await C(e.env,r,"/r2/delete",t);if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}for(let i of s){let l=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${a}/objects/${encodeURIComponent(i)}`,{method:"DELETE",headers:se(e.env.CF_API_TOKEN)});if(!l.ok&&l.status!==404)return e.json({error:"R2 delete failed",status:l.status},502)}return e.json({success:!0})});W.post("/list",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding);if(!n)return e.json({error:"binding required"},400);let s=await C(e.env,r,"/r2/list",t,{fallbackOnDispatchError:!0});if(s)return s;let o;try{o=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let a=new URLSearchParams,i=h(t.prefix);i&&a.set("prefix",i),K(t.limit)&&a.set("per_page",String(t.limit));let l=h(t.cursor);l&&a.set("cursor",l);let d=h(t.delimiter);d&&a.set("delimiter",d);let u=a.toString()?`?${a.toString()}`:"",p=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${o}/objects${u}`,{headers:se(e.env.CF_API_TOKEN)});if(!p.ok)return e.json({error:"R2 list failed",status:p.status},502);let m=await p.json();return e.json({objects:(m.result??[]).map(f=>({key:f.key,size:f.size,lastModified:f.last_modified??""})),truncated:!!m.result_info?.cursor,cursor:m.result_info?.cursor??null})});W.post("/head",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/r2/head",t,{fallbackOnDispatchError:!0});if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${a}/objects/${encodeURIComponent(s)}`,{method:"HEAD",headers:se(e.env.CF_API_TOKEN)});return i.status===404?e.json(null):i.ok?e.json({key:s,size:parseInt(i.headers.get("content-length")??"0"),etag:i.headers.get("etag")??"",lastModified:i.headers.get("last-modified")??"",contentType:i.headers.get("content-type")??"application/octet-stream"}):e.json({error:"R2 head failed",status:i.status},502)});var Xn=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}),Qn=1024*1024,Zn=8*1024*1024,D=class extends Error{constructor(r,n){super(r);this.status=n;this.name="RequestBodyError"}status;static{c(this,"RequestBodyError")}};function Er(e){switch(e){case"/ai/run":case"/ai/provider":case"/ai/toMarkdown":case"/kv/put":case"/r2/put":case"/r2/put-conditional":return Zn;default:return Qn}}c(Er,"requestBodyMaxBytes");async function es(e,t){let r=e-Date.now();if(r<=0)throw new D("request body timeout",408);let n;return Promise.race([t(),new Promise((s,o)=>{n=setTimeout(()=>o(new D("request body timeout",408)),r)})]).finally(()=>{n!==void 0&&clearTimeout(n)})}c(es,"beforeDeadline");async function st(e,t){let r=e.headers.get("content-length");if(r!==null&&/^\d+$/.test(r)&&Number(r)>t)throw e.body?.cancel().catch(()=>{}),new D("request body too large",413);if(e.headers.has("content-encoding")||!e.body||r!==null&&!/^\d+$/.test(r))throw e.body?.cancel().catch(()=>{}),new D("invalid request body",400);let n=r===null?null:Number(r),s=e.body.getReader(),o=new Uint8Array(Math.min(1024,t)),a=Date.now()+5e3,i=0;try{for(;;){let l=await es(a,()=>s.read());if(l.done)break;let d=i+l.value.byteLength;if(d>t)throw new D("request body too large",413);if(d>o.byteLength){let u=new Uint8Array(Math.min(t,Math.max(d,o.byteLength*2)));u.set(o.subarray(0,i)),o=u}o.set(l.value,i),i=d}}finally{s.cancel().catch(()=>{}),s.releaseLock()}if(i===0||n!==null&&i!==n)throw new D("invalid request body length",400);return JSON.parse(Xn.decode(o.subarray(0,i)))}c(st,"readRequestJson");var it=new M;it.post("/",async e=>{let t=e.get("projectId"),r=e.get("body"),n=await e.env.API.fetch(`https://api/internal/revalidate/${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":r.aiToken},body:JSON.stringify({paths:r.paths,all:r.all})});return new Response(n.body,{status:n.status,headers:n.headers})});var P=new M;P.use("/*",async(e,t)=>{let r=e.env.PLATFORM_HEALTH_PROBE_TOKEN;if(!(r!==void 0&&r!==""&&e.req.path==="/health"&&e.req.header("X-Void-Platform-Probe")===r)&&(e.env.PLATFORM_TRAFFIC_STATE==="staging"||e.env.PLATFORM_TRAFFIC_STATE==="sandbox-drain"||e.env.PLATFORM_INSTALLATION_ID&&await e.env.ROUTING.get(wr)===Rr))return e.json({error:"Platform disabled"},503);await t()});P.use("/*",xt({origin:"*",allowMethods:["POST","OPTIONS"],allowHeaders:["content-type","authorization"]}));P.get("/health",e=>e.json({ok:!0,bindings:{ai:!!e.env.AI,kv:!!e.env.ROUTING,jwt:!!e.env.JWT_SECRET,api:!!e.env.API,sendEmail:!!e.env.SEND_EMAIL,emailDomain:!!e.env.EMAIL_SENDER_DOMAIN}}));P.all("/*",async(e,t)=>{if(e.req.method!=="POST")return e.json({error:"method not allowed"},405);await t()});async function ts(e,t){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(e))),s="";for(let o of n)s+=String.fromCharCode(o);return btoa(s).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}c(ts,"hmacSign");P.post("/email/verify-receipt",async e=>{let t;try{t=await st(e.req.raw,2*1024)}catch{return e.json({valid:!1},400)}if(!t||typeof t!="object")return e.json({valid:!1},400);let r=t;if(typeof r.projectId!="string"||r.projectId.length>128||typeof r.deploymentId!="string"||r.deploymentId.length>128||typeof r.recipient!="string"||r.recipient.length>320||typeof r.receipt!="string"||r.receipt.length>1536)return e.json({valid:!1},400);let n=await ts(r.projectId,e.env.JWT_SECRET);if(e.req.header("x-void-internal")!==n)return e.json({valid:!1},403);if(!e.env.EMAIL_SIGNING_SECRET)return e.json({valid:!1},503);let s=await lt(r.receipt,e.env.EMAIL_SIGNING_SECRET,{projectId:r.projectId,deploymentId:r.deploymentId,recipient:r.recipient});return e.json({valid:s!==null,receiptId:s?.receiptId})});P.post("/email/relay",e=>e.json({error:"not found"},404));P.post("/*",async(e,t)=>{let r=new URL(e.req.url).pathname,n;try{let a=r==="/email"||r.startsWith("/email/")?8388608:Er(r),i=await st(e.req.raw,a);if(!j(i))return e.json({error:"invalid JSON body"},400);n=i}catch(a){return r!=="/email"&&!r.startsWith("/email/")&&a instanceof D?e.json({error:a.message},a.status):e.json({error:"invalid JSON body"},400)}e.set("body",n);let s,o=e.req.header("authorization");if(o?.startsWith("Bearer ")){let a=o.slice(7),i=await ss(a,e.env.JWT_SECRET);if(!i)return e.json({error:"invalid or expired token",message:"This proxy credential is invalid or expired. Sign in to the connected platform again for remote development, or restart the build to obtain a fresh prerender token."},401);let l=h(n.projectId);if(!l)return e.json({error:"projectId required"},400);if(i.aud==="prerender"){if(!i.project||i.project!==l)return e.json({error:"forbidden",message:"This prerender token does not match the requested project. Restart the build with a prerender token issued for the selected project."},403);if(!await Yt(e.env.API,e.env.JWT_SECRET,l,i.sub,{...i.build?{buildId:i.build}:{},...i.credential?{credentialId:i.credential}:{}}))return e.json({error:i.credential?"prerender token credential is no longer active":i.build?"prerender token build is no longer active":"prerender token authority is no longer active",message:i.credential?"The deploy credential used for prerendering is no longer authorized. Ask the project owner for an active deploy credential, then restart the build.":i.build?"This build is no longer authorized to prerender. Start a new build to obtain a fresh prerender token.":"This prerender token is no longer authorized. Confirm your project access with a project admin or owner, then restart the build to obtain a fresh token."},403)}else{let d=c(()=>Jt(e.env.API,e.env.JWT_SECRET,l,i.sub,a,e.req.header("Cf-Access-Jwt-Assertion"),new URL(e.req.url).origin),"checkOwner");if(s=c(async()=>i.exp>Date.now()/1e3&&await d(),"revalidateHuman"),!await s())return e.json({error:"forbidden",message:"Remote access could not be authorized. Check the selected platform and project, then ask a project admin or owner to confirm your access. If your access is correct, retry shortly."},403)}e.set("projectId",l)}else{let a=h(n.projectId),i=h(n.aiToken);if(!a||!i)return e.json({error:"projectId and aiToken required"},400);if(!await ns(a,i,e.env.JWT_SECRET))return e.json({error:"invalid project token"},403);e.set("projectId",a)}await t(),s&&e.res.body&&(e.res.headers.get("content-type")?.includes("text/event-stream")||r.startsWith("/ai/")||r==="/r2/get")&&(e.res=new Response(br(e.res.body,s,e.req.raw.signal),e.res))});P.post("/ai/*",async(e,t)=>{if(await e.env.ROUTING.get(`ai-block:${e.get("projectId")}`,{cacheTtl:60}))return xe({code:"usage_limit",resource:"ai",reason:"monthly_quota",message:"AI usage limit exceeded"});await t()});P.post("/email/*",async(e,t)=>{if(!Bt(e.env.PLATFORM_CAPABILITIES,"email"))return e.json({error:"platform capability unavailable",capability:"email",message:"This Void platform does not enable email."},501);await t()});P.route("/ai",J);P.route("/d1",Re);P.route("/kv",X);P.route("/r2",W);P.route("/revalidate",it);P.route("/email",nt);var ld={fetch:P.fetch},at=new TextEncoder,rs=new TextDecoder,Oe,Ar;async function _r(e){return Oe&&Ar===e||(Oe=await crypto.subtle.importKey("raw",at.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["verify"]),Ar=e),Oe}c(_r,"getVerifyKey");async function ns(e,t,r){try{let n=await _r(r),s=ot(t);return crypto.subtle.verify("HMAC",n,s.buffer,at.encode(e))}catch{return!1}}c(ns,"verifyHmac");function ot(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t);return Uint8Array.from(r,n=>n.charCodeAt(0))}c(ot,"base64urlDecode");async function ss(e,t){let r=e.split(".");if(r.length!==3)return null;let[n,s,o]=r;try{let a=await _r(t),i=ot(o);if(!await crypto.subtle.verify("HMAC",a,i.buffer,at.encode(`${n}.${s}`)))return null;let d=JSON.parse(rs.decode(ot(s))),u=Math.floor(Date.now()/1e3);return d.exp<=u||d.aud!=="api"&&d.aud!=="prerender"?null:d}catch{return null}}c(ss,"verifyJwt");export{ld as default};
|
|
5
|
+
${t.toLowerCase()}`,e.EMAIL_SIGNING_SECRET);i=await a(()=>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:s.signal}))}catch{return null}if(!i.ok)return i.body?.cancel().catch(()=>{}),null;let l=i.headers.get("content-length");if(l!==null&&(!/^\d+$/.test(l)||Number(l)>4096))return i.body?.cancel().catch(()=>{}),null;let d=i.body?.getReader();if(!d)return null;let u=new Uint8Array(4096),p=0;try{for(;;){let f=await a(()=>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(l!==null&&p!==Number(l))return null;let m=JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(u.subarray(0,p)));return Tn(m)}catch{return null}finally{d.cancel().catch(()=>{});try{d.releaseLock()}catch{}}}c(rr,"leaseEmailDomainCredential");function Tn(e){if(typeof e!="object"||e===null)return null;let t=e.kind,r=e.accountId;if(typeof r!="string"||!/^[a-zA-Z0-9_-]{1,128}$/.test(r))return null;if(t==="api_token"){let n=e.token;return typeof n=="string"&&n.length>0?{kind:t,token:n,accountId:r}:null}return null}c(Tn,"parseLease");var nr=new TextEncoder,ve,er;async function Pn(e){return ve&&er===e||(ve=await crypto.subtle.importKey("raw",nr.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),er=e),ve}c(Pn,"getSignKey");async function Mn(e,t){let r=await Pn(t),n=await crypto.subtle.sign("HMAC",r,nr.encode(e)),s=String.fromCharCode(...new Uint8Array(n));return btoa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}c(Mn,"hmacSign");var Se=class extends Error{static{c(this,"EmailProviderTimeoutError")}constructor(){super("email provider outcome unknown after timeout"),this.name="EmailProviderTimeoutError"}};function sr(e=6e4){let t=Date.now()+e;return{remainingMs(r=0){return Math.max(0,t-Date.now()-r)},expired(r=0){return Date.now()>=t-r},async run(r,n=0){let s=Math.min(3e4,t-Date.now()-n);if(s<=0)throw new Se;let o=r(),a;try{return await Promise.race([o,new Promise((i,l)=>{a=setTimeout(()=>l(new Se),s)})])}finally{a!==void 0&&clearTimeout(a)}}}}c(sr,"createEmailProviderDeadline");var nt=new M,On=5e4,U=5e3,ke=5*1024*1024,Nn=16*1024,Dn=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 Ln(e){let t=0,r=!1;for(let n=0;n<e.byteLength;){let s=n;for(;s<e.byteLength&&e[s]!==10;)s++;let o=s>n&&e[s-1]===13?s-1:s;if(o===n)return!0;if(e[n]!==32&&e[n]!==9){let a=n;for(;a<o&&e[a]!==58;)a++;let i=new TextDecoder().decode(e.subarray(n,a)).toLowerCase();r=a<o&&!Dn.has(i)}if(r&&(t+=o-n+2,t>Nn))return!1;n=s+1}return!0}c(Ln,"customMimeHeaderBytesWithinLimit");var or=50,ar=320,cr=320;function xn(e){let t=e.EMAIL_SENDER_DOMAIN;if(typeof t!="string")return null;let r=t.trim().toLowerCase();return r.length>0?r:null}c(xn,"readSenderDomain");var jn=/[.*+?^${}()|[\]\\]/g;function Un(e){return e.replace(jn,"\\$&")}c(Un,"escapeRegExp");var lr=new Map;function $n(e){let t=lr.get(e);if(t)return t;let r=new RegExp(`^[a-z0-9._-]+(?:\\+[a-z0-9._=/-]+)*@${Un(e)}$`);return lr.set(e,r),r}c($n,"strictFromRe");var Hn=new RegExp("[\\u0000-\\u001f\\u007f]+","g");function fr(e,t=200){return e.slice(0,t).replace(Hn," ")}c(fr,"sanitizeForLog");var Fn=128;function qn(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}c(qn,"bytesToStream");var dr=10,Ie=13,pr=32,mr=9,Bn=58,Te=[102,114,111,109];function Vn(e,t,r){if(r-t<=Te.length)return-1;for(let s=0;s<Te.length;s++)if((e[t+s]|32)!==Te[s])return-1;let n=t+Te.length;for(;n<r&&(e[n]===pr||e[n]===mr);)n++;return n<r&&e[n]===Bn?n+1:-1}c(Vn,"fromValueStart");var gr={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 yr(e){let t=e.byteLength,r=0,n=-1,s=-1,o=!1,a=!1,i=e.indexOf(Ie),l=0;for(;l<t;){let p=e.indexOf(dr,l),f=p===-1?t:p;if(f>l&&e[f-1]===Ie&&f--,f===l)break;if(i!==-1&&i<l&&(i=e.indexOf(Ie,l)),i!==-1&&i<f)return{ok:!1,reason:"malformed"};if(e[l]===pr||e[l]===mr)a&&(s=f,o=!0);else{let y=Vn(e,l,f);a=y!==-1,a&&(r++,n=y,s=f,o=!1)}l=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,s);if(o){d=e.slice(n,s);let p=0;for(let m=0;m<d.length;m++){let f=d[m];f!==Ie&&f!==dr&&(d[p++]=f)}d=d.subarray(0,p)}let u=Wn(new TextDecoder().decode(d));return u===null?{ok:!1,reason:"malformed"}:{ok:!0,addrSpec:u}}c(yr,"readMimeFromAddrSpec");function Wn(e){let t=!1,r=!1,n=-1,s=-1,o=-1;for(let i=0;i<e.length;i++){let l=e[i];if(t){r?r=!1:l==="\\"?r=!0:l==='"'&&(t=!1);continue}switch(l){case'"':if(n!==-1)return null;t=!0;break;case"<":if(n!==-1)return null;n=i;break;case">":if(n===-1||s!==-1)return null;s=i;break;case"@":o===-1&&(o=i);break;case",":case";":case":":case"(":case")":case"[":case"]":case"\\":return null;default:break}}if(t)return null;let a;if(n===-1)a=e.trim();else{if(s===-1||e.slice(s+1).trim().length!==0||o!==-1&&o<n)return null;a=e.slice(n+1,s)}return/^[\x21-\x7e]+$/.test(a)?a:null}c(Wn,"singleMailboxAddrSpec");nt.post("/send",async e=>{let t=sr(On),r=e.get("projectId"),n=e.get("body"),s=h(n.from),o=h(n.mimeBase64),a=h(n.requestId),i=a===null?"unknown":fr(a,Fn),l=h(n.idempotencyKey);if(l!==null&&(l.length===0||l.length>128||!/^[\x20-\x7e]+$/.test(l)))return e.json({ok:!1,error:{code:"INVALID_TO",message:"invalid idempotency key"}},400);let d=l??(a&&a.length<=128&&/^[\x20-\x7e]+$/.test(a)?a:crypto.randomUUID()),u=Array.isArray(n.recipients)?n.recipients:null;if(!s||!o||!u)return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"invalid body"}},400);if(u.length>or)return e.json({ok:!1,error:{code:"INVALID_TO",message:`too many recipients (max ${or}, got ${u.length})`}},413);if(s.length>cr)return e.json({ok:!1,error:{code:"INVALID_FROM",message:`sender exceeds ${cr} characters`}},413);let p=xn(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 w of u){if(typeof w!="string")continue;if(w.length>ar)return e.json({ok:!1,error:{code:"INVALID_TO",message:`recipient exceeds ${ar} characters`}},413);let S=w.trim().toLowerCase();!S||f.has(S)||(f.add(S),m.push(S))}if(m.length===0)return e.json({ok:!1,error:{code:"INVALID_TO",message:"no recipients"}},200);if(o.length>Math.ceil(ke*4/3)+4)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${ke} bytes (base64 length ${o.length})`}},413);let y;try{y=Yn(o)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"invalid base64 mime"}},400)}if(y.byteLength>ke)return e.json({ok:!1,error:{code:"MIME_ERROR",message:`mime exceeds ${ke} bytes (got ${y.byteLength})`}},413);if(!Ln(y))return e.json({ok:!1,error:{code:"MIME_ERROR",message:"custom headers exceed the 16 KiB limit"}},413);let R=s.indexOf("@"),b=R===-1?"":s.slice(R+1).toLowerCase();if(b!==""&&b!==p)return Jn(e,r,s,b,p,m,y,i,d,t);let _=e.env.SEND_EMAIL;if(typeof _?.send!="function")return e.json({ok:!1,error:{code:"UPSTREAM_ERROR",message:"email sending is not configured"}},502);let E=s.split("@")[0]?.split("+")[0]??"";if(!/^[\x21-\x7e]+$/.test(s))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let A=s.toLowerCase();if(!$n(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 O=yr(y);if(!O.ok||O.addrSpec.toLowerCase()!==A){let w=O.ok?"the From header address does not match the envelope sender":gr[O.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${s}: ${w}`}},403)}let I;try{I=await et(e.env,{projectId:r,kind:"direct",key:d,digest:await Ze("direct",s,m,y),from:s,recipients:m,transport:"binding"},t.remainingMs(U))}catch(w){let S=w instanceof Error&&w.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:S?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:S?"idempotency key has different content":"email admission unavailable"}},S?409:503)}let T=I.recipients.filter(w=>w.state!=="reserved").map(w=>({recipient:w.recipient,ok:w.state==="provider_accepted",state:w.state,messageId:w.providerReference??void 0,error:w.state==="provider_accepted"?void 0:{code:w.errorCode??(w.state==="outcome_unknown"||w.state==="attempt_started"?"OUTCOME_UNKNOWN":w.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:w.state==="outcome_unknown"||w.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":w.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(I.replay){for(let w of I.recipients.filter(S=>S.state==="reserved"))T.push({recipient:w.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return Me(e,I.operationId,T)}let $=I.recipients.filter(w=>w.state==="reserved").map(w=>w.recipient);for(let w=0;w<$.length;w++){let S=$[w];if(t.expired(U)){let F=$.slice(w),Q=await rt(e.env,I.operationId,F,t.remainingMs());for(let ie of F)T.push({recipient:ie,ok:!1,state:Q?"cancelled":"outcome_unknown",error:Q?{code:"UPSTREAM_ERROR",message:"email batch deadline elapsed before provider submission"}:{code:"OUTCOME_UNKNOWN",message:"could not cancel unstarted email attempt"}});break}try{await tt(e.env,I.operationId,[S],t.remainingMs(U))}catch{let F=await rt(e.env,I.operationId,[S],t.remainingMs());T.push({recipient:S,ok:!1,state:F?"cancelled":"outcome_unknown",error:F?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});continue}try{let F=new Cn(s,S,qn(y)),Q=await t.run(()=>_.send(F),U),ie=typeof Q?.messageId=="string"?Q.messageId:"";try{await V(e.env,I.operationId,[S],"provider_accepted",{providerReference:ie},t.remainingMs())}catch{T.push({recipient:S,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider accepted email but outcome could not be recorded"}});continue}T.push({recipient:S,ok:!0,state:"provider_accepted",messageId:ie})}catch{try{await V(e.env,I.operationId,[S],"outcome_unknown",{errorCode:"OUTCOME_UNKNOWN"},t.remainingMs())}catch{}T.push({recipient:S,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"}})}}return hr(r,i,T),T.some(w=>!w.ok)?e.json({ok:!1,operationId:I.operationId,deliveries:T},200):e.json({ok:!0,operationId:I.operationId,ids:T.map(w=>({recipient:w.recipient,messageId:w.messageId,state:"provider_accepted"}))})});var ur=64*1024;async function zn(e,t=3e4){let r=new AbortController,n=Date.now()+Math.min(3e4,t),s=JSON.stringify({from:e.from,recipients:e.recipients,mime_message:e.mimeMessage}),o=c(async p=>{let m=n-Date.now();if(m<=0)throw r.abort(),new Error("email sending request timed out");let f=p(),y;try{return await Promise.race([f,new Promise((R,b)=>{y=setTimeout(()=>{r.abort(),b(new Error("email sending request timed out"))},m)})])}finally{y!==void 0&&clearTimeout(y)}},"beforeDeadline"),a=await o(()=>fetch(`https://api.cloudflare.com/client/v4/accounts/${e.accountId}/email/sending/send_raw`,{method:"POST",headers:{authorization:`Bearer ${e.bearer}`,"content-type":"application/json"},body:s,signal:r.signal}));if(!a.ok)return a.body?.cancel().catch(()=>{}),{ok:!1,status:a.status};let i=a.headers.get("content-length");if(i!==null&&(!/^\d+$/.test(i)||Number(i)>ur))throw a.body?.cancel().catch(()=>{}),new Error("email sending API response too large");let l=a.body?.getReader();if(!l)throw new Error("email sending API response unreadable");let d=new Uint8Array(ur),u=0;try{for(;;){let p=await o(()=>l.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(i!==null&&u!==Number(i))throw new Error("email sending API response length mismatch");return{ok:!0,data:JSON.parse(new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(d.subarray(0,u)))}}finally{l.cancel().catch(()=>{});try{l.releaseLock()}catch{}}}c(zn,"requestSendRaw");function Pe(e){if(!Array.isArray(e))return null;let t=new Set;for(let r of e){if(typeof r!="string")return null;t.add(r.toLowerCase())}return t}c(Pe,"readSendRawAddressList");function Gn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,r=Pe(t.delivered),n=Pe(t.permanent_bounces),s=Pe(t.queued),o=Pe(t.suppressed_recipients);return!r||!n||!s||!o||typeof t.message_id!="string"||t.message_id===""?null:{delivered:r,messageId:t.message_id,permanentBounces:n,queued:s,suppressedRecipients:o}}c(Gn,"parseSendRawResult");function Kn(e,t){let r=t.toLowerCase(),n=[e.delivered.has(r),e.queued.has(r),e.permanentBounces.has(r),e.suppressedRecipients.has(r)];return n.filter(Boolean).length!==1?"outcome_unknown":n[0]||n[1]?"provider_accepted":n[2]?"permanent_bounce":"suppressed"}c(Kn,"classifySendRawRecipient");async function Jn(e,t,r,n,s,o,a,i,l,d){if(!/^[\x21-\x7e]+$/.test(r))return e.json({ok:!1,error:{code:"INVALID_FROM",message:"from address must be printable ASCII"}},403);let u=r.toLowerCase(),p=yr(a);if(!p.ok||p.addrSpec.toLowerCase()!==u){let g=p.ok?"the From header address does not match the envelope sender":gr[p.reason];return e.json({ok:!1,error:{code:"INVALID_FROM",message:`mime From must be the envelope sender ${r}: ${g}`}},403)}let m;try{m=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}).decode(a)}catch{return e.json({ok:!1,error:{code:"MIME_ERROR",message:"mime must be valid UTF-8"}},400)}let f;try{f=await et(e.env,{projectId:t,kind:"direct",key:l,digest:await Ze("direct",r,o,a),from:r,recipients:o,transport:"send_raw"},d.remainingMs(U))}catch(g){let v=g instanceof Error&&g.message==="IDEMPOTENCY_CONFLICT";return e.json({ok:!1,error:{code:v?"IDEMPOTENCY_CONFLICT":"UPSTREAM_ERROR",message:v?"idempotency key has different content":"email admission unavailable"}},v?409:503)}let y=f.recipients.filter(g=>g.state!=="reserved").map(g=>({recipient:g.recipient,ok:g.state==="provider_accepted",state:g.state,messageId:g.providerReference??void 0,error:g.state==="provider_accepted"?void 0:{code:g.errorCode??(g.state==="outcome_unknown"||g.state==="attempt_started"?"OUTCOME_UNKNOWN":g.state==="cancelled"?"UPSTREAM_ERROR":"UNVERIFIED_DESTINATION"),message:g.state==="outcome_unknown"||g.state==="attempt_started"?"provider outcome unknown; inspect email logs before retrying":g.state==="cancelled"?"email attempt was cancelled before provider submission":"recipient was not admitted"}}));if(f.replay){for(let g of f.recipients.filter(v=>v.state==="reserved"))y.push({recipient:g.recipient,ok:!1,state:"reserved",error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved; inspect email logs before retrying"}});return Me(e,f.operationId,y)}if(o=f.recipients.filter(g=>g.state==="reserved").map(g=>g.recipient),o.length===0)return Me(e,f.operationId,y);let R=await rr(e.env,n,t,d.remainingMs(U));if(!R)return await V(e.env,f.operationId,o,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"could not lease the domain credential"}},502);if(f.accountId!==R.accountId)return await V(e.env,f.operationId,o,"cancelled",{},d.remainingMs()).catch(()=>{}),e.json({ok:!1,operationId:f.operationId,error:{code:"UPSTREAM_ERROR",message:"email domain changed during admission"}},503);try{await tt(e.env,f.operationId,o,d.remainingMs(U))}catch{let g=await rt(e.env,f.operationId,o,d.remainingMs());for(let v of o)y.push({recipient:v,ok:!1,state:g?"cancelled":"outcome_unknown",error:g?{code:"UPSTREAM_ERROR",message:"email attempt did not start; reservation cancelled"}:{code:"OUTCOME_UNKNOWN",message:"could not confirm email attempt status"}});return Me(e,f.operationId,y)}let b=null,_="failed",E=null,A=null;try{A=await zn({accountId:R.accountId,bearer:tr(R),from:r,recipients:o,mimeMessage:m},d.remainingMs(U))}catch{b={code:"UPSTREAM_ERROR",message:"email sending request failed"},_="outcome_unknown"}if(A)if(!A.ok)b={code:A.status===429?"QUOTA_EXCEEDED":"UPSTREAM_ERROR",message:`email sending API returned ${A.status}`},_=A.status>=500||A.status===408?"outcome_unknown":"failed";else{let g=A.data,v=typeof g=="object"&&g!==null?g.success:void 0;v===!1?b={code:"UPSTREAM_ERROR",message:"email sending API refused the message"}:v!==!0?(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},_="outcome_unknown"):(E=Gn(g.result),E||(b={code:"OUTCOME_UNKNOWN",message:"email sending API response invalid"},_="outcome_unknown"))}for(let g of o){if(b){y.push({recipient:g,ok:!1,state:_,error:b});continue}let v=Kn(E,g);v==="permanent_bounce"?y.push({recipient:g,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${g}' permanently bounced`}}):v==="suppressed"?y.push({recipient:g,ok:!1,state:"failed",error:{code:"UNVERIFIED_DESTINATION",message:`recipient '${g}' is on the suppression list`}}):v==="outcome_unknown"?y.push({recipient:g,ok:!1,state:"outcome_unknown",error:{code:"OUTCOME_UNKNOWN",message:"email sending API did not classify the recipient"}}):y.push({recipient:g,ok:!0,state:"provider_accepted",messageId:E.messageId})}for(let g of y.filter(v=>f.recipients.some(O=>O.recipient===v.recipient&&O.state==="reserved")))try{await V(e.env,f.operationId,[g.recipient],g.ok?"provider_accepted":g.state==="outcome_unknown"?"outcome_unknown":"failed",{providerReference:g.messageId,errorCode:g.ok?void 0:g.state==="outcome_unknown"?"OUTCOME_UNKNOWN":b?.code??g.error?.code},d.remainingMs()),g.state=g.ok?"provider_accepted":g.state==="outcome_unknown"?"outcome_unknown":"failed",g.state==="outcome_unknown"&&!g.ok&&(g.error={code:"OUTCOME_UNKNOWN",message:"provider outcome unknown; inspect email logs before retrying"})}catch{g.ok=!1,g.state="outcome_unknown",g.error={code:"OUTCOME_UNKNOWN",message:"provider outcome could not be recorded"}}return hr(t,i,y),y.some(g=>!g.ok)?e.json({ok:!1,operationId:f.operationId,deliveries:y},200):e.json({ok:!0,operationId:f.operationId,ids:y.map(g=>({recipient:g.recipient,messageId:g.messageId,state:"provider_accepted"}))})}c(Jn,"sendViaCustomDomain");async function rt(e,t,r,n){try{let s=await V(e,t,r,"cancelled",{},n);return r.every(o=>s.recipients.some(a=>a.recipient===o&&a.state==="cancelled"))}catch{return!1}}c(rt,"cancelUnstartedRecipients");function Me(e,t,r){return r.length===0?e.json({ok:!1,operationId:t,error:{code:"OUTCOME_UNKNOWN",message:"email action remains reserved"}},200):r.some(n=>!n.ok)?e.json({ok:!1,operationId:t,deliveries:r},200):e.json({ok:!0,operationId:t,ids:r.map(n=>({recipient:n.recipient,messageId:n.messageId??"",state:n.state}))},200)}c(Me,"emailActionResponse");function hr(e,t,r){for(let n of r){let s=n.ok?"sent":n.error?.code??"unknown_error",o=n.messageId??"";console.log(`[email-log] ${e} ${t} ${fr(n.recipient,320)} ${s} ${o} @${Date.now()}`)}}c(hr,"logSend");function Yn(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}c(Yn,"base64Decode");function br(e,t,r){let n=e.getReader(),s=!1,o,a,i=c(()=>{s=!0,o!==void 0&&clearTimeout(o),r?.removeEventListener("abort",d)},"cleanup"),l=c(()=>{s||(i(),a.error(new Error("Authentication expired or was revoked. Sign in again.")),n.cancel().catch(()=>{}))},"stop"),d=c(()=>l(),"abort"),u=c(async()=>{if(s)return!1;try{if(await t())return!s}catch{}return l(),!1},"check"),p=c(()=>{o=setTimeout(async()=>{await u()&&p()},15e3)},"schedule");return new ReadableStream({start(m){a=m,r?.addEventListener("abort",d,{once:!0}),r?.aborted?l():p()},async pull(m){try{let f=await n.read();if(s)return;f.done?(i(),m.close()):await u()&&m.enqueue(f.value)}catch(f){s||(i(),m.error(f),n.cancel().catch(()=>{}))}},async cancel(m){i(),await n.cancel(m)}},{highWaterMark:0})}c(br,"guardHumanStream");var Ce="https://api.cloudflare.com/client/v4",X=new M;X.post("/get",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/kv/get",t,{fallbackOnDispatchError:!0});if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"kv",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${Ce}/accounts/${e.env.CF_ACCOUNT_ID}/storage/kv/namespaces/${a}/values/${encodeURIComponent(s)}`,{headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`}});if(i.status===404)return e.json(null);if(!i.ok)return e.json({error:"KV get failed",status:i.status},502);let l=h(t.type)??"text";return l==="json"?e.json(await i.json()):l==="arrayBuffer"?new Response(await i.arrayBuffer(),{headers:{"content-type":"application/octet-stream"}}):l==="stream"?new Response(i.body,{headers:{"content-type":"application/octet-stream"}}):e.json(await i.text())});X.post("/put",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/kv/put",t);if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"kv",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=new URLSearchParams;K(t.expiration)&&i.set("expiration",String(t.expiration)),K(t.expiration_ttl)&&i.set("expiration_ttl",String(t.expiration_ttl));let l=i.toString()?`?${i.toString()}`:"",d,u="text/plain";if(t.base64===!0&&typeof t.value=="string"){let m=atob(t.value),f=new Uint8Array(m.length);for(let y=0;y<m.length;y++)f[y]=m.charCodeAt(y);d=f.buffer,u="application/octet-stream"}else d=typeof t.value=="string"?t.value:JSON.stringify(t.value);let p=await fetch(`${Ce}/accounts/${e.env.CF_ACCOUNT_ID}/storage/kv/namespaces/${a}/values/${encodeURIComponent(s)}${l}`,{method:"PUT",headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`,"Content-Type":u},body:d});return p.ok?e.json({success:!0}):e.json({error:"KV put failed",status:p.status},502)});X.post("/delete",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/kv/delete",t);if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"kv",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${Ce}/accounts/${e.env.CF_ACCOUNT_ID}/storage/kv/namespaces/${a}/values/${encodeURIComponent(s)}`,{method:"DELETE",headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`}});return!i.ok&&i.status!==404?e.json({error:"KV delete failed",status:i.status},502):e.json({success:!0})});X.post("/list",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding);if(!n)return e.json({error:"binding required"},400);let s=await C(e.env,r,"/kv/list",t,{fallbackOnDispatchError:!0});if(s)return s;let o;try{o=await N(e.env.API,e.env.JWT_SECRET,r,"kv",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let a=new URLSearchParams,i=h(t.prefix);i&&a.set("prefix",i),K(t.limit)&&a.set("limit",String(t.limit));let l=h(t.cursor);l&&a.set("cursor",l);let d=a.toString()?`?${a.toString()}`:"",u=await fetch(`${Ce}/accounts/${e.env.CF_ACCOUNT_ID}/storage/kv/namespaces/${o}/keys${d}`,{headers:{Authorization:`Bearer ${e.env.CF_API_TOKEN}`}});if(!u.ok)return e.json({error:"KV list failed",status:u.status},502);let p=await u.json();return e.json({keys:p.result??[],list_complete:!p.result_info?.cursor,cursor:p.result_info?.cursor??null})});var wr="__void/platform/disabled/v1",Rr="disabled";var ne="https://api.cloudflare.com/client/v4",W=new M;function se(e){return{Authorization:`Bearer ${e}`}}c(se,"cfHeaders");W.post("/get",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/r2/get",t,{fallbackOnDispatchError:!0});if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${a}/objects/${encodeURIComponent(s)}`,{headers:se(e.env.CF_API_TOKEN)});if(i.status===404)return e.json(null);if(!i.ok)return e.json({error:"R2 get failed",status:i.status},502);let l=new Headers;return l.set("content-type",i.headers.get("content-type")??"application/octet-stream"),i.headers.has("content-length")&&l.set("content-length",i.headers.get("content-length")),i.headers.has("etag")&&l.set("etag",i.headers.get("etag")),i.headers.has("last-modified")&&l.set("last-modified",i.headers.get("last-modified")),new Response(i.body,{headers:l})});W.on("POST",["/put","/put-conditional"],async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key),o=h(t.base64);if(!n||!s)return e.json({error:"binding and key required"},400);let a=t.onlyIf!==void 0||e.req.path.endsWith("/put-conditional"),i=await C(e.env,r,a?"/r2/put-conditional":"/r2/put",t);if(i)return i;if(a)return e.json({error:"R2 conditional writes require an active deployment with the current Void remote-binding handler. Update your Void platform and redeploy the project."},501);let l;try{l=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let d=o?Uint8Array.from(atob(o),p=>p.charCodeAt(0)):new TextEncoder().encode(t.value??""),u=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${l}/objects/${encodeURIComponent(s)}`,{method:"PUT",headers:{...se(e.env.CF_API_TOKEN),"Content-Type":h(t.contentType)??"application/octet-stream"},body:d});return u.ok?e.json({success:!0}):e.json({error:"R2 put failed",status:u.status},502)});W.post("/delete",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding);if(!n)return e.json({error:"binding required"},400);let s=Array.isArray(t.keys)&&t.keys.every(i=>typeof i=="string")?t.keys:typeof t.key=="string"?[t.key]:[];if(s.length===0)return e.json({error:"key or keys required"},400);let o=await C(e.env,r,"/r2/delete",t);if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}for(let i of s){let l=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${a}/objects/${encodeURIComponent(i)}`,{method:"DELETE",headers:se(e.env.CF_API_TOKEN)});if(!l.ok&&l.status!==404)return e.json({error:"R2 delete failed",status:l.status},502)}return e.json({success:!0})});W.post("/list",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding);if(!n)return e.json({error:"binding required"},400);let s=await C(e.env,r,"/r2/list",t,{fallbackOnDispatchError:!0});if(s)return s;let o;try{o=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let a=new URLSearchParams,i=h(t.prefix);i&&a.set("prefix",i),K(t.limit)&&a.set("per_page",String(t.limit));let l=h(t.cursor);l&&a.set("cursor",l);let d=h(t.delimiter);d&&a.set("delimiter",d);let u=a.toString()?`?${a.toString()}`:"",p=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${o}/objects${u}`,{headers:se(e.env.CF_API_TOKEN)});if(!p.ok)return e.json({error:"R2 list failed",status:p.status},502);let m=await p.json();return e.json({objects:(m.result??[]).map(f=>({key:f.key,size:f.size,lastModified:f.last_modified??""})),truncated:!!m.result_info?.cursor,cursor:m.result_info?.cursor??null})});W.post("/head",async e=>{let t=e.get("body"),r=e.get("projectId"),n=h(t.binding),s=h(t.key);if(!n||!s)return e.json({error:"binding and key required"},400);let o=await C(e.env,r,"/r2/head",t,{fallbackOnDispatchError:!0});if(o)return o;let a;try{a=await N(e.env.API,e.env.JWT_SECRET,r,"r2",n)}catch{return e.json({error:`unknown binding "${n}"`},404)}let i=await fetch(`${ne}/accounts/${e.env.CF_ACCOUNT_ID}/r2/buckets/${a}/objects/${encodeURIComponent(s)}`,{method:"HEAD",headers:se(e.env.CF_API_TOKEN)});return i.status===404?e.json(null):i.ok?e.json({key:s,size:parseInt(i.headers.get("content-length")??"0"),etag:i.headers.get("etag")??"",lastModified:i.headers.get("last-modified")??"",contentType:i.headers.get("content-type")??"application/octet-stream"}):e.json({error:"R2 head failed",status:i.status},502)});var Xn=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!1}),Qn=1024*1024,Zn=8*1024*1024,D=class extends Error{constructor(r,n){super(r);this.status=n;this.name="RequestBodyError"}status;static{c(this,"RequestBodyError")}};function Er(e){switch(e){case"/ai/run":case"/ai/provider":case"/ai/toMarkdown":case"/kv/put":case"/r2/put":case"/r2/put-conditional":return Zn;default:return Qn}}c(Er,"requestBodyMaxBytes");async function es(e,t){let r=e-Date.now();if(r<=0)throw new D("request body timeout",408);let n;return Promise.race([t(),new Promise((s,o)=>{n=setTimeout(()=>o(new D("request body timeout",408)),r)})]).finally(()=>{n!==void 0&&clearTimeout(n)})}c(es,"beforeDeadline");async function st(e,t){let r=e.headers.get("content-length");if(r!==null&&/^\d+$/.test(r)&&Number(r)>t)throw e.body?.cancel().catch(()=>{}),new D("request body too large",413);if(e.headers.has("content-encoding")||!e.body||r!==null&&!/^\d+$/.test(r))throw e.body?.cancel().catch(()=>{}),new D("invalid request body",400);let n=r===null?null:Number(r),s=e.body.getReader(),o=new Uint8Array(Math.min(1024,t)),a=Date.now()+5e3,i=0;try{for(;;){let l=await es(a,()=>s.read());if(l.done)break;let d=i+l.value.byteLength;if(d>t)throw new D("request body too large",413);if(d>o.byteLength){let u=new Uint8Array(Math.min(t,Math.max(d,o.byteLength*2)));u.set(o.subarray(0,i)),o=u}o.set(l.value,i),i=d}}finally{s.cancel().catch(()=>{}),s.releaseLock()}if(i===0||n!==null&&i!==n)throw new D("invalid request body length",400);return JSON.parse(Xn.decode(o.subarray(0,i)))}c(st,"readRequestJson");var it=new M;it.post("/",async e=>{let t=e.get("projectId"),r=e.get("body"),n=await e.env.API.fetch(`https://api/internal/revalidate/${t}`,{method:"POST",headers:{"content-type":"application/json","x-void-internal":r.aiToken},body:JSON.stringify({paths:r.paths,all:r.all})});return new Response(n.body,{status:n.status,headers:n.headers})});var P=new M;P.use("/*",async(e,t)=>{let r=e.env.PLATFORM_HEALTH_PROBE_TOKEN;if(!(r!==void 0&&r!==""&&e.req.path==="/health"&&e.req.header("X-Void-Platform-Probe")===r)&&(e.env.PLATFORM_TRAFFIC_STATE==="staging"||e.env.PLATFORM_TRAFFIC_STATE==="sandbox-drain"||e.env.PLATFORM_INSTALLATION_ID&&await e.env.ROUTING.get(wr)===Rr))return e.json({error:"Platform disabled"},503);await t()});P.use("/*",xt({origin:"*",allowMethods:["POST","OPTIONS"],allowHeaders:["content-type","authorization"]}));P.get("/health",e=>e.json({ok:!0,bindings:{ai:!!e.env.AI,kv:!!e.env.ROUTING,jwt:!!e.env.JWT_SECRET,api:!!e.env.API,sendEmail:!!e.env.SEND_EMAIL,emailDomain:!!e.env.EMAIL_SENDER_DOMAIN}}));P.all("/*",async(e,t)=>{if(e.req.method!=="POST")return e.json({error:"method not allowed"},405);await t()});async function ts(e,t){let r=await crypto.subtle.importKey("raw",new TextEncoder().encode(t),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),n=new Uint8Array(await crypto.subtle.sign("HMAC",r,new TextEncoder().encode(e))),s="";for(let o of n)s+=String.fromCharCode(o);return btoa(s).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}c(ts,"hmacSign");P.post("/email/verify-receipt",async e=>{let t;try{t=await st(e.req.raw,2*1024)}catch{return e.json({valid:!1},400)}if(!t||typeof t!="object")return e.json({valid:!1},400);let r=t;if(typeof r.projectId!="string"||r.projectId.length>128||typeof r.deploymentId!="string"||r.deploymentId.length>128||typeof r.recipient!="string"||r.recipient.length>320||typeof r.receipt!="string"||r.receipt.length>1536)return e.json({valid:!1},400);let n=await ts(r.projectId,e.env.JWT_SECRET);if(e.req.header("x-void-internal")!==n)return e.json({valid:!1},403);if(!e.env.EMAIL_SIGNING_SECRET)return e.json({valid:!1},503);let s=await lt(r.receipt,e.env.EMAIL_SIGNING_SECRET,{projectId:r.projectId,deploymentId:r.deploymentId,recipient:r.recipient});return e.json({valid:s!==null,receiptId:s?.receiptId})});P.post("/email/relay",e=>e.json({error:"not found"},404));P.post("/*",async(e,t)=>{let r=new URL(e.req.url).pathname,n;try{let a=r==="/email"||r.startsWith("/email/")?8388608:Er(r),i=await st(e.req.raw,a);if(!j(i))return e.json({error:"invalid JSON body"},400);n=i}catch(a){return r!=="/email"&&!r.startsWith("/email/")&&a instanceof D?e.json({error:a.message},a.status):e.json({error:"invalid JSON body"},400)}e.set("body",n);let s,o=e.req.header("authorization");if(o?.startsWith("Bearer ")){let a=o.slice(7),i=await ss(a,e.env.JWT_SECRET);if(!i)return e.json({error:"invalid or expired token",message:"This proxy credential is invalid or expired. Sign in to the connected platform again for remote development, or restart the build to obtain a fresh prerender token."},401);let l=h(n.projectId);if(!l)return e.json({error:"projectId required"},400);if(i.aud==="prerender"){if(!i.project||i.project!==l)return e.json({error:"forbidden",message:"This prerender token does not match the requested project. Restart the build with a prerender token issued for the selected project."},403);if(!await Yt(e.env.API,e.env.JWT_SECRET,l,i.sub,{...i.build?{buildId:i.build}:{},...i.credential?{credentialId:i.credential}:{}}))return e.json({error:i.credential?"prerender token credential is no longer active":i.build?"prerender token build is no longer active":"prerender token authority is no longer active",message:i.credential?"The deploy credential used for prerendering is no longer authorized. Ask the project owner for an active deploy credential, then restart the build.":i.build?"This build is no longer authorized to prerender. Start a new build to obtain a fresh prerender token.":"This prerender token is no longer authorized. Confirm your project access with a project admin or owner, then restart the build to obtain a fresh token."},403)}else{let d=c(()=>Jt(e.env.API,e.env.JWT_SECRET,l,i.sub,a,e.req.header("Cf-Access-Jwt-Assertion"),new URL(e.req.url).origin),"checkOwner");if(s=c(async()=>i.exp>Date.now()/1e3&&await d(),"revalidateHuman"),!await s())return e.json({error:"forbidden",message:"Remote access could not be authorized. Check the selected platform and project, then ask a project admin or owner to confirm your access. If your access is correct, retry shortly."},403)}e.set("projectId",l)}else{let a=h(n.projectId),i=h(n.aiToken);if(!a||!i)return e.json({error:"projectId and aiToken required"},400);if(!await ns(a,i,e.env.JWT_SECRET))return e.json({error:"invalid project token"},403);e.set("projectId",a)}await t(),s&&e.res.body&&(e.res.headers.get("content-type")?.includes("text/event-stream")||r.startsWith("/ai/")||r==="/r2/get")&&(e.res=new Response(br(e.res.body,s,e.req.raw.signal),e.res))});P.post("/ai/*",async(e,t)=>{if(await e.env.ROUTING.get(`ai-block:${e.get("projectId")}`,{cacheTtl:60}))return xe({code:"usage_limit",resource:"ai",reason:"monthly_quota",message:"AI usage limit exceeded"});await t()});P.post("/email/*",async(e,t)=>{if(!Bt(e.env.PLATFORM_CAPABILITIES,"email"))return e.json({error:"platform capability unavailable",capability:"email",message:"This Void platform does not enable email."},501);await t()});P.route("/ai",J);P.route("/d1",Re);P.route("/kv",X);P.route("/r2",W);P.route("/revalidate",it);P.route("/email",nt);var dd={fetch:P.fetch},at=new TextEncoder,rs=new TextDecoder,Oe,Ar;async function _r(e){return Oe&&Ar===e||(Oe=await crypto.subtle.importKey("raw",at.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["verify"]),Ar=e),Oe}c(_r,"getVerifyKey");async function ns(e,t,r){try{let n=await _r(r),s=ot(t);return crypto.subtle.verify("HMAC",n,s.buffer,at.encode(e))}catch{return!1}}c(ns,"verifyHmac");function ot(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=atob(t);return Uint8Array.from(r,n=>n.charCodeAt(0))}c(ot,"base64urlDecode");async function ss(e,t){let r=e.split(".");if(r.length!==3)return null;let[n,s,o]=r;try{let a=await _r(t),i=ot(o);if(!await crypto.subtle.verify("HMAC",a,i.buffer,at.encode(`${n}.${s}`)))return null;let d=JSON.parse(rs.decode(ot(s))),u=Math.floor(Date.now()/1e3);return d.exp<=u||d.aud!=="api"&&d.aud!=="prerender"?null:d}catch{return null}}c(ss,"verifyJwt");export{dd as default};
|