@authhero/cloudflare-adapter 3.2.5 → 3.3.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.
@@ -1,4 +1,4 @@
1
- Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require("./sync-defaults-errors-Htp1NWTq.js");let l=require("@authhero/adapter-interfaces"),u=require("@hono/zod-openapi"),d=require("hono/http-exception"),f=require("wretch");f=s(f);let p=require("wretch/middlewares");var m=u.z.object({code:u.z.number(),message:u.z.string()}),h=u.z.object({message:u.z.string()}),g=u.z.object({emails:u.z.array(u.z.string()).optional(),http_body:u.z.string().optional(),http_url:u.z.string().optional(),txt_name:u.z.string().optional(),txt_value:u.z.string().optional()}),_=u.z.object({ciphers:u.z.array(u.z.string()).optional(),early_hints:u.z.string().optional(),http2:u.z.string().optional(),min_tls_version:u.z.string().optional(),tls_1_3:u.z.string().optional()}),ee=u.z.object({id:u.z.string(),bundle_method:u.z.string().optional(),certificate_authority:u.z.string(),custom_certificate:u.z.string().optional(),custom_csr_id:u.z.string().optional(),custom_key:u.z.string().optional(),expires_on:u.z.string().optional(),hosts:u.z.array(u.z.string()).optional(),issuer:u.z.string().optional(),method:u.z.string(),serial_number:u.z.string().optional(),settings:_.optional(),signature:u.z.string().optional(),type:u.z.string(),uploaded_on:u.z.string().optional(),validation_errors:u.z.array(h).optional(),validation_records:u.z.array(g).optional(),wildcard:u.z.boolean()}),te=u.z.object({name:u.z.string(),type:u.z.string(),value:u.z.string()}),ne=u.z.object({http_body:u.z.string().optional(),http_url:u.z.string().optional()}),v=u.z.object({id:u.z.string(),ssl:ee,hostname:u.z.string(),custom_metadata:u.z.record(u.z.string(),u.z.string()).optional(),custom_origin_server:u.z.string().optional(),custom_origin_sni:u.z.string().optional(),ownership_verification:te.optional(),ownership_verification_http:ne.optional(),status:u.z.string(),verification_errors:u.z.array(u.z.string()).optional(),created_at:u.z.string()}),y=u.z.object({errors:u.z.array(m),messages:u.z.array(m),success:u.z.boolean(),result:v}),b=u.z.object({errors:u.z.array(m),messages:u.z.array(m),success:u.z.boolean(),result:u.z.array(v)});function x(e){return(0,f.default)(`https://api.cloudflare.com/client/v4/zones/${e.zoneId}`).headers({"X-Auth-Email":e.authEmail,"X-Auth-Key":e.authKey,"Content-Type":`application/json`}).middlewares([(0,p.retry)(),(0,p.dedupe)()])}function S(e){let t={},n={};if(!e)return{sslOverrides:t,rest:n};for(let[r,i]of Object.entries(e))r.startsWith(`ssl.`)?t[r.slice(4)]=i:n[r]=i;return{sslOverrides:t,rest:n}}function C(e){let t=[];if(e.ssl.validation_records)for(let n of e.ssl.validation_records)n.txt_name&&n.txt_value&&t.push({name:`txt`,record:n.txt_value,domain:n.txt_name});if(e.ownership_verification&&t.push({name:`txt`,record:e.ownership_verification.value,domain:e.ownership_verification.name}),e.ownership_verification_http?.http_body&&e.ownership_verification_http?.http_url&&t.push({name:`http`,http_body:e.ownership_verification_http.http_body,http_url:e.ownership_verification_http.http_url}),e.ssl.validation_records)for(let n of e.ssl.validation_records)n.http_body&&n.http_url&&t.push({name:`http`,http_body:n.http_body,http_url:n.http_url});let n={...e.domain_metadata||{},"ssl.method":e.ssl.method,"ssl.type":e.ssl.type,"ssl.certificate_authority":e.ssl.certificate_authority};return{custom_domain_id:e.id,domain:e.hostname,primary:e.primary,status:e.status===`active`?`ready`:`pending`,type:e.type??`auth0_managed_certs`,verification:{methods:u.z.array(l.verificationMethodsSchema).parse(t)},domain_metadata:n}}function re(e){let t=e instanceof Error?e.message:String(e);return/duplicate/i.test(t)}async function ie(e,t,n){let r;try{r=await x(e).get(`/custom_hostnames?hostname=${encodeURIComponent(n)}`).json()}catch{return null}let i=b.safeParse(r);if(!i.success||!i.data.success)return null;let a=i.data.result.find(e=>e.hostname.toLowerCase()===n.toLowerCase());return!a||e.enterprise&&a.custom_metadata?.tenant_id!==t?null:a}async function ae(e,t,n,r){let i=n.custom_domain_id,a;try{a=C({...n,...r})}catch(e){return console.warn(`[custom-domains] mapCustomDomainResponse failed for ${i} (tenant=${t}); keeping the stored row.`,e instanceof Error?e.message:e),{domain:n,outcome:`failed`}}if(a.status===n.status&&JSON.stringify(a.verification)===JSON.stringify(n.verification))return{domain:a,outcome:`unchanged`};try{await e.customDomainAdapter.update(t,i,{status:a.status,verification:a.verification})}catch(e){return console.warn(`[custom-domains] DB writeback failed for ${i} (tenant=${t}); returning merged response without DB sync.`,e instanceof Error?e.message:e),{domain:a,outcome:`failed`}}return{domain:a,outcome:`updated`}}function oe(e){return{create:async(t,n)=>{let{sslOverrides:r,rest:i}=S(n.domain_metadata);if(await e.customDomainAdapter.getByDomain(n.domain))throw new d.HTTPException(409,{message:`The domain ${n.domain} is already registered`});let a;try{let i=y.parse(await x(e).post({hostname:n.domain,ssl:{method:`txt`,type:`dv`,...r},custom_metadata:e.enterprise?{tenant_id:t}:void 0},`/custom_hostnames`).json());if(!i.success)throw Error(JSON.stringify(i.errors));a=i.result}catch(r){if(!re(r))throw r;let i=await ie(e,t,n.domain);if(!i)throw r;a=i}let o=C({...a,primary:!1,type:n.type,domain_metadata:i});return await e.customDomainAdapter.create(t,{custom_domain_id:o.custom_domain_id,domain:o.domain,type:o.type,domain_metadata:n.domain_metadata}),await e.customDomainAdapter.update(t,o.custom_domain_id,{status:o.status,primary:o.primary,verification:o.verification}),o},get:async(t,n)=>{let r=await e.customDomainAdapter.get(t,n);if(!r)throw new d.HTTPException(404);let i;try{i=await x(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json()}catch(e){return console.warn(`[custom-domains] CF fetch failed for ${n} (tenant=${t}); returning stale DB row:`,e instanceof Error?e.message:e),r}let a=y.safeParse(i);if(!a.success||!a.data.success)return console.warn(`[custom-domains] CF response unparseable for ${n} (tenant=${t}); returning stale DB row.`,a.success?{cfErrors:a.data.errors}:{zodIssues:a.error.issues,body:i}),r;let{result:o}=a.data;if(e.enterprise&&o.custom_metadata?.tenant_id!==t)throw new d.HTTPException(404);let{domain:s}=await ae(e,t,r,o);return s},getByDomain:async t=>e.customDomainAdapter.getByDomain(t),list:async t=>e.customDomainAdapter.list(t),remove:async(t,n)=>{if(e.enterprise){let{result:r,success:i}=y.parse(await x(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json());if(!i||r.custom_metadata?.tenant_id!==t)throw new d.HTTPException(404)}let r=await x(e).delete(`/custom_hostnames/${encodeURIComponent(n)}`).res();return r.ok&&await e.customDomainAdapter.remove(t,n),r.ok},update:async(t,n,r)=>{let{sslOverrides:i}=S(r.domain_metadata),a={};if(Object.keys(i).length>0){let t;try{t=await x(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json()}catch(e){throw new d.HTTPException(503,{message:`Failed to fetch current custom hostname state: ${e instanceof Error?e.message:String(e)}`})}let r=y.safeParse(t);if(!r.success||!r.data.success)throw new d.HTTPException(503,{message:`Failed to parse current custom hostname state: ${JSON.stringify(r.success?r.data.errors:r.error.issues)}`});a.ssl={method:r.data.result.ssl.method,type:r.data.result.ssl.type,certificate_authority:r.data.result.ssl.certificate_authority,...i}}if(Object.keys(a).length>0){let t=await x(e).patch(a,`/custom_hostnames/${encodeURIComponent(n)}`).res().catch(e=>{throw new d.HTTPException(503,{message:`Failed to update custom hostname: ${e instanceof Error?e.message:String(e)}`})});if(!t.ok)throw new d.HTTPException(503,{message:await t.text()})}return e.customDomainAdapter.update(t,n,r)},uploadCertificate:async(t,n,r)=>{let i=await e.customDomainAdapter.get(t,n);if(!i)throw new d.HTTPException(404);let a=await x(e).patch({ssl:{custom_certificate:r.certificate,custom_key:r.private_key}},`/custom_hostnames/${encodeURIComponent(n)}`).json(),{result:o,errors:s,success:c}=y.parse(a);if(!c)throw new d.HTTPException(503,{message:JSON.stringify(s)});let l=C({...i,...o});return await e.customDomainAdapter.update(t,n,{status:l.status,verification:l.verification}),l}}}var se=class{config;cache=null;constructor(e){this.config=e}async getCache(){if(this.cache)return this.cache;if(typeof caches>`u`)throw Error(`caches API is not available - CloudflareCache should only be used in Cloudflare Workers`);return this.config.cacheName?this.cache=await caches.open(this.config.cacheName):this.cache=caches.default,this.cache}getKey(e){return this.config.keyPrefix?`${this.config.keyPrefix}:${e}`:e}createRequest(e){return new Request(`https://cache.internal/${this.getKey(e)}`)}async matchWithTimeout(e,t){let n=this.config.getTimeoutMs??200;return n<=0?e.match(t):new Promise(r=>{let i=setTimeout(()=>r(void 0),n);e.match(t).then(e=>{clearTimeout(i),r(e)},()=>{clearTimeout(i),r(void 0)})})}async get(e){try{let t=await this.getCache(),n=this.createRequest(e),r=await this.matchWithTimeout(t,n);if(!r)return null;let i=await r.text();if(!i)return await this.delete(e),null;let a;try{a=JSON.parse(i)}catch{return await this.delete(e),null}return a.expiresAt&&new Date(a.expiresAt)<new Date?(await this.delete(e),null):a.value}catch(t){return console.error(`CloudflareCache: get error for key ${e}:`,t),null}}async set(e,t,n){try{let r=await this.getCache(),i=n??this.config.defaultTtlSeconds,a=i!==void 0,o=a?Math.max(0,i):0,s={value:t,expiresAt:a?new Date(Date.now()+(o>0?o*1e3:-1)).toISOString():void 0,cachedAt:new Date().toISOString()},c=this.createRequest(e),l={"Content-Type":`application/json`};a&&o>0&&(l[`Cache-Control`]=`max-age=${o}`);let u=new Response(JSON.stringify(s),{headers:l});await r.put(c,u)}catch(t){console.error(`CloudflareCache: set error for key ${e}:`,t)}}async delete(e){try{let t=await this.getCache(),n=this.createRequest(e);return await t.delete(n)}catch(t){return console.error(`CloudflareCache: delete error for key ${e}:`,t),!1}}async deleteByPrefix(e){return console.warn(`CloudflareCache.deleteByPrefix() is not implemented - Cloudflare Cache API does not support prefix-based deletion`),0}async clear(){console.warn(`CloudflareCache.clear() is not implemented - Cloudflare Cache API does not support clearing all entries`)}};function ce(e={}){return new se({defaultTtlSeconds:300,keyPrefix:`authhero`,getTimeoutMs:200,...e})}var le=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,w=(e=21)=>{let t=``,n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=le[n[e]&63];return t};async function T(e,t){let n=e.timeout||3e4,r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=`https://api.sql.cloudflarestorage.com/api/v1/accounts/${e.accountId}/r2-sql/query/${e.warehouseName}`,i=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.authToken}`},body:JSON.stringify({query:t}),signal:r.signal});if(!i.ok)throw Error(`R2 SQL query failed: ${i.status} ${i.statusText}`);let a=await i.json();if(!a.success&&a.errors)throw Error(`R2 SQL error: ${a.errors.join(`, `)}`);return a.data||a.result?.data||[]}finally{clearTimeout(i)}}function E(e){return`'${e.replace(/'/g,`''`)}'`}function D(e){return`"${e.replace(/"/g,`""`)}"`}function O(e){let t=e=>{if(!e)return``;try{return JSON.parse(e)}catch{return e}};return{type:e.type,date:e.date,description:e.description,ip:e.ip,user_agent:e.user_agent,details:t(e.details),isMobile:!!e.isMobile,user_id:e.user_id,user_name:e.user_name,connection:e.connection,connection_id:e.connection_id,client_id:e.client_id,client_name:e.client_name,audience:e.audience,scope:e.scope,strategy:e.strategy,strategy_type:e.strategy_type,hostname:e.hostname,auth0_client:t(e.auth0_client),log_id:e.id,location_info:e.country_code||e.city_name||e.latitude||e.longitude||e.time_zone||e.continent_code?{country_code:e.country_code||``,city_name:e.city_name||``,latitude:e.latitude||``,longitude:e.longitude||``,time_zone:e.time_zone||``,continent_code:e.continent_code||``}:void 0}}function ue(e){return async(t,n)=>{let r=n.log_id||w(),i={...n,log_id:r};return await de(e,t,i),i}}async function de(e,t,n){let r=e=>e?JSON.stringify(e):void 0,i={id:n.log_id,tenant_id:t,type:n.type,date:n.date,description:n.description?.substring(0,256),ip:n.ip,user_agent:n.user_agent,details:r(n.details)?.substring(0,8192),isMobile:+!!n.isMobile,user_id:n.user_id,user_name:n.user_name,connection:n.connection,connection_id:n.connection_id,client_id:n.client_id,client_name:n.client_name,audience:n.audience,scope:n.scope,strategy:n.strategy,strategy_type:n.strategy_type,hostname:n.hostname,auth0_client:r(n.auth0_client),log_id:n.log_id,country_code:n.location_info?.country_code,city_name:n.location_info?.city_name,latitude:n.location_info?.latitude,longitude:n.location_info?.longitude,time_zone:n.location_info?.time_zone,continent_code:n.location_info?.continent_code};try{if(e.pipelineBinding)await e.pipelineBinding.send([i]);else if(e.pipelineEndpoint){let t=e.timeout||3e4,n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let t=await fetch(e.pipelineEndpoint,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify([i]),signal:n.signal});if(!t.ok)throw Error(`Pipeline ingestion failed: ${t.status} ${t.statusText}`)}finally{clearTimeout(r)}}else throw Error(`Either pipelineEndpoint or pipelineBinding must be configured`)}catch(e){throw console.error(`Failed to send log to Pipeline:`,e),e}}function fe(e){return async(t,n)=>{let r=e.namespace||`default`,i=e.tableName||`logs`,a=await T(e,`
1
+ Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require("./sync-defaults-errors-pnzkP88r.js");let l=require("@authhero/adapter-interfaces"),u=require("@hono/zod-openapi"),d=require("hono/http-exception"),f=require("wretch");f=s(f);let p=require("wretch/middlewares");var m=u.z.object({code:u.z.number(),message:u.z.string()}),h=u.z.object({message:u.z.string()}),g=u.z.object({emails:u.z.array(u.z.string()).optional(),http_body:u.z.string().optional(),http_url:u.z.string().optional(),txt_name:u.z.string().optional(),txt_value:u.z.string().optional()}),_=u.z.object({ciphers:u.z.array(u.z.string()).optional(),early_hints:u.z.string().optional(),http2:u.z.string().optional(),min_tls_version:u.z.string().optional(),tls_1_3:u.z.string().optional()}),ee=u.z.object({id:u.z.string(),bundle_method:u.z.string().optional(),certificate_authority:u.z.string(),custom_certificate:u.z.string().optional(),custom_csr_id:u.z.string().optional(),custom_key:u.z.string().optional(),expires_on:u.z.string().optional(),hosts:u.z.array(u.z.string()).optional(),issuer:u.z.string().optional(),method:u.z.string(),serial_number:u.z.string().optional(),settings:_.optional(),signature:u.z.string().optional(),type:u.z.string(),uploaded_on:u.z.string().optional(),validation_errors:u.z.array(h).optional(),validation_records:u.z.array(g).optional(),wildcard:u.z.boolean()}),te=u.z.object({name:u.z.string(),type:u.z.string(),value:u.z.string()}),ne=u.z.object({http_body:u.z.string().optional(),http_url:u.z.string().optional()}),v=u.z.object({id:u.z.string(),ssl:ee,hostname:u.z.string(),custom_metadata:u.z.record(u.z.string(),u.z.string()).optional(),custom_origin_server:u.z.string().optional(),custom_origin_sni:u.z.string().optional(),ownership_verification:te.optional(),ownership_verification_http:ne.optional(),status:u.z.string(),verification_errors:u.z.array(u.z.string()).optional(),created_at:u.z.string()}),y=u.z.object({errors:u.z.array(m),messages:u.z.array(m),success:u.z.boolean(),result:v}),b=u.z.object({errors:u.z.array(m),messages:u.z.array(m),success:u.z.boolean(),result:u.z.array(v)});function x(e){return(0,f.default)(`https://api.cloudflare.com/client/v4/zones/${e.zoneId}`).headers({"X-Auth-Email":e.authEmail,"X-Auth-Key":e.authKey,"Content-Type":`application/json`}).middlewares([(0,p.retry)(),(0,p.dedupe)()])}function S(e){let t={},n={};if(!e)return{sslOverrides:t,rest:n};for(let[r,i]of Object.entries(e))r.startsWith(`ssl.`)?t[r.slice(4)]=i:n[r]=i;return{sslOverrides:t,rest:n}}function C(e){let t=[];if(e.ssl.validation_records)for(let n of e.ssl.validation_records)n.txt_name&&n.txt_value&&t.push({name:`txt`,record:n.txt_value,domain:n.txt_name});if(e.ownership_verification&&t.push({name:`txt`,record:e.ownership_verification.value,domain:e.ownership_verification.name}),e.ownership_verification_http?.http_body&&e.ownership_verification_http?.http_url&&t.push({name:`http`,http_body:e.ownership_verification_http.http_body,http_url:e.ownership_verification_http.http_url}),e.ssl.validation_records)for(let n of e.ssl.validation_records)n.http_body&&n.http_url&&t.push({name:`http`,http_body:n.http_body,http_url:n.http_url});let n={...e.domain_metadata||{},"ssl.method":e.ssl.method,"ssl.type":e.ssl.type,"ssl.certificate_authority":e.ssl.certificate_authority};return{custom_domain_id:e.id,domain:e.hostname,primary:e.primary,status:e.status===`active`?`ready`:`pending`,type:e.type??`auth0_managed_certs`,verification:{methods:u.z.array(l.verificationMethodsSchema).parse(t)},domain_metadata:n}}function re(e){let t=e instanceof Error?e.message:String(e);return/duplicate/i.test(t)}async function ie(e,t,n){let r;try{r=await x(e).get(`/custom_hostnames?hostname=${encodeURIComponent(n)}`).json()}catch{return null}let i=b.safeParse(r);if(!i.success||!i.data.success)return null;let a=i.data.result.find(e=>e.hostname.toLowerCase()===n.toLowerCase());return!a||e.enterprise&&a.custom_metadata?.tenant_id!==t?null:a}async function ae(e,t,n,r){let i=n.custom_domain_id,a;try{a=C({...n,...r})}catch(e){return console.warn(`[custom-domains] mapCustomDomainResponse failed for ${i} (tenant=${t}); keeping the stored row.`,e instanceof Error?e.message:e),{domain:n,outcome:`failed`}}if(a.status===n.status&&JSON.stringify(a.verification)===JSON.stringify(n.verification))return{domain:a,outcome:`unchanged`};try{await e.customDomainAdapter.update(t,i,{status:a.status,verification:a.verification})}catch(e){return console.warn(`[custom-domains] DB writeback failed for ${i} (tenant=${t}); returning merged response without DB sync.`,e instanceof Error?e.message:e),{domain:a,outcome:`failed`}}return{domain:a,outcome:`updated`}}function oe(e){return{create:async(t,n)=>{let{sslOverrides:r,rest:i}=S(n.domain_metadata);if(await e.customDomainAdapter.getByDomain(n.domain))throw new d.HTTPException(409,{message:`The domain ${n.domain} is already registered`});let a;try{let i=y.parse(await x(e).post({hostname:n.domain,ssl:{method:`txt`,type:`dv`,...r},custom_metadata:e.enterprise?{tenant_id:t}:void 0},`/custom_hostnames`).json());if(!i.success)throw Error(JSON.stringify(i.errors));a=i.result}catch(r){if(!re(r))throw r;let i=await ie(e,t,n.domain);if(!i)throw r;a=i}let o=C({...a,primary:!1,type:n.type,domain_metadata:i});return await e.customDomainAdapter.create(t,{custom_domain_id:o.custom_domain_id,domain:o.domain,type:o.type,domain_metadata:n.domain_metadata}),await e.customDomainAdapter.update(t,o.custom_domain_id,{status:o.status,primary:o.primary,verification:o.verification}),o},get:async(t,n)=>{let r=await e.customDomainAdapter.get(t,n);if(!r)throw new d.HTTPException(404);let i;try{i=await x(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json()}catch(e){return console.warn(`[custom-domains] CF fetch failed for ${n} (tenant=${t}); returning stale DB row:`,e instanceof Error?e.message:e),r}let a=y.safeParse(i);if(!a.success||!a.data.success)return console.warn(`[custom-domains] CF response unparseable for ${n} (tenant=${t}); returning stale DB row.`,a.success?{cfErrors:a.data.errors}:{zodIssues:a.error.issues,body:i}),r;let{result:o}=a.data;if(e.enterprise&&o.custom_metadata?.tenant_id!==t)throw new d.HTTPException(404);let{domain:s}=await ae(e,t,r,o);return s},getByDomain:async t=>e.customDomainAdapter.getByDomain(t),list:async t=>e.customDomainAdapter.list(t),remove:async(t,n)=>{if(e.enterprise){let{result:r,success:i}=y.parse(await x(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json());if(!i||r.custom_metadata?.tenant_id!==t)throw new d.HTTPException(404)}let r=await x(e).delete(`/custom_hostnames/${encodeURIComponent(n)}`).res();return r.ok&&await e.customDomainAdapter.remove(t,n),r.ok},update:async(t,n,r)=>{let{sslOverrides:i}=S(r.domain_metadata),a={};if(Object.keys(i).length>0){let t;try{t=await x(e).get(`/custom_hostnames/${encodeURIComponent(n)}`).json()}catch(e){throw new d.HTTPException(503,{message:`Failed to fetch current custom hostname state: ${e instanceof Error?e.message:String(e)}`})}let r=y.safeParse(t);if(!r.success||!r.data.success)throw new d.HTTPException(503,{message:`Failed to parse current custom hostname state: ${JSON.stringify(r.success?r.data.errors:r.error.issues)}`});a.ssl={method:r.data.result.ssl.method,type:r.data.result.ssl.type,certificate_authority:r.data.result.ssl.certificate_authority,...i}}if(Object.keys(a).length>0){let t=await x(e).patch(a,`/custom_hostnames/${encodeURIComponent(n)}`).res().catch(e=>{throw new d.HTTPException(503,{message:`Failed to update custom hostname: ${e instanceof Error?e.message:String(e)}`})});if(!t.ok)throw new d.HTTPException(503,{message:await t.text()})}return e.customDomainAdapter.update(t,n,r)},uploadCertificate:async(t,n,r)=>{let i=await e.customDomainAdapter.get(t,n);if(!i)throw new d.HTTPException(404);let a=await x(e).patch({ssl:{custom_certificate:r.certificate,custom_key:r.private_key}},`/custom_hostnames/${encodeURIComponent(n)}`).json(),{result:o,errors:s,success:c}=y.parse(a);if(!c)throw new d.HTTPException(503,{message:JSON.stringify(s)});let l=C({...i,...o});return await e.customDomainAdapter.update(t,n,{status:l.status,verification:l.verification}),l}}}var se=class{config;cache=null;constructor(e){this.config=e}async getCache(){if(this.cache)return this.cache;if(typeof caches>`u`)throw Error(`caches API is not available - CloudflareCache should only be used in Cloudflare Workers`);return this.config.cacheName?this.cache=await caches.open(this.config.cacheName):this.cache=caches.default,this.cache}getKey(e){return this.config.keyPrefix?`${this.config.keyPrefix}:${e}`:e}createRequest(e){return new Request(`https://cache.internal/${this.getKey(e)}`)}async matchWithTimeout(e,t){let n=this.config.getTimeoutMs??200;return n<=0?e.match(t):new Promise(r=>{let i=setTimeout(()=>r(void 0),n);e.match(t).then(e=>{clearTimeout(i),r(e)},()=>{clearTimeout(i),r(void 0)})})}async get(e){try{let t=await this.getCache(),n=this.createRequest(e),r=await this.matchWithTimeout(t,n);if(!r)return null;let i=await r.text();if(!i)return await this.delete(e),null;let a;try{a=JSON.parse(i)}catch{return await this.delete(e),null}return a.expiresAt&&new Date(a.expiresAt)<new Date?(await this.delete(e),null):a.value}catch(t){return console.error(`CloudflareCache: get error for key ${e}:`,t),null}}async set(e,t,n){try{let r=await this.getCache(),i=n??this.config.defaultTtlSeconds,a=i!==void 0,o=a?Math.max(0,i):0,s={value:t,expiresAt:a?new Date(Date.now()+(o>0?o*1e3:-1)).toISOString():void 0,cachedAt:new Date().toISOString()},c=this.createRequest(e),l={"Content-Type":`application/json`};a&&o>0&&(l[`Cache-Control`]=`max-age=${o}`);let u=new Response(JSON.stringify(s),{headers:l});await r.put(c,u)}catch(t){console.error(`CloudflareCache: set error for key ${e}:`,t)}}async delete(e){try{let t=await this.getCache(),n=this.createRequest(e);return await t.delete(n)}catch(t){return console.error(`CloudflareCache: delete error for key ${e}:`,t),!1}}async deleteByPrefix(e){return console.warn(`CloudflareCache.deleteByPrefix() is not implemented - Cloudflare Cache API does not support prefix-based deletion`),0}async clear(){console.warn(`CloudflareCache.clear() is not implemented - Cloudflare Cache API does not support clearing all entries`)}};function ce(e={}){return new se({defaultTtlSeconds:300,keyPrefix:`authhero`,getTimeoutMs:200,...e})}var le=`useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict`,w=(e=21)=>{let t=``,n=crypto.getRandomValues(new Uint8Array(e|=0));for(;e--;)t+=le[n[e]&63];return t};async function T(e,t){let n=e.timeout||3e4,r=new AbortController,i=setTimeout(()=>r.abort(),n);try{let n=`https://api.sql.cloudflarestorage.com/api/v1/accounts/${e.accountId}/r2-sql/query/${e.warehouseName}`,i=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${e.authToken}`},body:JSON.stringify({query:t}),signal:r.signal});if(!i.ok)throw Error(`R2 SQL query failed: ${i.status} ${i.statusText}`);let a=await i.json();if(!a.success&&a.errors)throw Error(`R2 SQL error: ${a.errors.join(`, `)}`);return a.data||a.result?.data||[]}finally{clearTimeout(i)}}function E(e){return`'${e.replace(/'/g,`''`)}'`}function D(e){return`"${e.replace(/"/g,`""`)}"`}function O(e){let t=e=>{if(!e)return``;try{return JSON.parse(e)}catch{return e}};return{type:e.type,date:e.date,description:e.description,ip:e.ip,user_agent:e.user_agent,details:t(e.details),isMobile:!!e.isMobile,user_id:e.user_id,user_name:e.user_name,connection:e.connection,connection_id:e.connection_id,client_id:e.client_id,client_name:e.client_name,audience:e.audience,scope:e.scope,strategy:e.strategy,strategy_type:e.strategy_type,hostname:e.hostname,auth0_client:t(e.auth0_client),log_id:e.id,location_info:e.country_code||e.city_name||e.latitude||e.longitude||e.time_zone||e.continent_code?{country_code:e.country_code||``,city_name:e.city_name||``,latitude:e.latitude||``,longitude:e.longitude||``,time_zone:e.time_zone||``,continent_code:e.continent_code||``}:void 0}}function ue(e){return async(t,n)=>{let r=n.log_id||w(),i={...n,log_id:r};return await de(e,t,i),i}}async function de(e,t,n){let r=e=>e?JSON.stringify(e):void 0,i={id:n.log_id,tenant_id:t,type:n.type,date:n.date,description:n.description?.substring(0,256),ip:n.ip,user_agent:n.user_agent,details:r(n.details)?.substring(0,8192),isMobile:+!!n.isMobile,user_id:n.user_id,user_name:n.user_name,connection:n.connection,connection_id:n.connection_id,client_id:n.client_id,client_name:n.client_name,audience:n.audience,scope:n.scope,strategy:n.strategy,strategy_type:n.strategy_type,hostname:n.hostname,auth0_client:r(n.auth0_client),log_id:n.log_id,country_code:n.location_info?.country_code,city_name:n.location_info?.city_name,latitude:n.location_info?.latitude,longitude:n.location_info?.longitude,time_zone:n.location_info?.time_zone,continent_code:n.location_info?.continent_code};try{if(e.pipelineBinding)await e.pipelineBinding.send([i]);else if(e.pipelineEndpoint){let t=e.timeout||3e4,n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let t=await fetch(e.pipelineEndpoint,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify([i]),signal:n.signal});if(!t.ok)throw Error(`Pipeline ingestion failed: ${t.status} ${t.statusText}`)}finally{clearTimeout(r)}}else throw Error(`Either pipelineEndpoint or pipelineBinding must be configured`)}catch(e){throw console.error(`Failed to send log to Pipeline:`,e),e}}function fe(e){return async(t,n)=>{let r=e.namespace||`default`,i=e.tableName||`logs`,a=await T(e,`
2
2
  SELECT * FROM ${D(r)}.${D(i)}
3
3
  WHERE tenant_id = ${E(t)}
4
4
  AND id = ${E(n)}
@@ -1,4 +1,4 @@
1
- import { a as e, i as t, n, t as r } from "./sync-defaults-errors-BlLZh6Gt.mjs";
1
+ import { a as e, i as t, n, t as r } from "./sync-defaults-errors-CKdx0nzD.mjs";
2
2
  import { TRIGGER_API_SHAPES as i, TRIGGER_FUNCTION_NAMES as a, actionExecutionStatusSchema as o, tokenizeLuceneQuery as s, unescapeLuceneValue as c, verificationMethodsSchema as l } from "@authhero/adapter-interfaces";
3
3
  import { z as u } from "@hono/zod-openapi";
4
4
  import { HTTPException as d } from "hono/http-exception";
@@ -242,8 +242,10 @@ function f(e) {
242
242
  //#region src/wfp-provisioner/sync-defaults-errors.ts
243
243
  function p(e) {
244
244
  if (typeof e != "object" || !e) return [];
245
- let t = [];
246
- 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);
245
+ let t = [], n = (e) => {
246
+ if (typeof e == "object" && e && "errors" in e && Array.isArray(e.errors)) for (let n of e.errors) typeof n == "string" && t.push(n);
247
+ };
248
+ for (let [t, r] of Object.entries(e)) if (n(r), t === "resolved" && typeof r == "object" && r && "entities" in r && typeof r.entities == "object" && r.entities !== null) for (let e of Object.values(r.entities)) n(e);
247
249
  return t;
248
250
  }
249
251
  //#endregion
@@ -1 +1 @@
1
- var e=class extends Error{status;endpoint;errors;body;constructor(e,n,r,i=[]){super(`Cloudflare API ${e} ${n}: ${t(r,256)}`),this.name=`CloudflareApiError`,this.status=e,this.endpoint=n,this.body=r,this.errors=i}};function t(e,t){return e.length<=t?e:`${e.slice(0,t)}…`}var n=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(t,n,r){let i=`${this.baseUrl}${n}`,a=new AbortController,o=setTimeout(()=>a.abort(),this.timeoutMs),s={Authorization:`Bearer ${this.apiToken}`,...r?.headers??{}};r?.body&&!(r.body instanceof FormData)&&!s[`Content-Type`]&&(s[`Content-Type`]=`application/json`);let c;try{c=await this.fetchImpl(i,{method:t,headers:s,body:r?.body,signal:a.signal})}finally{clearTimeout(o)}let l=await c.text();if(!c.ok){let t=[];try{let e=JSON.parse(l);Array.isArray(e.errors)&&(t=e.errors)}catch{}throw new e(c.status,n,l,t)}if(!(l===``||c.status===204))return JSON.parse(l)}},r=`{tenant_id}`,i=`tenant-{tenant_id}`,a=`index.js`,o=`2026-05-01`,s=64;function c(e,t){return e.replace(/\{tenant_id\}/g,t)}function l(t){if(!(t instanceof e))return!1;let n=t.body.toLowerCase();return t.status===409||n.includes(`already exists`)||n.includes(`name is already taken`)||n.includes(`already in use`)}function u(t){return t instanceof e?t.status===404:!1}function d(e){return e.replace(/'/g,`''`)}function f(e){let t=new n({accountId:e.accountId,apiToken:e.apiToken,fetch:e.fetch,timeoutMs:e.timeoutMs}),f=e.scriptNameTemplate??r,p=e.d1NameTemplate??i,m=e.scriptMetadata?.main_module??a,h=e.scriptMetadata?.compatibility_date??o,g=e.scriptMetadata?.compatibility_flags??[`nodejs_compat`],_=e.dispatchNamespace,v=e.logger,y=`_authhero_provisioner_migrations`;function b(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 x(e){return b(await t.execD1(e,`SELECT name FROM sqlite_master WHERE type='table' AND name='${y}';`),`name`).length>0}async function S(e){await t.execD1(e,`CREATE TABLE IF NOT EXISTS ${y} (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL);`)}async function C(e){let n=await t.execD1(e,`SELECT name FROM ${y};`);return new Set(b(n,`name`))}async function w(e,n){let r=new Date().toISOString();await t.execD1(e,`INSERT OR IGNORE INTO ${y} (name, applied_at) VALUES ('${d(n)}', '${d(r)}');`)}async function T(n){let r=await C(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 w(n,i.name)}}return{client:t,names(e){return{scriptName:c(f,e),databaseName:c(p,e)}},validate(){let t=e.migrations[e.migrations.length-1]?.name;if(t!==void 0&&t.length>s)throw Error(`Migration name "${t}" exceeds the ${s}-character database_version limit.`);return{databaseVersion:t,bundleConfiguration:e.bundleConfiguration,workerVersion:e.workerVersion}},async findOrCreateDatabase(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(!l(n))throw n;let r=(await t.listD1Databases(e)).find(t=>t.name===e);if(r)return{id:r.uuid,created:!1};throw n}},async applyMigrations(t,n){let r=n?!1:await x(t);if(n||r)await S(t),await T(t);else{v?.warn(`D1 ${t} has no migration-tracking table — assuming it predates tracking and is fully migrated; backfilling the tracking table and skipping migrations.`),await S(t);for(let n of e.migrations)await w(t,n.name)}},async uploadScript(n,r){let i=[{type:`d1`,name:`AUTH_DB`,id:r},{type:`plain_text`,name:`CONTROL_PLANE_BASE_URL`,text:e.controlPlaneBaseUrl},...e.extraBindings??[]];await t.uploadNamespacedScript(_,n,{script:e.tenantWorkerScript,mainModule:m,compatibilityDate:h,compatibilityFlags:g,bindings:i,tags:[`authhero-tenant`,`tenant:${n}`]})},async uploadSecrets(n,r){let i=await e.secrets(r);for(let[e,r]of Object.entries(i))await t.setNamespacedScriptSecret(_,n,e,r)},async deprovision(e){let n=c(f,e),r=c(p,e),i=[];try{await t.deleteNamespacedScript(_,n)}catch(e){u(e)||i.push(e)}try{let e=(await t.listD1Databases(r)).find(e=>e.name===r);if(e)try{await t.deleteD1Database(e.uuid)}catch(e){u(e)||i.push(e)}}catch(e){i.push(e)}if(i.length>0){let t=i.map(e=>e instanceof Error?e.message:String(e)).join(`; `);throw Error(`Deprovision of tenant "${e}" had ${i.length} failure(s): ${t}`,{cause:i[0]})}}}}function p(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}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return p}});
1
+ var e=class extends Error{status;endpoint;errors;body;constructor(e,n,r,i=[]){super(`Cloudflare API ${e} ${n}: ${t(r,256)}`),this.name=`CloudflareApiError`,this.status=e,this.endpoint=n,this.body=r,this.errors=i}};function t(e,t){return e.length<=t?e:`${e.slice(0,t)}…`}var n=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(t,n,r){let i=`${this.baseUrl}${n}`,a=new AbortController,o=setTimeout(()=>a.abort(),this.timeoutMs),s={Authorization:`Bearer ${this.apiToken}`,...r?.headers??{}};r?.body&&!(r.body instanceof FormData)&&!s[`Content-Type`]&&(s[`Content-Type`]=`application/json`);let c;try{c=await this.fetchImpl(i,{method:t,headers:s,body:r?.body,signal:a.signal})}finally{clearTimeout(o)}let l=await c.text();if(!c.ok){let t=[];try{let e=JSON.parse(l);Array.isArray(e.errors)&&(t=e.errors)}catch{}throw new e(c.status,n,l,t)}if(!(l===``||c.status===204))return JSON.parse(l)}},r=`{tenant_id}`,i=`tenant-{tenant_id}`,a=`index.js`,o=`2026-05-01`,s=64;function c(e,t){return e.replace(/\{tenant_id\}/g,t)}function l(t){if(!(t instanceof e))return!1;let n=t.body.toLowerCase();return t.status===409||n.includes(`already exists`)||n.includes(`name is already taken`)||n.includes(`already in use`)}function u(t){return t instanceof e?t.status===404:!1}function d(e){return e.replace(/'/g,`''`)}function f(e){let t=new n({accountId:e.accountId,apiToken:e.apiToken,fetch:e.fetch,timeoutMs:e.timeoutMs}),f=e.scriptNameTemplate??r,p=e.d1NameTemplate??i,m=e.scriptMetadata?.main_module??a,h=e.scriptMetadata?.compatibility_date??o,g=e.scriptMetadata?.compatibility_flags??[`nodejs_compat`],_=e.dispatchNamespace,v=e.logger,y=`_authhero_provisioner_migrations`;function b(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 x(e){return b(await t.execD1(e,`SELECT name FROM sqlite_master WHERE type='table' AND name='${y}';`),`name`).length>0}async function S(e){await t.execD1(e,`CREATE TABLE IF NOT EXISTS ${y} (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL);`)}async function C(e){let n=await t.execD1(e,`SELECT name FROM ${y};`);return new Set(b(n,`name`))}async function w(e,n){let r=new Date().toISOString();await t.execD1(e,`INSERT OR IGNORE INTO ${y} (name, applied_at) VALUES ('${d(n)}', '${d(r)}');`)}async function T(n){let r=await C(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 w(n,i.name)}}return{client:t,names(e){return{scriptName:c(f,e),databaseName:c(p,e)}},validate(){let t=e.migrations[e.migrations.length-1]?.name;if(t!==void 0&&t.length>s)throw Error(`Migration name "${t}" exceeds the ${s}-character database_version limit.`);return{databaseVersion:t,bundleConfiguration:e.bundleConfiguration,workerVersion:e.workerVersion}},async findOrCreateDatabase(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(!l(n))throw n;let r=(await t.listD1Databases(e)).find(t=>t.name===e);if(r)return{id:r.uuid,created:!1};throw n}},async applyMigrations(t,n){let r=n?!1:await x(t);if(n||r)await S(t),await T(t);else{v?.warn(`D1 ${t} has no migration-tracking table — assuming it predates tracking and is fully migrated; backfilling the tracking table and skipping migrations.`),await S(t);for(let n of e.migrations)await w(t,n.name)}},async uploadScript(n,r){let i=[{type:`d1`,name:`AUTH_DB`,id:r},{type:`plain_text`,name:`CONTROL_PLANE_BASE_URL`,text:e.controlPlaneBaseUrl},...e.extraBindings??[]];await t.uploadNamespacedScript(_,n,{script:e.tenantWorkerScript,mainModule:m,compatibilityDate:h,compatibilityFlags:g,bindings:i,tags:[`authhero-tenant`,`tenant:${n}`]})},async uploadSecrets(n,r){let i=await e.secrets(r);for(let[e,r]of Object.entries(i))await t.setNamespacedScriptSecret(_,n,e,r)},async deprovision(e){let n=c(f,e),r=c(p,e),i=[];try{await t.deleteNamespacedScript(_,n)}catch(e){u(e)||i.push(e)}try{let e=(await t.listD1Databases(r)).find(e=>e.name===r);if(e)try{await t.deleteD1Database(e.uuid)}catch(e){u(e)||i.push(e)}}catch(e){i.push(e)}if(i.length>0){let t=i.map(e=>e instanceof Error?e.message:String(e)).join(`; `);throw Error(`Deprovision of tenant "${e}" had ${i.length} failure(s): ${t}`,{cause:i[0]})}}}}function p(e){if(typeof e!=`object`||!e)return[];let t=[],n=e=>{if(typeof e==`object`&&e&&`errors`in e&&Array.isArray(e.errors))for(let n of e.errors)typeof n==`string`&&t.push(n)};for(let[t,r]of Object.entries(e))if(n(r),t===`resolved`&&typeof r==`object`&&r&&`entities`in r&&typeof r.entities==`object`&&r.entities!==null)for(let e of Object.values(r.entities))n(e);return t}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return p}});