@authhero/cloudflare-adapter 2.38.15 → 3.0.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.
@@ -96,7 +96,7 @@ function l(t) {
96
96
  return t.status === 409 || n.includes("already exists") || n.includes("name is already taken") || n.includes("already in use");
97
97
  }
98
98
  function u(t) {
99
- return t instanceof e && t.status === 404;
99
+ return t instanceof e ? t.status === 404 : !1;
100
100
  }
101
101
  function d(e) {
102
102
  return e.replace(/'/g, "''");
@@ -180,7 +180,7 @@ function f(e) {
180
180
  }
181
181
  },
182
182
  async applyMigrations(t, n) {
183
- let r = !n && await x(t);
183
+ let r = n ? !1 : await x(t);
184
184
  if (n || r) await S(t), await T(t);
185
185
  else {
186
186
  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);
@@ -0,0 +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}});