@authhero/cloudflare-adapter 2.37.2 → 2.37.3
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.
|
@@ -17,7 +17,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
|
|
|
17
17
|
WHERE index1 = ${M(t)}
|
|
18
18
|
AND blob1 = ${M(n)}
|
|
19
19
|
LIMIT 1
|
|
20
|
-
`);return r.length===0||!r[0]?null:P(r[0])}}function me(e){let t={
|
|
20
|
+
`);return r.length===0||!r[0]?null:P(r[0])}}function me(e){return e.replace(/\\([\\"+\-!(){}[\]^~*?:/&|])/g,`$1`)}function he(e){let t=[],n=``,r=!1;for(let i=0;i<e.length;i++){let a=e[i];a===`"`?(r=!r,n+=a):a===` `&&!r?(n.trim()&&t.push(n.trim()),n=``):n+=a}return n.trim()&&t.push(n.trim()),t}function F(e){let t=e;return t.startsWith(`"`)&&t.endsWith(`"`)&&t.length>1&&(t=t.slice(1,-1)),me(t)}function ge(e){let t={},n=[];for(let r of he(e)){if(r===`OR`||r===`AND`)continue;let e=r.match(/^(\w+):([\s\S]*)$/);if(e){let n=e[1],r=F(e[2]);t[n]||(t[n]=[]),t[n].push(r)}else{let e=F(r);e&&n.push(e)}}return{fields:t,terms:n}}function I(e){return{log_id:`blob1`,tenant_id:`blob2`,type:`blob3`,description:`blob4`,ip:`blob5`,user_agent:`blob6`,user_id:`blob7`,user_name:`blob8`,connection:`blob9`,connection_id:`blob10`,client_id:`blob11`,client_name:`blob12`,audience:`blob13`,scope:`blob14`,strategy:`blob15`,strategy_type:`blob16`,hostname:`blob17`}[e]||null}function _e(e){let t=[];for(let[n,r]of Object.entries(e)){let e=r.filter(e=>e!==``);if(e.length===0)continue;if(n===`success`){let n=[],r=new Set;for(let t of e)r.has(t)||(r.add(t),t===`true`?n.push(`blob3 LIKE 's%'`):t===`false`&&n.push(`blob3 LIKE 'f%'`));n.length>0&&t.push(`(${n.join(` OR `)})`);continue}let i=I(n);if(i)if(e.length===1)t.push(`${i} = ${M(e[0])}`);else{let n=e.map(e=>M(e)).join(`, `);t.push(`${i} IN (${n})`)}}return t}function ve(e){return e.filter(e=>e!==``).map(e=>{let t=M(e),n=M(`%${e}%`);return`(blob7 = ${t} OR blob5 LIKE ${n} OR blob4 LIKE ${n})`})}function ye(e){return e===`date`?`double2`:I(e)||`timestamp`}function be(e){return async(t,n={})=>{let{page:r=0,per_page:i=50,include_totals:a=!1,sort:o,q:s,from_date:c,to_date:l}=n,u=e.dataset||`authhero_logs`,d=[`index1 = ${M(t)}`];if(s){let{fields:e,terms:t}=ge(s);d.push(..._e(e)),d.push(...ve(t))}typeof c==`number`&&Number.isFinite(c)&&d.push(`double2 >= ${Math.floor(c)*1e3}`),typeof l==`number`&&Number.isFinite(l)&&d.push(`double2 <= ${Math.floor(l)*1e3}`);let f=d.join(` AND `),p=`ORDER BY timestamp DESC`;o&&o.sort_by&&(p=`ORDER BY ${ye(o.sort_by)} ${o.sort_order===`asc`?`ASC`:`DESC`}`);let m=r*i,h=`LIMIT ${i} OFFSET ${m}`,g=(await j(e,`
|
|
21
21
|
SELECT *
|
|
22
22
|
FROM ${N(u)}
|
|
23
23
|
WHERE ${f}
|
|
@@ -27,12 +27,12 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
|
|
|
27
27
|
SELECT count() as count
|
|
28
28
|
FROM ${N(u)}
|
|
29
29
|
WHERE ${f}
|
|
30
|
-
`;try{let t=(await j(e,_))[0]?.count||0;return{logs:g,start:m,limit:i,length:Number(t)}}catch{return{logs:g,start:m,limit:i,length:g.length}}}}var
|
|
30
|
+
`;try{let t=(await j(e,_))[0]?.count||0;return{logs:g,start:m,limit:i,length:Number(t)}}catch{return{logs:g,start:m,limit:i,length:g.length}}}}var L=[`s`],xe=[`pwd_leak`];function R(e){return`${e.slice(0,4)}-${e.slice(4,6)}-${e.slice(6,8)}`}function z(e){return e.toISOString().split(`T`)[0]}function Se(e){let t=e.dataset||`authhero_logs`;return{async getDaily(n,r={}){let{from:i,to:a}=r,o=new Date,s=new Date(o);s.setDate(s.getDate()-30);let c=i?R(i):z(s),l=a?R(a):z(o),u=new Date(`${c}T00:00:00Z`).getTime(),d=new Date(`${l}T23:59:59.999Z`).getTime();return(await j(e,`
|
|
31
31
|
SELECT
|
|
32
32
|
toDate(toDateTime(double2 / 1000)) AS date,
|
|
33
|
-
SUM(CASE WHEN blob3 IN (${
|
|
33
|
+
SUM(CASE WHEN blob3 IN (${L.map(e=>M(e)).join(`, `)}) THEN 1 ELSE 0 END) AS logins,
|
|
34
34
|
SUM(CASE WHEN blob3 = 'ss' THEN 1 ELSE 0 END) AS signups,
|
|
35
|
-
SUM(CASE WHEN blob3 IN (${
|
|
35
|
+
SUM(CASE WHEN blob3 IN (${xe.map(e=>M(e)).join(`, `)}) THEN 1 ELSE 0 END) AS leaked_passwords,
|
|
36
36
|
MIN(double2) AS first_event,
|
|
37
37
|
MAX(double2) AS last_event
|
|
38
38
|
FROM "${t}"
|
|
@@ -41,7 +41,7 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
|
|
|
41
41
|
AND double2 <= ${d}
|
|
42
42
|
GROUP BY date
|
|
43
43
|
ORDER BY date ASC
|
|
44
|
-
`)).map(e=>({date:String(e.date),logins:Number(e.logins)||0,signups:Number(e.signups)||0,leaked_passwords:Number(e.leaked_passwords)||0,created_at:e.first_event?new Date(Number(e.first_event)).toISOString():new Date().toISOString(),updated_at:e.last_event?new Date(Number(e.last_event)).toISOString():new Date().toISOString()}))},async getActiveUsers(n){let r=new Date;r.setDate(r.getDate()-30);let i=r.getTime(),a=
|
|
44
|
+
`)).map(e=>({date:String(e.date),logins:Number(e.logins)||0,signups:Number(e.signups)||0,leaked_passwords:Number(e.leaked_passwords)||0,created_at:e.first_event?new Date(Number(e.first_event)).toISOString():new Date().toISOString(),updated_at:e.last_event?new Date(Number(e.last_event)).toISOString():new Date().toISOString()}))},async getActiveUsers(n){let r=new Date;r.setDate(r.getDate()-30);let i=r.getTime(),a=L.map(e=>M(e)).join(`, `),o=(await j(e,`
|
|
45
45
|
SELECT COUNT(DISTINCT blob7) AS count
|
|
46
46
|
FROM "${t}"
|
|
47
47
|
WHERE index1 = ${M(n)}
|
|
@@ -49,21 +49,21 @@ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{val
|
|
|
49
49
|
AND blob3 IN (${a})
|
|
50
50
|
AND blob7 IS NOT NULL
|
|
51
51
|
AND blob7 != ''
|
|
52
|
-
`))[0];return o&&o.count!==void 0&&Number(o.count)||0}}}var
|
|
52
|
+
`))[0];return o&&o.count!==void 0&&Number(o.count)||0}}}var Ce={"active-users":[`s`,`seacft`],logins:[`s`,`f`,`fp`],signups:[`ss`,`fs`],"refresh-tokens":[`seacft`,`fertft`],sessions:[`slo`],logouts:[`slo`,`flo`],"password-changes":[`scp`,`fcp`,`scpr`,`fcpr`],mfa:[`gd_auth_succeed`,`gd_auth_failed`,`gd_auth_rejected`],"email-verifications":[`sv`,`fv`,`svr`,`fvr`],"codes-sent":[`cls`,`cs`]},we={connection:`blob9`,client_id:`blob11`,user_type:`blob16`,event:`blob3`},Te={connection:`blob9`,client_id:`blob11`,user_type:`blob16`,user_id:`blob7`},Ee={"active-users":{expr:`count(DISTINCT blob7)`,alias:`active_users`,type:`UInt64`},logins:{expr:`count()`,alias:`logins`,type:`UInt64`},signups:{expr:`count()`,alias:`signups`,type:`UInt64`},"refresh-tokens":{expr:`count()`,alias:`refresh_tokens`,type:`UInt64`},sessions:{expr:`count()`,alias:`sessions`,type:`UInt64`},logouts:{expr:`count()`,alias:`logouts`,type:`UInt64`},"password-changes":{expr:`count()`,alias:`password_changes`,type:`UInt64`},mfa:{expr:`count()`,alias:`mfa`,type:`UInt64`},"email-verifications":{expr:`count()`,alias:`email_verifications`,type:`UInt64`},"codes-sent":{expr:`count()`,alias:`codes_sent`,type:`UInt64`}};function De(e,t){let n=`toDateTime(intDiv(double2, 1000), ${M(t)})`;switch(e){case`hour`:return`toStartOfHour(${n})`;case`week`:return`toStartOfWeek(${n})`;case`month`:return`toStartOfMonth(${n})`;default:return`toStartOfDay(${n})`}}function Oe(e){return e===`hour`?`DateTime`:`Date`}function ke(e,t,n){let r=new Date(e.from).getTime(),i=new Date(e.to).getTime(),a=n.map(e=>M(e)).join(`, `),o=[`index1 = ${M(t)}`,`double2 >= ${r}`,`double2 < ${i}`,`blob3 IN (${a})`];for(let[t,n]of Object.entries(Te)){let r=e.filters[t];if(r&&r.length>0){let e=r.map(e=>M(e)).join(`, `);o.push(`${n} IN (${e})`)}}return o.join(` AND `)}function Ae(e,t,n){if(e.order_by){let t=e.order_by.startsWith(`-`);return`${N(t?e.order_by.slice(1):e.order_by)} ${t?`DESC`:`ASC`}`}return t.length>0&&t[0]===`time`?`${N(`time`)} ASC`:`${N(n)} DESC`}function B(e){let t=e.dataset||`authhero_logs`;return{async query(n,r,i){let a=Ce[r],o=Ee[r],s=[],c=[];for(let e of i.group_by)if(e===`time`){let e=De(i.interval,i.tz);s.push(`${e} AS ${N(`time`)}`),c.push({name:`time`,type:Oe(i.interval)})}else{let t=we[e];s.push(`${t} AS ${N(e)}`),c.push({name:e,type:`String`})}c.push({name:o.alias,type:o.type});let l=[...s,`${o.expr} AS ${N(o.alias)}`],u=i.group_by.length?`GROUP BY ${i.group_by.map(e=>N(e===`time`?`time`:e)).join(`, `)}`:``,d=Ae(i,i.group_by.map(e=>e===`time`?`time`:e),o.alias),f=`
|
|
53
53
|
SELECT ${l.join(`, `)}
|
|
54
54
|
FROM ${N(t)}
|
|
55
|
-
WHERE ${
|
|
55
|
+
WHERE ${ke(i,n,a)}
|
|
56
56
|
${u}
|
|
57
57
|
ORDER BY ${d}
|
|
58
58
|
LIMIT ${Math.max(0,i.limit)} OFFSET ${Math.max(0,i.offset)}
|
|
59
59
|
FORMAT JSON
|
|
60
|
-
`,p=`https://api.cloudflare.com/client/v4/accounts/${e.accountId}/analytics_engine/sql`,m=e.timeout||3e4,h=new AbortController,g=setTimeout(()=>h.abort(),m),_=Date.now();try{let t=await fetch(p,{method:`POST`,headers:{"Content-Type":`text/plain`,Authorization:`Bearer ${e.apiToken}`},body:f,signal:h.signal});if(!t.ok){let e=await t.text();throw Error(`Analytics Engine query failed: ${t.status} ${t.statusText} - ${e}`)}let n=await t.json();if(n.success===!1&&n.errors?.length)throw Error(`Analytics Engine error: ${n.errors.map(e=>e.message).join(`, `)}`);let r=n.data??[];return{meta:n.meta??c,data:r,rows:n.rows??r.length,rows_before_limit_at_least:n.rows_before_limit_at_least??r.length,statistics:{elapsed:(Date.now()-_)/1e3}}}finally{clearTimeout(g)}}}}function
|
|
60
|
+
`,p=`https://api.cloudflare.com/client/v4/accounts/${e.accountId}/analytics_engine/sql`,m=e.timeout||3e4,h=new AbortController,g=setTimeout(()=>h.abort(),m),_=Date.now();try{let t=await fetch(p,{method:`POST`,headers:{"Content-Type":`text/plain`,Authorization:`Bearer ${e.apiToken}`},body:f,signal:h.signal});if(!t.ok){let e=await t.text();throw Error(`Analytics Engine query failed: ${t.status} ${t.statusText} - ${e}`)}let n=await t.json();if(n.success===!1&&n.errors?.length)throw Error(`Analytics Engine error: ${n.errors.map(e=>e.message).join(`, `)}`);let r=n.data??[];return{meta:n.meta??c,data:r,rows:n.rows??r.length,rows_before_limit_at_least:n.rows_before_limit_at_least??r.length,statistics:{elapsed:(Date.now()-_)/1e3}}}finally{clearTimeout(g)}}}}function V(e){return e.analyticsEngineBinding||console.warn(`Analytics Engine: No binding configured. Logs will not be written to Analytics Engine.`),(!e.accountId||!e.apiToken)&&console.warn(`Analytics Engine: accountId and apiToken are required for querying logs via SQL API.`),{create:de(e),list:be(e),get:pe(e)}}var je=`authhero_action_executions`,Me=1024,Ne=`[truncated]`;function H(e){if(!(typeof e!=`string`||e.length===0))try{return JSON.parse(e)}catch{return}}function Pe(e){let t=c.actionExecutionStatusSchema.safeParse(e);return t.success?t.data:`unspecified`}function U(e,t=Me){return e.length<=t?e:`${e.substring(0,t-11)}${Ne}`}function W(e){return e==null?``:JSON.stringify(e)}function Fe(e){let t=typeof e.blob6==`string`&&e.blob6.length>0?e.blob6:typeof e.double1==`number`?new Date(e.double1).toISOString():``,n=typeof e.blob7==`string`&&e.blob7.length>0?e.blob7:t;return{id:typeof e.blob1==`string`?e.blob1:``,tenant_id:typeof e.index1==`string`?e.index1:``,trigger_id:typeof e.blob2==`string`?e.blob2:``,status:Pe(e.blob3),results:H(e.blob4)??[],logs:H(e.blob5),created_at:t,updated_at:n}}function Ie(e){return async(t,n)=>{let r=Date.now(),i=new Date(r).toISOString(),a={id:n.id,tenant_id:t,trigger_id:n.trigger_id,status:n.status,results:n.results,logs:n.logs,created_at:i,updated_at:i};return Le(e,t,a,r),a}}function Le(e,t,n,r){if(!e.analyticsEngineBinding){console.error(`Analytics Engine action_executions binding not configured; skipping write`);return}try{e.analyticsEngineBinding.writeDataPoint({blobs:[U(n.id),U(n.trigger_id),U(n.status),U(W(n.results)),U(W(n.logs)),U(n.created_at),U(n.updated_at)],doubles:[r],indexes:[t.substring(0,96)]})}catch(e){console.error(`Failed to write action_execution to Analytics Engine:`,e)}}function Re(e){return async(t,n)=>{let r=await j(e,`
|
|
61
61
|
SELECT *
|
|
62
|
-
FROM ${N(e.dataset||
|
|
62
|
+
FROM ${N(e.dataset||je)}
|
|
63
63
|
WHERE index1 = ${M(t)}
|
|
64
64
|
AND blob1 = ${M(n)}
|
|
65
65
|
LIMIT 1
|
|
66
|
-
`);return r.length===0||!r[0]?null:
|
|
66
|
+
`);return r.length===0||!r[0]?null:Fe(r[0])}}function G(e){return e.analyticsEngineBinding||console.warn(`Analytics Engine: No action_executions binding configured. Executions will not be written.`),(!e.accountId||!e.apiToken)&&console.warn(`Analytics Engine: accountId and apiToken are required to read action_executions via the SQL API.`),{create:Ie(e),get:Re(e)}}function ze(){return{async getGeoInfo(e){try{let t=e[`cf-ipcountry`],n=e[`cf-ipcity`],r=e[`cf-iplatitude`],i=e[`cf-iplongitude`],a=e[`cf-timezone`],o=e[`cf-ipcontinent`];return t?{country_code:t,city_name:n||``,latitude:r||``,longitude:i||``,time_zone:a||``,continent_code:o||``}:null}catch(e){return console.warn(`Failed to get geo info from Cloudflare headers:`,e),null}}}}var Be=class{bindings;constructor(e){this.bindings=e}async consume(e,t){let n=this.bindings[e];if(!n)return{allowed:!0};try{let{success:e}=await n.limit({key:t});return{allowed:e}}catch(t){return console.error(`CloudflareRateLimit: limit() error for scope ${e}:`,t),{allowed:!0}}}};function K(e){if(e&&Object.keys(e).some(t=>e[t]))return new Be(e)}function q(e){return`// Auto-generated AuthHero code hook worker
|
|
67
67
|
|
|
68
68
|
const fnNames = {
|
|
69
69
|
"post-user-login": "onExecutePostLogin",
|
|
@@ -166,9 +166,9 @@ export default {
|
|
|
166
166
|
}
|
|
167
167
|
},
|
|
168
168
|
};
|
|
169
|
-
`}var
|
|
170
|
-
const TRIGGER_FN_NAMES = ${JSON.stringify(
|
|
171
|
-
const API_SHAPES = ${JSON.stringify(
|
|
169
|
+
`}var J=class{config;constructor(e){this.config=e}async execute(e){let t=Date.now();if(!e.hookCodeId)return{success:!1,error:`DispatchNamespaceCodeExecutor requires hookCodeId`,durationMs:Date.now()-t,apiCalls:[]};let n=`hook-${e.hookCodeId}`,r=JSON.stringify({triggerId:e.triggerId,event:e.event});try{let i;if(this.config.dispatcher)i=await this.config.dispatcher.get(n,{},{limits:{cpuMs:e.cpuLimitMs??5e3}}).fetch(new Request(`https://hook.internal/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:r}));else if(this.config.dispatchUrl)i=await fetch(`${this.config.dispatchUrl}/${n}`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.config.apiToken}`},body:r});else return{success:!1,error:`No dispatcher binding or dispatchUrl configured`,durationMs:Date.now()-t,apiCalls:[]};if(!i.ok){let e=await i.text();return{success:!1,error:`Worker invocation failed (${i.status}): ${e}`,durationMs:Date.now()-t,apiCalls:[]}}return{...await i.json(),durationMs:Date.now()-t}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t,apiCalls:[]}}}async deploy(e,t){let n=`hook-${e}`,r=q(t),i=`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/workers/dispatch/namespaces/${this.config.dispatchNamespace}/scripts/${n}`,a=JSON.stringify({main_module:`index.js`,compatibility_date:this.config.compatibilityDate??`2024-11-20`}),o=new FormData;o.append(`metadata`,new Blob([a],{type:`application/json`})),o.append(`index.js`,new Blob([r],{type:`application/javascript+module`}),`index.js`);let s=await fetch(i,{method:`PUT`,headers:{Authorization:`Bearer ${this.config.apiToken}`},body:o});if(!s.ok){let e=await s.text();throw Error(`Failed to deploy hook worker ${n}: ${s.status} ${e}`)}}async remove(e){let t=`hook-${e}`,n=`https://api.cloudflare.com/client/v4/accounts/${this.config.accountId}/workers/dispatch/namespaces/${this.config.dispatchNamespace}/scripts/${t}`,r=await fetch(n,{method:`DELETE`,headers:{Authorization:`Bearer ${this.config.apiToken}`}});if(!r.ok&&r.status!==404){let e=await r.text();throw Error(`Failed to remove hook worker ${t}: ${r.status} ${e}`)}}},Ve=J,He={"post-user-login":`onExecutePostLogin`,"credentials-exchange":`onExecuteCredentialsExchange`,"pre-user-registration":`onExecutePreUserRegistration`,"post-user-registration":`onExecutePostUserRegistration`},Ue={"post-user-login":{accessToken:[`setCustomClaim`],idToken:[`setCustomClaim`],access:[`deny`],prompt:[`render`],redirect:[`sendUserTo`]},"credentials-exchange":{accessToken:[`setCustomClaim`],idToken:[`setCustomClaim`],access:[`deny`]},"pre-user-registration":{user:[`setUserMetadata`,`setLinkedTo`],access:[`deny`]},"post-user-registration":{}};async function We(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n),i=``;for(let e of r)i+=e.toString(16).padStart(2,`0`);return i}function Ge(e){return`
|
|
170
|
+
const TRIGGER_FN_NAMES = ${JSON.stringify(He)};
|
|
171
|
+
const API_SHAPES = ${JSON.stringify(Ue)};
|
|
172
172
|
const MAX_LOG_ENTRIES = 50;
|
|
173
173
|
const MAX_LOG_LENGTH = 500;
|
|
174
174
|
|
|
@@ -266,4 +266,4 @@ export default {
|
|
|
266
266
|
}
|
|
267
267
|
},
|
|
268
268
|
};
|
|
269
|
-
`}var Ue=class{loader;compatibilityDate;constructor(e){this.loader=e.loader,this.compatibilityDate=e.compatibilityDate||`2025-01-01`}async execute(e){let t=Date.now();try{let t=He(e.code),n={compatibilityDate:this.compatibilityDate,mainModule:`hook.js`,modules:{"hook.js":t}},r=e.hookCodeId?`${e.hookCodeId}-${await Ve(e.code)}`:null;return await(await(r?this.loader.get(r,async()=>n):this.loader.load(n)).getEntrypoint().fetch(new Request(`https://hook/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({event:e.event,triggerId:e.triggerId})}))).json()}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t,apiCalls:[]}}}},J=class extends Error{status;endpoint;errors;body;constructor(e,t,n,r=[]){super(`Cloudflare API ${e} ${t}: ${We(n,256)}`),this.name=`CloudflareApiError`,this.status=e,this.endpoint=t,this.body=n,this.errors=r}};function We(e,t){return e.length<=t?e:`${e.slice(0,t)}…`}var Y=class{accountId;apiToken;fetchImpl;timeoutMs;baseUrl;constructor(e){this.accountId=e.accountId,this.apiToken=e.apiToken,this.fetchImpl=e.fetch??((...e)=>fetch(...e)),this.timeoutMs=e.timeoutMs??3e4,this.baseUrl=(e.baseUrl??`https://api.cloudflare.com/client/v4`).replace(/\/+$/,``)}async createD1Database(e){let t=`/accounts/${encodeURIComponent(this.accountId)}/d1/database`;return(await this.request(`POST`,t,{body:JSON.stringify({name:e})})).result}async listD1Databases(e){let t=e?`?name=${encodeURIComponent(e)}`:``,n=`/accounts/${encodeURIComponent(this.accountId)}/d1/database${t}`;return(await this.request(`GET`,n)).result??[]}async deleteD1Database(e){let t=`/accounts/${encodeURIComponent(this.accountId)}/d1/database/${encodeURIComponent(e)}`;await this.request(`DELETE`,t)}async execD1(e,t){let n=`/accounts/${encodeURIComponent(this.accountId)}/d1/database/${encodeURIComponent(e)}/query`;return(await this.request(`POST`,n,{body:JSON.stringify({sql:t})})).result??[]}async uploadNamespacedScript(e,t,n){let r=`/accounts/${this.accountId}/workers/dispatch/namespaces/${encodeURIComponent(e)}/scripts/${encodeURIComponent(t)}`,i={main_module:n.mainModule,compatibility_date:n.compatibilityDate,compatibility_flags:n.compatibilityFlags??[],bindings:n.bindings??[],tags:n.tags},a=new FormData;a.append(`metadata`,new Blob([JSON.stringify(i)],{type:`application/json`})),a.append(n.mainModule,new Blob([n.script],{type:`application/javascript+module`}),n.mainModule),await this.request(`PUT`,r,{body:a})}async deleteNamespacedScript(e,t){let n=`/accounts/${this.accountId}/workers/dispatch/namespaces/${encodeURIComponent(e)}/scripts/${encodeURIComponent(t)}`;await this.request(`DELETE`,n)}async setNamespacedScriptSecret(e,t,n,r){let i=`/accounts/${this.accountId}/workers/dispatch/namespaces/${encodeURIComponent(e)}/scripts/${encodeURIComponent(t)}/secrets`;await this.request(`PUT`,i,{body:JSON.stringify({name:n,text:r,type:`secret_text`})})}async request(e,t,n){let r=`${this.baseUrl}${t}`,i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs),o={Authorization:`Bearer ${this.apiToken}`,...n?.headers??{}};n?.body&&!(n.body instanceof FormData)&&!o[`Content-Type`]&&(o[`Content-Type`]=`application/json`);let s;try{s=await this.fetchImpl(r,{method:e,headers:o,body:n?.body,signal:i.signal})}finally{clearTimeout(a)}let c=await s.text();if(!s.ok){let e=[];try{let t=JSON.parse(c);Array.isArray(t.errors)&&(e=t.errors)}catch{}throw new J(s.status,t,c,e)}if(!(c===``||s.status===204))return JSON.parse(c)}},Ge=`{tenant_id}`,Ke=`tenant-{tenant_id}`,qe=`index.js`,Je=`2026-05-01`,X=64;function Z(e,t){return e.replace(/\{tenant_id\}/g,t)}function Ye(e){if(!(e instanceof J))return!1;let t=e.body.toLowerCase();return e.status===409||t.includes(`already exists`)||t.includes(`name is already taken`)||t.includes(`already in use`)}function Q(e){return e instanceof J?e.status===404:!1}function Xe(e){let t=new Y({accountId:e.accountId,apiToken:e.apiToken,fetch:e.fetch,timeoutMs:e.timeoutMs}),n=e.scriptNameTemplate??Ge,r=e.d1NameTemplate??Ke,i=e.scriptMetadata?.main_module??qe,a=e.scriptMetadata?.compatibility_date??Je,o=e.scriptMetadata?.compatibility_flags??[`nodejs_compat`],s=e.dispatchNamespace,c=e.logger;async function l(e){let n=(await t.listD1Databases(e)).find(t=>t.name===e);if(n)return{id:n.uuid,created:!1};try{return{id:(await t.createD1Database(e)).uuid,created:!0}}catch(n){if(!Ye(n))throw n;let r=(await t.listD1Databases(e)).find(t=>t.name===e);if(r)return{id:r.uuid,created:!1};throw n}}let u=`_authhero_provisioner_migrations`;function d(e,t){let n=[];for(let r of e)for(let e of r.results??[])if(e&&typeof e==`object`&&t in e){let r=e[t];typeof r==`string`&&n.push(r)}return n}async function f(e){return d(await t.execD1(e,`SELECT name FROM sqlite_master WHERE type='table' AND name='${u}';`),`name`).length>0}async function p(e){await t.execD1(e,`CREATE TABLE IF NOT EXISTS ${u} (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL);`)}async function m(e){let n=await t.execD1(e,`SELECT name FROM ${u};`);return new Set(d(n,`name`))}function h(e){return e.replace(/'/g,`''`)}async function g(e,n){let r=new Date().toISOString();await t.execD1(e,`INSERT OR IGNORE INTO ${u} (name, applied_at) VALUES ('${h(n)}', '${h(r)}');`)}async function _(n){let r=await m(n);for(let i of e.migrations)if(!r.has(i.name)){try{await t.execD1(n,i.sql)}catch(e){throw e instanceof Error?Error(`Failed to apply migration "${i.name}" to D1 ${n}: ${e.message}`,{cause:e}):e}await g(n,i.name)}}async function v(n,r){let c=[{type:`d1`,name:`AUTH_DB`,id:r},{type:`plain_text`,name:`CONTROL_PLANE_BASE_URL`,text:e.controlPlaneBaseUrl},...e.extraBindings??[]];await t.uploadNamespacedScript(s,n,{script:e.tenantWorkerScript,mainModule:i,compatibilityDate:a,compatibilityFlags:o,bindings:c,tags:[`authhero-tenant`,`tenant:${n}`]})}async function y(n,r){let i=await e.secrets(r);for(let[e,r]of Object.entries(i))await t.setNamespacedScriptSecret(s,n,e,r)}return{async onProvision(t){let i=Z(n,t),a=Z(r,t),o=e.migrations[e.migrations.length-1]?.name;if(o!==void 0&&o.length>X)throw Error(`Migration name "${o}" exceeds the ${X}-character database_version limit.`);let{id:s,created:u}=await l(a),d=u?!1:await f(s);if(u||d)await p(s),await _(s);else{c?.warn(`D1 "${a}" has no migration-tracking table — assuming it predates tracking and is fully migrated; backfilling the tracking table and skipping migrations.`),await p(s);for(let t of e.migrations)await g(s,t.name)}return await v(i,s),await y(i,t),{d1DatabaseId:s,scriptName:i,d1Name:a,bundleConfiguration:e.bundleConfiguration,workerVersion:e.workerVersion,databaseVersion:o}},async onDeprovision(e){let i=Z(n,e),a=Z(r,e),o=[];try{await t.deleteNamespacedScript(s,i)}catch(e){Q(e)||o.push(e)}try{let e=(await t.listD1Databases(a)).find(e=>e.name===a);if(e)try{await t.deleteD1Database(e.uuid)}catch(e){Q(e)||o.push(e)}}catch(e){o.push(e)}if(o.length>0){let t=o.map(e=>e instanceof Error?e.message:String(e)).join(`; `);throw Error(`Deprovision of tenant "${e}" had ${o.length} failure(s): ${t}`,{cause:o[0]})}}}}function Ze(e){return e.deployment_type===`wfp`}function $(e){if(typeof e!=`object`||!e)return[];let t=[];for(let n of Object.values(e))if(typeof n==`object`&&n&&`errors`in n&&Array.isArray(n.errors))for(let e of n.errors)typeof e==`string`&&t.push(e);return t}function Qe(e){let{provisioner:t,tenants:n,syncDefaults:r}=e,i=e.shouldProvision??Ze,a=e.logger;async function o(e,t){let r=t instanceof Error?t.message:String(t);try{await n.update(e,{provisioning_state:`failed`,provisioning_error:r.slice(0,2048),provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`,t)}}async function s(e){let i;try{i=await t.onProvision(e)}catch(t){throw await o(e,t),t}let s={d1_database_id:i.d1DatabaseId,worker_script_name:i.scriptName,bundle_configuration:i.bundleConfiguration,worker_version:i.workerVersion,database_version:i.databaseVersion};try{if(r){let t=$(await r(e));if(t.length>0)throw Error(`sync-defaults seed reported ${t.length} error(s): ${t.join(`; `)}`)}await n.update(e,{...s,provisioning_state:`ready`,provisioning_error:void 0,provisioning_state_changed_at:new Date().toISOString()})}catch(t){let r=t instanceof Error?t.message:String(t);try{await n.update(e,{...s,provisioning_state:`failed`,provisioning_error:r.slice(0,2048),provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`,t)}throw t}}return{async onProvision(e){let t=await n.get(e);t&&i(t)&&await s(e)},async onUpgrade(e){let t=await n.get(e);if(!t)throw Error(`Cannot upgrade tenant "${e}": not found.`);if(!i(t))throw Error(`Cannot upgrade tenant "${e}": not a WFP-provisioned tenant.`);try{await n.update(e,{provisioning_state:`pending`,provisioning_error:void 0,provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="pending" for tenant ${e}:`,t)}await s(e)},async onDeprovision(e){let r=await n.get(e);r&&!i(r)||await t.onDeprovision(e)}}}var $e=`DISPATCHER`,et=`tenant-{tenant_id}-auth`;function tt(e){return typeof e==`object`&&!!e&&`get`in e&&typeof Reflect.get(e,`get`)==`function`}function nt(e,t){return e.replace(/\{tenant_id\}/g,t)}function rt(e){let{tenants:t,controlPlaneTenantId:n,dispatcherBinding:r=$e,scriptNameTemplate:i=et,resolveTenantId:a=e=>e.req.header(`tenant-id`)}=e;return async(e,o)=>{let s=await a(e);if(!s||s===n)return o();let c=await t.get(s);if(!c||c.deployment_type!==`wfp`||c.provisioning_state&&c.provisioning_state!==`ready`)return o();let l=Reflect.get(e.env??{},r);if(!tt(l))return o();let u=nt(i,s),d;try{d=await l.get(u).fetch(e.req.raw)}catch(t){let n=t instanceof Error?t.message:String(t),r=/not\s*found|no\s*such|does not exist/i.test(n),i=r?`wfp_worker_not_found`:`wfp_dispatch_failed`;return console.error(`[wfp-forward] ${i} tenant=${s} script=${u}: ${n}`),e.header(`X-Authhero-Error`,i),e.header(`X-Wfp-Tenant`,s),e.json({error:i,detail:r?`Tenant '${s}' is marked ready but its worker '${u}' is not deployed in the dispatch namespace.`:`The worker for tenant '${s}' could not be reached.`,tenant_id:s},r?503:502)}if(d.status>=500){let e=d.headers.get(`X-Authhero-Error`);console.error(`[wfp-forward] tenant worker ${d.status}${e?` (${e})`:``} tenant=${s} script=${u}`)}let f=Reflect.get(d,`webSocket`);if(d.status===101||f!=null)return d;let p=new Response(d.body,d);return p.headers.set(`X-Wfp-Tenant`,s),p}}function it(e){let t={customDomains:ee(e),cache:ne({...e.cacheName&&{cacheName:e.cacheName},...e.defaultTtlSeconds!==void 0&&{defaultTtlSeconds:e.defaultTtlSeconds},...e.keyPrefix&&{keyPrefix:e.keyPrefix}}),geo:Ie()};e.r2SqlLogs?t.logs=A(e.r2SqlLogs):e.analyticsEngineLogs&&(t.logs=B(e.analyticsEngineLogs)),e.analyticsEngineLogs&&(t.analytics=z(e.analyticsEngineLogs)),e.analyticsEngineActionExecutions&&(t.actionExecutions=W(e.analyticsEngineActionExecutions));let n=G(e.rateLimitBindings);return n&&(t.rateLimit=n),t}exports.CloudflareApiClient=Y,exports.CloudflareApiError=J,exports.CloudflareCodeExecutor=Re,exports.DispatchNamespaceCodeExecutor=q,exports.WorkerLoaderCodeExecutor=Ue,exports.createAnalyticsEngineActionExecutionsAdapter=W,exports.createAnalyticsEngineAnalyticsAdapter=z,exports.createAnalyticsEngineLogsAdapter=B,exports.createAnalyticsEngineStatsAdapter=ye,exports.createCloudflareRateLimitAdapter=G,exports.createCloudflareWfpD1Provisioner=Xe,exports.createR2SQLLogsAdapter=A,exports.createR2SQLStatsAdapter=ue,exports.createWfpForwardMiddleware=rt,exports.createWfpTenantProvisioningHook=Qe,exports.default=it,exports.generateWorkerScript=K;
|
|
269
|
+
`}var Ke=class{loader;compatibilityDate;constructor(e){this.loader=e.loader,this.compatibilityDate=e.compatibilityDate||`2025-01-01`}async execute(e){let t=Date.now();try{let t=Ge(e.code),n={compatibilityDate:this.compatibilityDate,mainModule:`hook.js`,modules:{"hook.js":t}},r=e.hookCodeId?`${e.hookCodeId}-${await We(e.code)}`:null;return await(await(r?this.loader.get(r,async()=>n):this.loader.load(n)).getEntrypoint().fetch(new Request(`https://hook/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({event:e.event,triggerId:e.triggerId})}))).json()}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e),durationMs:Date.now()-t,apiCalls:[]}}}},Y=class extends Error{status;endpoint;errors;body;constructor(e,t,n,r=[]){super(`Cloudflare API ${e} ${t}: ${qe(n,256)}`),this.name=`CloudflareApiError`,this.status=e,this.endpoint=t,this.body=n,this.errors=r}};function qe(e,t){return e.length<=t?e:`${e.slice(0,t)}…`}var X=class{accountId;apiToken;fetchImpl;timeoutMs;baseUrl;constructor(e){this.accountId=e.accountId,this.apiToken=e.apiToken,this.fetchImpl=e.fetch??((...e)=>fetch(...e)),this.timeoutMs=e.timeoutMs??3e4,this.baseUrl=(e.baseUrl??`https://api.cloudflare.com/client/v4`).replace(/\/+$/,``)}async createD1Database(e){let t=`/accounts/${encodeURIComponent(this.accountId)}/d1/database`;return(await this.request(`POST`,t,{body:JSON.stringify({name:e})})).result}async listD1Databases(e){let t=e?`?name=${encodeURIComponent(e)}`:``,n=`/accounts/${encodeURIComponent(this.accountId)}/d1/database${t}`;return(await this.request(`GET`,n)).result??[]}async deleteD1Database(e){let t=`/accounts/${encodeURIComponent(this.accountId)}/d1/database/${encodeURIComponent(e)}`;await this.request(`DELETE`,t)}async execD1(e,t){let n=`/accounts/${encodeURIComponent(this.accountId)}/d1/database/${encodeURIComponent(e)}/query`;return(await this.request(`POST`,n,{body:JSON.stringify({sql:t})})).result??[]}async uploadNamespacedScript(e,t,n){let r=`/accounts/${this.accountId}/workers/dispatch/namespaces/${encodeURIComponent(e)}/scripts/${encodeURIComponent(t)}`,i={main_module:n.mainModule,compatibility_date:n.compatibilityDate,compatibility_flags:n.compatibilityFlags??[],bindings:n.bindings??[],tags:n.tags},a=new FormData;a.append(`metadata`,new Blob([JSON.stringify(i)],{type:`application/json`})),a.append(n.mainModule,new Blob([n.script],{type:`application/javascript+module`}),n.mainModule),await this.request(`PUT`,r,{body:a})}async deleteNamespacedScript(e,t){let n=`/accounts/${this.accountId}/workers/dispatch/namespaces/${encodeURIComponent(e)}/scripts/${encodeURIComponent(t)}`;await this.request(`DELETE`,n)}async setNamespacedScriptSecret(e,t,n,r){let i=`/accounts/${this.accountId}/workers/dispatch/namespaces/${encodeURIComponent(e)}/scripts/${encodeURIComponent(t)}/secrets`;await this.request(`PUT`,i,{body:JSON.stringify({name:n,text:r,type:`secret_text`})})}async request(e,t,n){let r=`${this.baseUrl}${t}`,i=new AbortController,a=setTimeout(()=>i.abort(),this.timeoutMs),o={Authorization:`Bearer ${this.apiToken}`,...n?.headers??{}};n?.body&&!(n.body instanceof FormData)&&!o[`Content-Type`]&&(o[`Content-Type`]=`application/json`);let s;try{s=await this.fetchImpl(r,{method:e,headers:o,body:n?.body,signal:i.signal})}finally{clearTimeout(a)}let c=await s.text();if(!s.ok){let e=[];try{let t=JSON.parse(c);Array.isArray(t.errors)&&(e=t.errors)}catch{}throw new Y(s.status,t,c,e)}if(!(c===``||s.status===204))return JSON.parse(c)}},Je=`{tenant_id}`,Ye=`tenant-{tenant_id}`,Xe=`index.js`,Ze=`2026-05-01`,Z=64;function Q(e,t){return e.replace(/\{tenant_id\}/g,t)}function Qe(e){if(!(e instanceof Y))return!1;let t=e.body.toLowerCase();return e.status===409||t.includes(`already exists`)||t.includes(`name is already taken`)||t.includes(`already in use`)}function $(e){return e instanceof Y?e.status===404:!1}function $e(e){let t=new X({accountId:e.accountId,apiToken:e.apiToken,fetch:e.fetch,timeoutMs:e.timeoutMs}),n=e.scriptNameTemplate??Je,r=e.d1NameTemplate??Ye,i=e.scriptMetadata?.main_module??Xe,a=e.scriptMetadata?.compatibility_date??Ze,o=e.scriptMetadata?.compatibility_flags??[`nodejs_compat`],s=e.dispatchNamespace,c=e.logger;async function l(e){let n=(await t.listD1Databases(e)).find(t=>t.name===e);if(n)return{id:n.uuid,created:!1};try{return{id:(await t.createD1Database(e)).uuid,created:!0}}catch(n){if(!Qe(n))throw n;let r=(await t.listD1Databases(e)).find(t=>t.name===e);if(r)return{id:r.uuid,created:!1};throw n}}let u=`_authhero_provisioner_migrations`;function d(e,t){let n=[];for(let r of e)for(let e of r.results??[])if(e&&typeof e==`object`&&t in e){let r=e[t];typeof r==`string`&&n.push(r)}return n}async function f(e){return d(await t.execD1(e,`SELECT name FROM sqlite_master WHERE type='table' AND name='${u}';`),`name`).length>0}async function p(e){await t.execD1(e,`CREATE TABLE IF NOT EXISTS ${u} (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL);`)}async function m(e){let n=await t.execD1(e,`SELECT name FROM ${u};`);return new Set(d(n,`name`))}function h(e){return e.replace(/'/g,`''`)}async function g(e,n){let r=new Date().toISOString();await t.execD1(e,`INSERT OR IGNORE INTO ${u} (name, applied_at) VALUES ('${h(n)}', '${h(r)}');`)}async function _(n){let r=await m(n);for(let i of e.migrations)if(!r.has(i.name)){try{await t.execD1(n,i.sql)}catch(e){throw e instanceof Error?Error(`Failed to apply migration "${i.name}" to D1 ${n}: ${e.message}`,{cause:e}):e}await g(n,i.name)}}async function v(n,r){let c=[{type:`d1`,name:`AUTH_DB`,id:r},{type:`plain_text`,name:`CONTROL_PLANE_BASE_URL`,text:e.controlPlaneBaseUrl},...e.extraBindings??[]];await t.uploadNamespacedScript(s,n,{script:e.tenantWorkerScript,mainModule:i,compatibilityDate:a,compatibilityFlags:o,bindings:c,tags:[`authhero-tenant`,`tenant:${n}`]})}async function y(n,r){let i=await e.secrets(r);for(let[e,r]of Object.entries(i))await t.setNamespacedScriptSecret(s,n,e,r)}return{async onProvision(t){let i=Q(n,t),a=Q(r,t),o=e.migrations[e.migrations.length-1]?.name;if(o!==void 0&&o.length>Z)throw Error(`Migration name "${o}" exceeds the ${Z}-character database_version limit.`);let{id:s,created:u}=await l(a),d=u?!1:await f(s);if(u||d)await p(s),await _(s);else{c?.warn(`D1 "${a}" has no migration-tracking table — assuming it predates tracking and is fully migrated; backfilling the tracking table and skipping migrations.`),await p(s);for(let t of e.migrations)await g(s,t.name)}return await v(i,s),await y(i,t),{d1DatabaseId:s,scriptName:i,d1Name:a,bundleConfiguration:e.bundleConfiguration,workerVersion:e.workerVersion,databaseVersion:o}},async onDeprovision(e){let i=Q(n,e),a=Q(r,e),o=[];try{await t.deleteNamespacedScript(s,i)}catch(e){$(e)||o.push(e)}try{let e=(await t.listD1Databases(a)).find(e=>e.name===a);if(e)try{await t.deleteD1Database(e.uuid)}catch(e){$(e)||o.push(e)}}catch(e){o.push(e)}if(o.length>0){let t=o.map(e=>e instanceof Error?e.message:String(e)).join(`; `);throw Error(`Deprovision of tenant "${e}" had ${o.length} failure(s): ${t}`,{cause:o[0]})}}}}function et(e){return e.deployment_type===`wfp`}function tt(e){if(typeof e!=`object`||!e)return[];let t=[];for(let n of Object.values(e))if(typeof n==`object`&&n&&`errors`in n&&Array.isArray(n.errors))for(let e of n.errors)typeof e==`string`&&t.push(e);return t}function nt(e){let{provisioner:t,tenants:n,syncDefaults:r}=e,i=e.shouldProvision??et,a=e.logger;async function o(e,t){let r=t instanceof Error?t.message:String(t);try{await n.update(e,{provisioning_state:`failed`,provisioning_error:r.slice(0,2048),provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`,t)}}async function s(e){let i;try{i=await t.onProvision(e)}catch(t){throw await o(e,t),t}let s={d1_database_id:i.d1DatabaseId,worker_script_name:i.scriptName,bundle_configuration:i.bundleConfiguration,worker_version:i.workerVersion,database_version:i.databaseVersion};try{if(r){let t=tt(await r(e));if(t.length>0)throw Error(`sync-defaults seed reported ${t.length} error(s): ${t.join(`; `)}`)}await n.update(e,{...s,provisioning_state:`ready`,provisioning_error:void 0,provisioning_state_changed_at:new Date().toISOString()})}catch(t){let r=t instanceof Error?t.message:String(t);try{await n.update(e,{...s,provisioning_state:`failed`,provisioning_error:r.slice(0,2048),provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="failed" for tenant ${e}:`,t)}throw t}}return{async onProvision(e){let t=await n.get(e);t&&i(t)&&await s(e)},async onUpgrade(e){let t=await n.get(e);if(!t)throw Error(`Cannot upgrade tenant "${e}": not found.`);if(!i(t))throw Error(`Cannot upgrade tenant "${e}": not a WFP-provisioned tenant.`);try{await n.update(e,{provisioning_state:`pending`,provisioning_error:void 0,provisioning_state_changed_at:new Date().toISOString()})}catch(t){a?.warn(`Failed to write provisioning_state="pending" for tenant ${e}:`,t)}await s(e)},async onDeprovision(e){let r=await n.get(e);r&&!i(r)||await t.onDeprovision(e)}}}var rt=`DISPATCHER`,it=`tenant-{tenant_id}-auth`;function at(e){return typeof e==`object`&&!!e&&`get`in e&&typeof Reflect.get(e,`get`)==`function`}function ot(e,t){return e.replace(/\{tenant_id\}/g,t)}function st(e){let{tenants:t,controlPlaneTenantId:n,dispatcherBinding:r=rt,scriptNameTemplate:i=it,resolveTenantId:a=e=>e.req.header(`tenant-id`)}=e;return async(e,o)=>{let s=await a(e);if(!s||s===n)return o();let c=await t.get(s);if(!c||c.deployment_type!==`wfp`||c.provisioning_state&&c.provisioning_state!==`ready`)return o();let l=Reflect.get(e.env??{},r);if(!at(l))return o();let u=ot(i,s),d;try{d=await l.get(u).fetch(e.req.raw)}catch(t){let n=t instanceof Error?t.message:String(t),r=/not\s*found|no\s*such|does not exist/i.test(n),i=r?`wfp_worker_not_found`:`wfp_dispatch_failed`;return console.error(`[wfp-forward] ${i} tenant=${s} script=${u}: ${n}`),e.header(`X-Authhero-Error`,i),e.header(`X-Wfp-Tenant`,s),e.json({error:i,detail:r?`Tenant '${s}' is marked ready but its worker '${u}' is not deployed in the dispatch namespace.`:`The worker for tenant '${s}' could not be reached.`,tenant_id:s},r?503:502)}if(d.status>=500){let e=d.headers.get(`X-Authhero-Error`);console.error(`[wfp-forward] tenant worker ${d.status}${e?` (${e})`:``} tenant=${s} script=${u}`)}let f=Reflect.get(d,`webSocket`);if(d.status===101||f!=null)return d;let p=new Response(d.body,d);return p.headers.set(`X-Wfp-Tenant`,s),p}}function ct(e){let t={customDomains:ee(e),cache:ne({...e.cacheName&&{cacheName:e.cacheName},...e.defaultTtlSeconds!==void 0&&{defaultTtlSeconds:e.defaultTtlSeconds},...e.keyPrefix&&{keyPrefix:e.keyPrefix}}),geo:ze()};e.r2SqlLogs?t.logs=A(e.r2SqlLogs):e.analyticsEngineLogs&&(t.logs=V(e.analyticsEngineLogs)),e.analyticsEngineLogs&&(t.analytics=B(e.analyticsEngineLogs)),e.analyticsEngineActionExecutions&&(t.actionExecutions=G(e.analyticsEngineActionExecutions));let n=K(e.rateLimitBindings);return n&&(t.rateLimit=n),t}exports.CloudflareApiClient=X,exports.CloudflareApiError=Y,exports.CloudflareCodeExecutor=Ve,exports.DispatchNamespaceCodeExecutor=J,exports.WorkerLoaderCodeExecutor=Ke,exports.createAnalyticsEngineActionExecutionsAdapter=G,exports.createAnalyticsEngineAnalyticsAdapter=B,exports.createAnalyticsEngineLogsAdapter=V,exports.createAnalyticsEngineStatsAdapter=Se,exports.createCloudflareRateLimitAdapter=K,exports.createCloudflareWfpD1Provisioner=$e,exports.createR2SQLLogsAdapter=A,exports.createR2SQLStatsAdapter=ue,exports.createWfpForwardMiddleware=st,exports.createWfpTenantProvisioningHook=nt,exports.default=ct,exports.generateWorkerScript=q;
|