@authhero/drizzle 0.41.0 → 0.43.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,13 +1,13 @@
1
- "use strict";var wr=Object.defineProperty;var Nr=(n,i,e)=>i in n?wr(n,i,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[i]=e;var p=(n,i,e)=>Nr(n,typeof i!="symbol"?i+"":i,e);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const v=Symbol.for("drizzle:entityKind");function X(n,i){if(!n||typeof n!="object")return!1;if(n instanceof i)return!0;if(!Object.prototype.hasOwnProperty.call(i,v))throw new Error(`Class "${i.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let e=Object.getPrototypeOf(n).constructor;if(e)for(;e;){if(v in e&&e[v]===i[v])return!0;e=Object.getPrototypeOf(e)}return!1}var Mt;Mt=v;class Qe{constructor(i,e){p(this,"name");p(this,"keyAsName");p(this,"primary");p(this,"notNull");p(this,"default");p(this,"defaultFn");p(this,"onUpdateFn");p(this,"hasDefault");p(this,"isUnique");p(this,"uniqueName");p(this,"uniqueType");p(this,"dataType");p(this,"columnType");p(this,"enumValues");p(this,"generated");p(this,"generatedIdentity");p(this,"config");this.table=i,this.config=e,this.name=e.name,this.keyAsName=e.keyAsName,this.notNull=e.notNull,this.default=e.default,this.defaultFn=e.defaultFn,this.onUpdateFn=e.onUpdateFn,this.hasDefault=e.hasDefault,this.primary=e.primaryKey,this.isUnique=e.isUnique,this.uniqueName=e.uniqueName,this.uniqueType=e.uniqueType,this.dataType=e.dataType,this.columnType=e.columnType,this.generated=e.generated,this.generatedIdentity=e.generatedIdentity}mapFromDriverValue(i){return i}mapToDriverValue(i){return i}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}p(Qe,Mt,"Column");var Vt;Vt=v;class qi{constructor(i,e,t){p(this,"config");p(this,"$default",this.$defaultFn);p(this,"$onUpdate",this.$onUpdateFn);this.config={name:i,keyAsName:i==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:e,columnType:t,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(i){return this.config.default=i,this.config.hasDefault=!0,this}$defaultFn(i){return this.config.defaultFn=i,this.config.hasDefault=!0,this}$onUpdateFn(i){return this.config.onUpdateFn=i,this.config.hasDefault=!0,this}primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(i){this.config.name===""&&(this.config.name=i)}}p(qi,Vt,"ColumnBuilder");const ze=Symbol.for("drizzle:Name"),Tt=Symbol.for("drizzle:isPgEnum");function vr(n){return!!n&&typeof n=="function"&&Tt in n&&n[Tt]===!0}var Rt;Rt=v;class bt{constructor(i,e,t,r=!1,o=[]){this._={brand:"Subquery",sql:i,selectedFields:e,alias:t,isWith:r,usedTables:o}}}p(bt,Rt,"Subquery");const Sr={startActiveSpan(n,i){return i()}},Ce=Symbol.for("drizzle:ViewBaseConfig"),Xe=Symbol.for("drizzle:Schema"),qt=Symbol.for("drizzle:Columns"),Lt=Symbol.for("drizzle:ExtraConfigColumns"),Ze=Symbol.for("drizzle:OriginalName"),et=Symbol.for("drizzle:BaseName"),Ve=Symbol.for("drizzle:IsAlias"),Et=Symbol.for("drizzle:ExtraConfigBuilder"),xr=Symbol.for("drizzle:IsDrizzleTable");var Wt,Ht,Gt,Yt,Xt,Zt,en,tn,nn,rn;rn=v,nn=ze,tn=Ze,en=Xe,Zt=qt,Xt=Lt,Yt=et,Gt=Ve,Ht=xr,Wt=Et;class M{constructor(i,e,t){p(this,nn);p(this,tn);p(this,en);p(this,Zt);p(this,Xt);p(this,Yt);p(this,Gt,!1);p(this,Ht,!0);p(this,Wt);this[ze]=this[Ze]=i,this[Xe]=e,this[et]=t}}p(M,rn,"Table"),p(M,"Symbol",{Name:ze,Schema:Xe,OriginalName:Ze,Columns:qt,ExtraConfigColumns:Lt,BaseName:et,IsAlias:Ve,ExtraConfigBuilder:Et});function Li(n){return n!=null&&typeof n.getSQL=="function"}function br(n){var e;const i={sql:"",params:[]};for(const t of n)i.sql+=t.sql,i.params.push(...t.params),(e=t.typings)!=null&&e.length&&(i.typings||(i.typings=[]),i.typings.push(...t.typings));return i}var sn;sn=v;class Z{constructor(i){p(this,"value");this.value=Array.isArray(i)?i:[i]}getSQL(){return new F([this])}}p(Z,sn,"StringChunk");var on;on=v;const De=class De{constructor(i){p(this,"decoder",Ei);p(this,"shouldInlineParams",!1);p(this,"usedTables",[]);this.queryChunks=i;for(const e of i)if(X(e,M)){const t=e[M.Symbol.Schema];this.usedTables.push(t===void 0?e[M.Symbol.Name]:t+"."+e[M.Symbol.Name])}}append(i){return this.queryChunks.push(...i.queryChunks),this}toQuery(i){return Sr.startActiveSpan("drizzle.buildSQL",e=>{const t=this.buildQueryFromSourceParams(this.queryChunks,i);return e==null||e.setAttributes({"drizzle.query.text":t.sql,"drizzle.query.params":JSON.stringify(t.params)}),t})}buildQueryFromSourceParams(i,e){const t=Object.assign({},e,{inlineParams:e.inlineParams||this.shouldInlineParams,paramStartIndex:e.paramStartIndex||{value:0}}),{casing:r,escapeName:o,escapeParam:l,prepareTyping:_,inlineParams:u,paramStartIndex:c}=t;return br(i.map(d=>{var h;if(X(d,Z))return{sql:d.value.join(""),params:[]};if(X(d,Re))return{sql:o(d.value),params:[]};if(d===void 0)return{sql:"",params:[]};if(Array.isArray(d)){const f=[new Z("(")];for(const[y,N]of d.entries())f.push(N),y<d.length-1&&f.push(new Z(", "));return f.push(new Z(")")),this.buildQueryFromSourceParams(f,t)}if(X(d,De))return this.buildQueryFromSourceParams(d.queryChunks,{...t,inlineParams:u||d.shouldInlineParams});if(X(d,M)){const f=d[M.Symbol.Schema],y=d[M.Symbol.Name];return{sql:f===void 0||d[Ve]?o(y):o(f)+"."+o(y),params:[]}}if(X(d,Qe)){const f=r.getColumnCasing(d);if(e.invokeSource==="indexes")return{sql:o(f),params:[]};const y=d.table[M.Symbol.Schema];return{sql:d.table[Ve]||y===void 0?o(d.table[M.Symbol.Name])+"."+o(f):o(y)+"."+o(d.table[M.Symbol.Name])+"."+o(f),params:[]}}if(X(d,Dt)){const f=d[Ce].schema,y=d[Ce].name;return{sql:f===void 0||d[Ce].isAlias?o(y):o(f)+"."+o(y),params:[]}}if(X(d,Ae)){if(X(d.value,Be))return{sql:l(c.value++,d),params:[d],typings:["none"]};const f=d.value===null?null:d.encoder.mapToDriverValue(d.value);if(X(f,De))return this.buildQueryFromSourceParams([f],t);if(u)return{sql:this.mapInlineParam(f,t),params:[]};let y=["none"];return _&&(y=[_(d.encoder)]),{sql:l(c.value++,f),params:[f],typings:y}}return X(d,Be)?{sql:l(c.value++,d),params:[d],typings:["none"]}:X(d,De.Aliased)&&d.fieldAlias!==void 0?{sql:o(d.fieldAlias),params:[]}:X(d,bt)?d._.isWith?{sql:o(d._.alias),params:[]}:this.buildQueryFromSourceParams([new Z("("),d._.sql,new Z(") "),new Re(d._.alias)],t):vr(d)?d.schema?{sql:o(d.schema)+"."+o(d.enumName),params:[]}:{sql:o(d.enumName),params:[]}:Li(d)?(h=d.shouldOmitSQLParens)!=null&&h.call(d)?this.buildQueryFromSourceParams([d.getSQL()],t):this.buildQueryFromSourceParams([new Z("("),d.getSQL(),new Z(")")],t):u?{sql:this.mapInlineParam(d,t),params:[]}:{sql:l(c.value++,d),params:[d],typings:["none"]}}))}mapInlineParam(i,{escapeString:e}){if(i===null)return"null";if(typeof i=="number"||typeof i=="boolean")return i.toString();if(typeof i=="string")return e(i);if(typeof i=="object"){const t=i.toString();return e(t==="[object Object]"?JSON.stringify(i):t)}throw new Error("Unexpected param value: "+i)}getSQL(){return this}as(i){return i===void 0?this:new De.Aliased(this,i)}mapWith(i){return this.decoder=typeof i=="function"?{mapFromDriverValue:i}:i,this}inlineParams(){return this.shouldInlineParams=!0,this}if(i){return i?this:void 0}};p(De,on,"SQL");let F=De;var an;an=v;class Re{constructor(i){p(this,"brand");this.value=i}getSQL(){return new F([this])}}p(Re,an,"Name");function Dr(n){return typeof n=="object"&&n!==null&&"mapToDriverValue"in n&&typeof n.mapToDriverValue=="function"}const Ei={mapFromDriverValue:n=>n},Ci={mapToDriverValue:n=>n};({...Ei,...Ci});var ln;ln=v;class Ae{constructor(i,e=Ci){p(this,"brand");this.value=i,this.encoder=e}getSQL(){return new F([this])}}p(Ae,ln,"Param");function w(n,...i){const e=[];(i.length>0||n.length>0&&n[0]!=="")&&e.push(new Z(n[0]));for(const[t,r]of i.entries())e.push(r,new Z(n[t+1]));return new F(e)}(n=>{function i(){return new F([])}n.empty=i;function e(u){return new F(u)}n.fromList=e;function t(u){return new F([new Z(u)])}n.raw=t;function r(u,c){const d=[];for(const[h,f]of u.entries())h>0&&c!==void 0&&d.push(c),d.push(f);return new F(d)}n.join=r;function o(u){return new Re(u)}n.identifier=o;function l(u){return new Be(u)}n.placeholder=l;function _(u,c){return new Ae(u,c)}n.param=_})(w||(w={}));(n=>{var e;e=v;const t=class t{constructor(o,l){p(this,"isSelectionField",!1);this.sql=o,this.fieldAlias=l}getSQL(){return this.sql}clone(){return new t(this.sql,this.fieldAlias)}};p(t,e,"SQL.Aliased");let i=t;n.Aliased=i})(F||(F={}));var _n;_n=v;class Be{constructor(i){this.name=i}getSQL(){return new F([this])}}p(Be,_n,"Placeholder");const Or=Symbol.for("drizzle:IsDrizzleView");var un,dn,cn;cn=v,dn=Ce,un=Or;class Dt{constructor({name:i,schema:e,selectedFields:t,query:r}){p(this,dn);p(this,un,!0);this[Ce]={name:i,originalName:i,schema:e,selectedFields:t,query:r,isExisting:!r,isAlias:!1}}getSQL(){return new F([this])}}p(Dt,cn,"View");Qe.prototype.getSQL=function(){return new F([this])};M.prototype.getSQL=function(){return new F([this])};bt.prototype.getSQL=function(){return new F([this])};function Je(n,i){return{name:typeof n=="string"&&n.length>0?n:"",config:typeof n=="object"?n:i}}const Ai=typeof TextDecoder>"u"?null:new TextDecoder;function xe(n,i){return Dr(i)&&!Li(n)&&!X(n,Ae)&&!X(n,Be)&&!X(n,Qe)&&!X(n,M)&&!X(n,Dt)?new Ae(n,i):n}const a=(n,i)=>w`${n} = ${xe(i,n)}`,kr=(n,i)=>w`${n} <> ${xe(i,n)}`;function g(...n){const i=n.filter(e=>e!==void 0);if(i.length!==0)return i.length===1?new F(i):new F([new Z("("),w.join(i,new Z(" and ")),new Z(")")])}function de(...n){const i=n.filter(e=>e!==void 0);if(i.length!==0)return i.length===1?new F(i):new F([new Z("("),w.join(i,new Z(" or ")),new Z(")")])}const We=(n,i)=>w`${n} > ${xe(i,n)}`,He=(n,i)=>w`${n} >= ${xe(i,n)}`,we=(n,i)=>w`${n} < ${xe(i,n)}`,Oe=(n,i)=>w`${n} <= ${xe(i,n)}`;function Ne(n,i){return Array.isArray(i)?i.length===0?w`false`:w`${n} in ${i.map(e=>xe(e,n))}`:w`${n} in ${xe(i,n)}`}function me(n){return w`${n} is null`}function Me(n){return w`${n} is not null`}function Ie(n,i){return w`${n} like ${i}`}function G(n){return w`${n} asc`}function V(n){return w`${n} desc`}function R(n){return w`count(${w.raw("*")})`.mapWith(Number)}function Ir(){const n=i=>{throw new Error(`Actions are not implemented in the Drizzle adapter (called ${i}). Use the Kysely adapter for tenants that require actions.`)};return{create:()=>n("create"),get:()=>n("get"),list:()=>n("list"),update:()=>n("update"),remove:()=>n("remove")}}var gn;gn=v;class Bi{constructor(i,e){p(this,"reference");p(this,"_onUpdate");p(this,"_onDelete");this.reference=()=>{const{name:t,columns:r,foreignColumns:o}=i();return{name:t,columns:r,foreignTable:o[0].table,foreignColumns:o}},e&&(this._onUpdate=e.onUpdate,this._onDelete=e.onDelete)}onUpdate(i){return this._onUpdate=i,this}onDelete(i){return this._onDelete=i,this}build(i){return new $i(i,this)}}p(Bi,gn,"SQLiteForeignKeyBuilder");var fn;fn=v;class $i{constructor(i,e){p(this,"reference");p(this,"onUpdate");p(this,"onDelete");this.table=i,this.reference=e.reference,this.onUpdate=e._onUpdate,this.onDelete=e._onDelete}getName(){const{name:i,columns:e,foreignColumns:t}=this.reference(),r=e.map(_=>_.name),o=t.map(_=>_.name),l=[this.table[ze],...r,t[0].table[ze],...o];return i??`${l.join("_")}_fk`}}p($i,fn,"SQLiteForeignKey");function zr(n,i){return`${n[ze]}_${i.join("_")}_unique`}var pn,hn;class ce extends(hn=qi,pn=v,hn){constructor(){super(...arguments);p(this,"foreignKeyConfigs",[])}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e){return this.config.isUnique=!0,this.config.uniqueName=e,this}generatedAlwaysAs(e,t){return this.config.generated={as:e,type:"always",mode:(t==null?void 0:t.mode)??"virtual"},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:o})=>((l,_)=>{const u=new Bi(()=>{const c=l();return{columns:[e],foreignColumns:[c]}});return _.onUpdate&&u.onUpdate(_.onUpdate),_.onDelete&&u.onDelete(_.onDelete),u.build(t)})(r,o))}}p(ce,pn,"SQLiteColumnBuilder");var mn,yn;class ge extends(yn=Qe,mn=v,yn){constructor(i,e){e.uniqueName||(e.uniqueName=zr(i,[e.name])),super(i,e),this.table=i}}p(ge,mn,"SQLiteColumn");var wn,Nn;class Qi extends(Nn=ce,wn=v,Nn){constructor(i){super(i,"bigint","SQLiteBigInt")}build(i){return new Ji(i,this.config)}}p(Qi,wn,"SQLiteBigIntBuilder");var vn,Sn;class Ji extends(Sn=ge,vn=v,Sn){getSQLType(){return"blob"}mapFromDriverValue(i){if(typeof Buffer<"u"&&Buffer.from){const e=Buffer.isBuffer(i)?i:i instanceof ArrayBuffer?Buffer.from(i):i.buffer?Buffer.from(i.buffer,i.byteOffset,i.byteLength):Buffer.from(i);return BigInt(e.toString("utf8"))}return BigInt(Ai.decode(i))}mapToDriverValue(i){return Buffer.from(i.toString())}}p(Ji,vn,"SQLiteBigInt");var xn,bn;class Pi extends(bn=ce,xn=v,bn){constructor(i){super(i,"json","SQLiteBlobJson")}build(i){return new Fi(i,this.config)}}p(Pi,xn,"SQLiteBlobJsonBuilder");var Dn,On;class Fi extends(On=ge,Dn=v,On){getSQLType(){return"blob"}mapFromDriverValue(i){if(typeof Buffer<"u"&&Buffer.from){const e=Buffer.isBuffer(i)?i:i instanceof ArrayBuffer?Buffer.from(i):i.buffer?Buffer.from(i.buffer,i.byteOffset,i.byteLength):Buffer.from(i);return JSON.parse(e.toString("utf8"))}return JSON.parse(Ai.decode(i))}mapToDriverValue(i){return Buffer.from(JSON.stringify(i))}}p(Fi,Dn,"SQLiteBlobJson");var kn,In;class Ui extends(In=ce,kn=v,In){constructor(i){super(i,"buffer","SQLiteBlobBuffer")}build(i){return new Ki(i,this.config)}}p(Ui,kn,"SQLiteBlobBufferBuilder");var zn,Tn;class Ki extends(Tn=ge,zn=v,Tn){mapFromDriverValue(i){return Buffer.isBuffer(i)?i:Buffer.from(i)}getSQLType(){return"blob"}}p(Ki,zn,"SQLiteBlobBuffer");function Tr(n,i){const{name:e,config:t}=Je(n,i);return(t==null?void 0:t.mode)==="json"?new Pi(e):(t==null?void 0:t.mode)==="bigint"?new Qi(e):new Ui(e)}var qn,Ln;class ji extends(Ln=ce,qn=v,Ln){constructor(i,e,t){super(i,"custom","SQLiteCustomColumn"),this.config.fieldConfig=e,this.config.customTypeParams=t}build(i){return new Mi(i,this.config)}}p(ji,qn,"SQLiteCustomColumnBuilder");var En,Cn;class Mi extends(Cn=ge,En=v,Cn){constructor(e,t){super(e,t);p(this,"sqlName");p(this,"mapTo");p(this,"mapFrom");this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom=="function"?this.mapFrom(e):e}mapToDriverValue(e){return typeof this.mapTo=="function"?this.mapTo(e):e}}p(Mi,En,"SQLiteCustomColumn");function qr(n){return(i,e)=>{const{name:t,config:r}=Je(i,e);return new ji(t,r,n)}}var An,Bn;class Ge extends(Bn=ce,An=v,Bn){constructor(i,e,t){super(i,e,t),this.config.autoIncrement=!1}primaryKey(i){return i!=null&&i.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}}p(Ge,An,"SQLiteBaseIntegerBuilder");var $n,Qn;class Ye extends(Qn=ge,$n=v,Qn){constructor(){super(...arguments);p(this,"autoIncrement",this.config.autoIncrement)}getSQLType(){return"integer"}}p(Ye,$n,"SQLiteBaseInteger");var Jn,Pn;class Vi extends(Pn=Ge,Jn=v,Pn){constructor(i){super(i,"number","SQLiteInteger")}build(i){return new Ri(i,this.config)}}p(Vi,Jn,"SQLiteIntegerBuilder");var Fn,Un;class Ri extends(Un=Ye,Fn=v,Un){}p(Ri,Fn,"SQLiteInteger");var Kn,jn;class Wi extends(jn=Ge,Kn=v,jn){constructor(i,e){super(i,"date","SQLiteTimestamp"),this.config.mode=e}defaultNow(){return this.default(w`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(i){return new Hi(i,this.config)}}p(Wi,Kn,"SQLiteTimestampBuilder");var Mn,Vn;class Hi extends(Vn=Ye,Mn=v,Vn){constructor(){super(...arguments);p(this,"mode",this.config.mode)}mapFromDriverValue(e){return this.config.mode==="timestamp"?new Date(e*1e3):new Date(e)}mapToDriverValue(e){const t=e.getTime();return this.config.mode==="timestamp"?Math.floor(t/1e3):t}}p(Hi,Mn,"SQLiteTimestamp");var Rn,Wn;class Gi extends(Wn=Ge,Rn=v,Wn){constructor(i,e){super(i,"boolean","SQLiteBoolean"),this.config.mode=e}build(i){return new Yi(i,this.config)}}p(Gi,Rn,"SQLiteBooleanBuilder");var Hn,Gn;class Yi extends(Gn=Ye,Hn=v,Gn){constructor(){super(...arguments);p(this,"mode",this.config.mode)}mapFromDriverValue(e){return Number(e)===1}mapToDriverValue(e){return e?1:0}}p(Yi,Hn,"SQLiteBoolean");function m(n,i){const{name:e,config:t}=Je(n,i);return(t==null?void 0:t.mode)==="timestamp"||(t==null?void 0:t.mode)==="timestamp_ms"?new Wi(e,t.mode):(t==null?void 0:t.mode)==="boolean"?new Gi(e,t.mode):new Vi(e)}var Yn,Xn;class Xi extends(Xn=ce,Yn=v,Xn){constructor(i){super(i,"string","SQLiteNumeric")}build(i){return new Zi(i,this.config)}}p(Xi,Yn,"SQLiteNumericBuilder");var Zn,ei;class Zi extends(ei=ge,Zn=v,ei){mapFromDriverValue(i){return typeof i=="string"?i:String(i)}getSQLType(){return"numeric"}}p(Zi,Zn,"SQLiteNumeric");var ti,ni;class er extends(ni=ce,ti=v,ni){constructor(i){super(i,"number","SQLiteNumericNumber")}build(i){return new tr(i,this.config)}}p(er,ti,"SQLiteNumericNumberBuilder");var ii,ri;class tr extends(ri=ge,ii=v,ri){constructor(){super(...arguments);p(this,"mapToDriverValue",String)}mapFromDriverValue(e){return typeof e=="number"?e:Number(e)}getSQLType(){return"numeric"}}p(tr,ii,"SQLiteNumericNumber");var si,oi;class nr extends(oi=ce,si=v,oi){constructor(i){super(i,"bigint","SQLiteNumericBigInt")}build(i){return new ir(i,this.config)}}p(nr,si,"SQLiteNumericBigIntBuilder");var ai,li;class ir extends(li=ge,ai=v,li){constructor(){super(...arguments);p(this,"mapFromDriverValue",BigInt);p(this,"mapToDriverValue",String)}getSQLType(){return"numeric"}}p(ir,ai,"SQLiteNumericBigInt");function Lr(n,i){const{name:e,config:t}=Je(n,i),r=t==null?void 0:t.mode;return r==="number"?new er(e):r==="bigint"?new nr(e):new Xi(e)}var _i,ui;class rr extends(ui=ce,_i=v,ui){constructor(i){super(i,"number","SQLiteReal")}build(i){return new sr(i,this.config)}}p(rr,_i,"SQLiteRealBuilder");var di,ci;class sr extends(ci=ge,di=v,ci){getSQLType(){return"real"}}p(sr,di,"SQLiteReal");function Er(n){return new rr(n??"")}var gi,fi;class or extends(fi=ce,gi=v,fi){constructor(i,e){super(i,"string","SQLiteText"),this.config.enumValues=e.enum,this.config.length=e.length}build(i){return new ar(i,this.config)}}p(or,gi,"SQLiteTextBuilder");var pi,hi;class ar extends(hi=ge,pi=v,hi){constructor(e,t){super(e,t);p(this,"enumValues",this.config.enumValues);p(this,"length",this.config.length)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}p(ar,pi,"SQLiteText");var mi,yi;class lr extends(yi=ce,mi=v,yi){constructor(i){super(i,"json","SQLiteTextJson")}build(i){return new _r(i,this.config)}}p(lr,mi,"SQLiteTextJsonBuilder");var wi,Ni;class _r extends(Ni=ge,wi=v,Ni){getSQLType(){return"text"}mapFromDriverValue(i){return JSON.parse(i)}mapToDriverValue(i){return JSON.stringify(i)}}p(_r,wi,"SQLiteTextJson");function s(n,i={}){const{name:e,config:t}=Je(n,i);return t.mode==="json"?new lr(e):new or(e,t)}function Cr(){return{blob:Tr,customType:qr,integer:m,numeric:Lr,real:Er,text:s}}const ht=Symbol.for("drizzle:SQLiteInlineForeignKeys");var vi,Si,xi,bi,Di;class $e extends(Di=M,bi=v,xi=M.Symbol.Columns,Si=ht,vi=M.Symbol.ExtraConfigBuilder,Di){constructor(){super(...arguments);p(this,xi);p(this,Si,[]);p(this,vi)}}p($e,bi,"SQLiteTable"),p($e,"Symbol",Object.assign({},M.Symbol,{InlineForeignKeys:ht}));function Ar(n,i,e,t,r=n){const o=new $e(n,t,r),l=typeof i=="function"?i(Cr()):i,_=Object.fromEntries(Object.entries(l).map(([c,d])=>{const h=d;h.setName(c);const f=h.build(o);return o[ht].push(...h.buildForeignKeys(f,o)),[c,f]})),u=Object.assign(o,_);return u[M.Symbol.Columns]=_,u[M.Symbol.ExtraConfigColumns]=_,e&&(u[$e.Symbol.ExtraConfigBuilder]=e),u}const O=(n,i,e)=>Ar(n,i,e);var Oi;Oi=v;class Ot{constructor(i,e){this.name=i,this.unique=e}on(...i){return new ur(this.name,i,this.unique)}}p(Ot,Oi,"SQLiteIndexBuilderOn");var ki;ki=v;class ur{constructor(i,e,t){p(this,"config");this.config={name:i,columns:e,unique:t,where:void 0}}where(i){return this.config.where=i,this}build(i){return new dr(this.config,i)}}p(ur,ki,"SQLiteIndexBuilder");var Ii;Ii=v;class dr{constructor(i,e){p(this,"config");this.config={...i,table:e}}}p(dr,Ii,"SQLiteIndex");function S(n){return new Ot(n,!1)}function Te(n){return new Ot(n,!0)}function oe(...n){return n[0].columns?new mt(n[0].columns,n[0].name):new mt(n)}var zi;zi=v;class mt{constructor(i,e){p(this,"columns");p(this,"name");this.columns=i,this.name=e}build(i){return new cr(i,this.columns,this.name)}}p(mt,zi,"SQLitePrimaryKeyBuilder");var Ti;Ti=v;class cr{constructor(i,e,t){p(this,"columns");p(this,"name");this.table=i,this.columns=e,this.name=t}getName(){return this.name??`${this.table[$e.Symbol.Name]}_${this.columns.map(i=>i.name).join("_")}_pk`}}p(cr,Ti,"SQLitePrimaryKey");const D=O("tenants",{id:s("id",{length:191}).primaryKey(),name:s("name",{length:255}),audience:s("audience",{length:255}),sender_email:s("sender_email",{length:255}),sender_name:s("sender_name",{length:255}),language:s("language",{length:255}),logo:s("logo",{length:255}),primary_color:s("primary_color",{length:255}),secondary_color:s("secondary_color",{length:255}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),support_url:s("support_url",{length:255}),idle_session_lifetime:m("idle_session_lifetime"),session_lifetime:m("session_lifetime"),session_cookie:s("session_cookie"),allowed_logout_urls:s("allowed_logout_urls"),ephemeral_session_lifetime:m("ephemeral_session_lifetime"),idle_ephemeral_session_lifetime:m("idle_ephemeral_session_lifetime"),default_redirection_uri:s("default_redirection_uri"),enabled_locales:s("enabled_locales"),default_directory:s("default_directory",{length:255}),error_page:s("error_page"),flags:s("flags"),friendly_name:s("friendly_name",{length:255}),picture_url:s("picture_url"),support_email:s("support_email",{length:255}),sandbox_version:s("sandbox_version",{length:50}),sandbox_versions_available:s("sandbox_versions_available"),legacy_sandbox_version:s("legacy_sandbox_version",{length:50}),change_password:s("change_password"),guardian_mfa_page:s("guardian_mfa_page"),device_flow:s("device_flow"),default_token_quota:s("default_token_quota"),default_audience:s("default_audience",{length:255}),default_organization:s("default_organization",{length:255}),sessions:s("sessions"),oidc_logout:s("oidc_logout"),allow_organization_name_in_authentication_api:m("allow_organization_name_in_authentication_api"),customize_mfa_in_postlogin_action:m("customize_mfa_in_postlogin_action"),acr_values_supported:s("acr_values_supported"),mtls:s("mtls"),pushed_authorization_requests_supported:m("pushed_authorization_requests_supported"),authorization_response_iss_parameter_supported:m("authorization_response_iss_parameter_supported")}),k=O("users",{user_id:s("user_id",{length:255}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),email:s("email",{length:255}),given_name:s("given_name",{length:255}),family_name:s("family_name",{length:255}),nickname:s("nickname",{length:255}),name:s("name",{length:255}),picture:s("picture",{length:2083}),tags:s("tags",{length:255}),phone_number:s("phone_number",{length:17}),phone_verified:m("phone_verified",{mode:"boolean"}),username:s("username",{length:128}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),linked_to:s("linked_to",{length:255}),last_ip:s("last_ip",{length:255}),login_count:m("login_count").notNull(),last_login:s("last_login",{length:255}),registration_completed_at:s("registration_completed_at",{length:35}),provider:s("provider",{length:255}).notNull(),connection:s("connection",{length:255}),email_verified:m("email_verified",{mode:"boolean"}).notNull(),is_social:m("is_social",{mode:"boolean"}).notNull(),app_metadata:s("app_metadata",{length:4096}).notNull().default("{}"),user_metadata:s("user_metadata").notNull().default("{}"),profileData:s("profileData",{length:2048}),locale:s("locale",{length:255}),middle_name:s("middle_name",{length:100}),preferred_username:s("preferred_username",{length:255}),profile:s("profile"),website:s("website"),gender:s("gender",{length:50}),birthdate:s("birthdate",{length:10}),zoneinfo:s("zoneinfo",{length:100}),address:s("address")},n=>[oe({columns:[n.user_id,n.tenant_id],name:"users_tenants"}),Te("unique_email_provider").on(n.email,n.provider,n.tenant_id),Te("unique_phone_provider").on(n.phone_number,n.provider,n.tenant_id),Te("unique_username_provider").on(n.username,n.provider,n.tenant_id),S("users_email_index").on(n.email),S("users_linked_to_index").on(n.linked_to),S("users_name_index").on(n.name),S("users_phone_tenant_provider_index").on(n.tenant_id,n.phone_number,n.provider)]),A=O("passwords",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),user_id:s("user_id",{length:255}).notNull(),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),password:s("password",{length:255}).notNull(),algorithm:s("algorithm",{length:16}).notNull().default("bcrypt"),is_current:m("is_current").notNull().default(1)}),$=O("sessions",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),user_id:s("user_id",{length:255}),created_at_ts:m("created_at_ts").notNull(),updated_at_ts:m("updated_at_ts").notNull(),expires_at_ts:m("expires_at_ts"),idle_expires_at_ts:m("idle_expires_at_ts"),authenticated_at_ts:m("authenticated_at_ts"),last_interaction_at_ts:m("last_interaction_at_ts"),used_at_ts:m("used_at_ts"),revoked_at_ts:m("revoked_at_ts"),device:s("device").notNull(),clients:s("clients").notNull(),login_session_id:s("login_session_id",{length:21})},n=>[oe({columns:[n.tenant_id,n.id],name:"sessions_pk"}),S("IDX_sessions_login_session_id").on(n.login_session_id),S("idx_sessions_user_id").on(n.tenant_id,n.user_id),S("idx_sessions_expires_at_ts").on(n.expires_at_ts)]),z=O("refresh_tokens",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),client_id:s("client_id",{length:191}).notNull(),login_id:s("login_id",{length:21}).notNull(),user_id:s("user_id",{length:255}),resource_servers:s("resource_servers").notNull(),device:s("device").notNull(),rotating:m("rotating",{mode:"boolean"}).notNull(),created_at_ts:m("created_at_ts").notNull(),expires_at_ts:m("expires_at_ts"),idle_expires_at_ts:m("idle_expires_at_ts"),last_exchanged_at_ts:m("last_exchanged_at_ts"),revoked_at_ts:m("revoked_at_ts")},n=>[oe({columns:[n.tenant_id,n.id],name:"refresh_tokens_pk"}),S("idx_refresh_tokens_user_id").on(n.tenant_id,n.user_id),S("idx_refresh_tokens_login_id").on(n.login_id),S("idx_refresh_tokens_expires_at_ts").on(n.expires_at_ts)]),L=O("login_sessions",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),session_id:s("session_id",{length:21}),csrf_token:s("csrf_token",{length:21}).notNull(),auth_params:s("auth_params"),authorization_url:s("authorization_url"),created_at_ts:m("created_at_ts").notNull(),updated_at_ts:m("updated_at_ts").notNull(),expires_at_ts:m("expires_at_ts").notNull(),ip:s("ip",{length:39}),useragent:s("useragent"),auth0Client:s("auth0Client",{length:255}),state:s("state",{length:50}).notNull().default("pending"),state_data:s("state_data"),failure_reason:s("failure_reason"),user_id:s("user_id",{length:255}),auth_connection:s("auth_connection",{length:255}),auth_strategy_strategy:s("auth_strategy_strategy",{length:64}),auth_strategy_strategy_type:s("auth_strategy_strategy_type",{length:64}),authenticated_at:s("authenticated_at",{length:35})},n=>[oe({columns:[n.tenant_id,n.id],name:"login_sessions_pk"}),S("login_sessions_id_index").on(n.id),S("login_sessions_state_idx").on(n.state),S("login_sessions_state_updated_idx").on(n.state,n.updated_at_ts),S("login_sessions_tenant_user_idx").on(n.tenant_id,n.user_id),S("idx_login_sessions_expires_at_ts").on(n.expires_at_ts)]),J=O("codes",{code_id:s("code_id",{length:191}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),user_id:s("user_id",{length:255}),login_id:s("login_id",{length:255}),connection_id:s("connection_id",{length:255}),code_type:s("code_type",{length:255}).notNull(),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),used_at:s("used_at",{length:35}),code_verifier:s("code_verifier",{length:128}),code_challenge:s("code_challenge",{length:128}),code_challenge_method:s("code_challenge_method",{length:5}),redirect_uri:s("redirect_uri",{length:1024}),nonce:s("nonce",{length:1024}),state:s("state",{length:2048})},n=>[oe({columns:[n.code_id,n.code_type],name:"PK_codes_code_id_code_type"}),S("codes_expires_at_index").on(n.expires_at)]),Br=O("authentication_codes",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),code:s("code",{length:255}).primaryKey(),client_id:s("client_id",{length:255}).notNull(),user_id:s("user_id",{length:255}).notNull(),nonce:s("nonce",{length:255}),state:s("state",{length:8192}),scope:s("scope",{length:1024}),response_type:s("response_type",{length:256}),response_mode:s("response_mode",{length:256}),redirect_uri:s("redirect_uri",{length:1024}),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),used_at:s("used_at",{length:35})}),$r=O("otps",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),id:s("id",{length:255}).primaryKey(),client_id:s("client_id",{length:255}).notNull(),code:s("code",{length:255}).notNull(),email:s("email",{length:255}).notNull(),user_id:s("user_id",{length:255}),send:s("send",{length:255}),nonce:s("nonce",{length:255}),state:s("state",{length:1024}),scope:s("scope",{length:1024}),response_type:s("response_type",{length:256}),response_mode:s("response_mode",{length:256}),redirect_uri:s("redirect_uri",{length:1024}),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),used_at:s("used_at",{length:35}),audience:s("audience",{length:255}),ip:s("ip",{length:64})},n=>[S("otps_email_index").on(n.email),S("otps_expires_at_index").on(n.expires_at)]),Qr=O("tickets",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),id:s("id",{length:255}).primaryKey(),client_id:s("client_id",{length:255}).notNull(),email:s("email",{length:255}).notNull(),nonce:s("nonce",{length:255}),state:s("state",{length:1024}),scope:s("scope",{length:1024}),response_type:s("response_type",{length:256}),response_mode:s("response_mode",{length:256}),redirect_uri:s("redirect_uri",{length:1024}),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),used_at:s("used_at",{length:35})}),I=O("clients",{client_id:s("client_id",{length:191}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),name:s("name",{length:255}).notNull(),description:s("description",{length:140}),global:m("global").notNull().default(0),client_secret:s("client_secret",{length:255}),app_type:s("app_type",{length:64}).default("regular_web"),logo_uri:s("logo_uri",{length:2083}),is_first_party:m("is_first_party").notNull().default(0),oidc_conformant:m("oidc_conformant").notNull().default(1),auth0_conformant:m("auth0_conformant").notNull().default(1),callbacks:s("callbacks").notNull(),allowed_origins:s("allowed_origins").notNull(),web_origins:s("web_origins").notNull(),client_aliases:s("client_aliases").notNull(),allowed_clients:s("allowed_clients").notNull(),allowed_logout_urls:s("allowed_logout_urls").notNull(),session_transfer:s("session_transfer").notNull(),oidc_logout:s("oidc_logout").notNull(),grant_types:s("grant_types").notNull(),jwt_configuration:s("jwt_configuration").notNull(),signing_keys:s("signing_keys").notNull(),encryption_key:s("encryption_key").notNull(),sso:m("sso").notNull().default(0),sso_disabled:m("sso_disabled").notNull().default(1),cross_origin_authentication:m("cross_origin_authentication").notNull().default(0),cross_origin_loc:s("cross_origin_loc",{length:2083}),custom_login_page_on:m("custom_login_page_on").notNull().default(0),custom_login_page:s("custom_login_page"),custom_login_page_preview:s("custom_login_page_preview"),form_template:s("form_template"),addons:s("addons").notNull(),token_endpoint_auth_method:s("token_endpoint_auth_method",{length:64}).default("client_secret_basic"),client_metadata:s("client_metadata").notNull(),mobile:s("mobile").notNull(),initiate_login_uri:s("initiate_login_uri",{length:2083}),native_social_login:s("native_social_login").notNull(),refresh_token:s("refresh_token").notNull(),default_organization:s("default_organization").notNull(),organization_usage:s("organization_usage",{length:32}).default("deny"),organization_require_behavior:s("organization_require_behavior",{length:32}).default("no_prompt"),client_authentication_methods:s("client_authentication_methods").notNull(),require_pushed_authorization_requests:m("require_pushed_authorization_requests").notNull().default(0),require_proof_of_possession:m("require_proof_of_possession").notNull().default(0),signed_request_object:s("signed_request_object").notNull(),compliance_level:s("compliance_level",{length:64}),par_request_expiry:m("par_request_expiry"),token_quota:s("token_quota").notNull(),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),connections:s("connections").notNull().default("[]")},n=>[oe({columns:[n.tenant_id,n.client_id],name:"clients_tenant_id_client_id"})]),Y=O("client_grants",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),client_id:s("client_id",{length:191}).notNull(),audience:s("audience",{length:191}).notNull(),scope:s("scope").default("[]"),organization_usage:s("organization_usage",{length:32}),allow_any_organization:m("allow_any_organization").default(0),is_system:m("is_system").default(0),subject_type:s("subject_type",{length:32}),authorization_details_types:s("authorization_details_types").default("[]"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[oe({columns:[n.tenant_id,n.id],name:"pk_client_grants"}),S("idx_client_grants_audience").on(n.audience)]),j=O("connections",{id:s("id",{length:255}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),name:s("name",{length:255}).notNull(),response_type:s("response_type",{length:255}),response_mode:s("response_mode",{length:255}),strategy:s("strategy",{length:64}),options:s("options",{length:8192}).notNull().default("{}"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),display_name:s("display_name",{length:255}),is_domain_connection:m("is_domain_connection"),show_as_button:m("show_as_button"),is_system:m("is_system").notNull().default(0),metadata:s("metadata",{length:4096})},n=>[oe({columns:[n.tenant_id,n.id]}),S("connections_tenant_id_index").on(n.tenant_id),Te("connections_id_unique").on(n.id)]),se=O("custom_domains",{custom_domain_id:s("custom_domain_id",{length:256}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),domain:s("domain",{length:255}).notNull(),primary:m("primary",{mode:"boolean"}).notNull(),status:s("status",{length:50}).notNull(),type:s("type",{length:50}).notNull(),origin_domain_name:s("origin_domain_name",{length:255}),verification:s("verification",{length:2048}),custom_client_ip_header:s("custom_client_ip_header",{length:50}),tls_policy:s("tls_policy",{length:50}),domain_metadata:s("domain_metadata",{length:2048}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[Te("custom_domains_domain_unique").on(n.domain)]),Jr=O("domains",{id:s("id",{length:255}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),domain:s("domain",{length:255}).notNull(),email_service:s("email_service",{length:255}),email_api_key:s("email_api_key",{length:255}),dkim_private_key:s("dkim_private_key",{length:2048}),dkim_public_key:s("dkim_public_key",{length:2048}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()}),E=O("organizations",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull(),name:s("name",{length:256}).notNull(),display_name:s("display_name",{length:256}),branding:s("branding"),metadata:s("metadata"),enabled_connections:s("enabled_connections"),token_quota:s("token_quota"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[S("idx_organizations_tenant_id").on(n.tenant_id)]),P=O("user_organizations",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull(),user_id:s("user_id",{length:191}).notNull(),organization_id:s("organization_id",{length:21}).notNull(),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[Te("user_organizations_unique").on(n.tenant_id,n.user_id,n.organization_id),S("idx_user_organizations_tenant_id").on(n.tenant_id),S("idx_user_organizations_user_id").on(n.user_id),S("idx_user_organizations_organization_id").on(n.organization_id)]),ne=O("invites",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull(),organization_id:s("organization_id",{length:21}).notNull(),inviter:s("inviter").notNull(),invitee:s("invitee").notNull(),client_id:s("client_id",{length:191}).notNull(),connection_id:s("connection_id",{length:21}),invitation_url:s("invitation_url").notNull(),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),app_metadata:s("app_metadata"),user_metadata:s("user_metadata"),roles:s("roles"),ticket_id:s("ticket_id",{length:191}),ttl_sec:m("ttl_sec"),send_invitation_email:m("send_invitation_email")},n=>[S("idx_invites_tenant_id").on(n.tenant_id),S("idx_invites_organization_id").on(n.organization_id),S("idx_invites_expires_at").on(n.expires_at),S("idx_invites_tenant_created").on(n.tenant_id,n.created_at)]),U=O("roles",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull(),name:s("name",{length:50}).notNull(),description:s("description",{length:255}),is_system:m("is_system").notNull().default(0),metadata:s("metadata",{length:4096}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[oe({columns:[n.tenant_id,n.id],name:"roles_pk"})]),le=O("role_permissions",{tenant_id:s("tenant_id",{length:191}).notNull(),role_id:s("role_id",{length:21}).notNull(),resource_server_identifier:s("resource_server_identifier",{length:191}).notNull(),permission_name:s("permission_name",{length:191}).notNull(),created_at:s("created_at",{length:35}).notNull()},n=>[oe({columns:[n.tenant_id,n.role_id,n.resource_server_identifier,n.permission_name],name:"role_permissions_pk"}),S("role_permissions_role_fk").on(n.tenant_id,n.role_id),S("role_permissions_permission_fk").on(n.tenant_id,n.resource_server_identifier,n.permission_name)]),_e=O("user_permissions",{tenant_id:s("tenant_id",{length:191}).notNull(),user_id:s("user_id",{length:191}).notNull(),resource_server_identifier:s("resource_server_identifier",{length:191}).notNull(),permission_name:s("permission_name",{length:191}).notNull(),organization_id:s("organization_id",{length:21}).notNull().default(""),created_at:s("created_at",{length:35}).notNull()},n=>[oe({columns:[n.tenant_id,n.user_id,n.resource_server_identifier,n.permission_name,n.organization_id],name:"user_permissions_pk"}),S("user_permissions_user_fk").on(n.tenant_id,n.user_id),S("user_permissions_permission_fk").on(n.tenant_id,n.resource_server_identifier,n.permission_name),S("user_permissions_organization_fk").on(n.organization_id)]),ue=O("user_roles",{tenant_id:s("tenant_id",{length:191}).notNull(),user_id:s("user_id",{length:191}).notNull(),role_id:s("role_id",{length:21}).notNull(),organization_id:s("organization_id",{length:191}).notNull().default(""),created_at:s("created_at",{length:35}).notNull()},n=>[oe({columns:[n.tenant_id,n.user_id,n.role_id,n.organization_id],name:"user_roles_pk"}),S("user_roles_user_fk").on(n.tenant_id,n.user_id),S("user_roles_role_fk").on(n.tenant_id,n.role_id),S("user_roles_organization_fk").on(n.organization_id)]),C=O("resource_servers",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull(),identifier:s("identifier",{length:191}).notNull(),name:s("name",{length:255}).notNull(),scopes:s("scopes",{length:4096}),signing_alg:s("signing_alg",{length:64}),signing_secret:s("signing_secret",{length:2048}),token_lifetime:m("token_lifetime"),token_lifetime_for_web:m("token_lifetime_for_web"),skip_consent_for_verifiable_first_party_clients:m("skip_consent_for_verifiable_first_party_clients"),allow_offline_access:m("allow_offline_access"),verification_key:s("verification_key",{length:4096}),options:s("options",{length:4096}),is_system:m("is_system").notNull().default(0),metadata:s("metadata",{length:4096}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[oe({columns:[n.tenant_id,n.id],name:"resource_servers_pk"})]),Le=O("branding",{tenant_id:s("tenant_id",{length:191}).primaryKey().references(()=>D.id,{onDelete:"cascade"}),logo_url:s("logo_url",{length:512}),favicon_url:s("favicon_url",{length:512}),font_url:s("font_url",{length:512}),colors_primary:s("colors_primary",{length:8}),colors_page_background_type:s("colors_page_background_type",{length:32}),colors_page_background_start:s("colors_page_background_start",{length:8}),colors_page_background_end:s("colors_page_background_end",{length:8}),colors_page_background_angle_dev:m("colors_page_background_angle_dev")}),ve=O("universal_login_templates",{tenant_id:s("tenant_id",{length:191}).primaryKey().references(()=>D.id,{onDelete:"cascade"}),body:s("body").notNull(),created_at_ts:m("created_at_ts").notNull(),updated_at_ts:m("updated_at_ts").notNull()}),fe=O("themes",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),themeId:s("themeId",{length:255}).notNull(),displayName:s("displayName",{length:255}).notNull(),colors_primary_button_label:s("colors_primary_button_label",{length:24}).notNull(),colors_primary_button:s("colors_primary_button",{length:24}).notNull(),colors_secondary_button_border:s("colors_secondary_button_border",{length:24}).notNull(),colors_secondary_button_label:s("colors_secondary_button_label",{length:24}).notNull(),colors_base_focus_color:s("colors_base_focus_color",{length:24}).notNull(),colors_base_hover_color:s("colors_base_hover_color",{length:24}).notNull(),colors_body_text:s("colors_body_text",{length:24}).notNull(),colors_captcha_widget_theme:s("colors_captcha_widget_theme",{length:24}).notNull(),colors_error:s("colors_error",{length:24}).notNull(),colors_header:s("colors_header",{length:24}).notNull(),colors_icons:s("colors_icons",{length:24}).notNull(),colors_input_background:s("colors_input_background",{length:24}).notNull(),colors_input_border:s("colors_input_border",{length:24}).notNull(),colors_input_filled_text:s("colors_input_filled_text",{length:24}).notNull(),colors_input_labels_placeholders:s("colors_input_labels_placeholders",{length:24}).notNull(),colors_links_focused_components:s("colors_links_focused_components",{length:24}).notNull(),colors_success:s("colors_success",{length:24}).notNull(),colors_widget_background:s("colors_widget_background",{length:24}).notNull(),colors_widget_border:s("colors_widget_border",{length:24}).notNull(),borders_button_border_radius:m("borders_button_border_radius").notNull(),borders_button_border_weight:m("borders_button_border_weight").notNull(),borders_buttons_style:s("borders_buttons_style",{length:24}).notNull(),borders_input_border_radius:m("borders_input_border_radius").notNull(),borders_input_border_weight:m("borders_input_border_weight").notNull(),borders_inputs_style:s("borders_inputs_style",{length:24}).notNull(),borders_show_widget_shadow:m("borders_show_widget_shadow",{mode:"boolean"}).notNull(),borders_widget_border_weight:m("borders_widget_border_weight").notNull(),borders_widget_corner_radius:m("borders_widget_corner_radius").notNull(),fonts_body_text_bold:m("fonts_body_text_bold").notNull(),fonts_body_text_size:m("fonts_body_text_size").notNull(),fonts_buttons_text_bold:m("fonts_buttons_text_bold").notNull(),fonts_buttons_text_size:m("fonts_buttons_text_size").notNull(),fonts_font_url:s("fonts_font_url",{length:255}).notNull(),fonts_input_labels_bold:m("fonts_input_labels_bold").notNull(),fonts_input_labels_size:m("fonts_input_labels_size").notNull(),fonts_links_bold:m("fonts_links_bold",{mode:"boolean"}).notNull(),fonts_links_size:m("fonts_links_size").notNull(),fonts_links_style:s("fonts_links_style",{length:24}).notNull(),fonts_reference_text_size:m("fonts_reference_text_size").notNull(),fonts_subtitle_bold:m("fonts_subtitle_bold",{mode:"boolean"}).notNull(),fonts_subtitle_size:m("fonts_subtitle_size").notNull(),fonts_title_bold:m("fonts_title_bold",{mode:"boolean"}).notNull(),fonts_title_size:m("fonts_title_size").notNull(),page_background_background_color:s("page_background_background_color",{length:24}).notNull(),page_background_background_image_url:s("page_background_background_image_url",{length:255}).notNull(),page_background_page_layout:s("page_background_page_layout",{length:24}).notNull(),widget_header_text_alignment:s("widget_header_text_alignment",{length:24}).notNull(),widget_logo_height:m("widget_logo_height").notNull(),widget_logo_position:s("widget_logo_position",{length:24}).notNull(),widget_logo_url:s("widget_logo_url",{length:255}).notNull(),widget_social_buttons_layout:s("widget_social_buttons_layout",{length:24}).notNull(),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[oe({columns:[n.tenant_id,n.themeId],name:"themes_pkey"}),S("themes_tenant_id_idx").on(n.tenant_id)]),ie=O("forms",{id:s("id",{length:255}).primaryKey(),name:s("name",{length:255}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),messages:s("messages",{length:255}),languages:s("languages",{length:255}),translations:s("translations",{length:4096}),nodes:s("nodes",{length:4096}),start:s("start",{length:255}),ending:s("ending",{length:255}),style:s("style",{length:1042}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[S("forms_tenant_id_idx").on(n.tenant_id)]),re=O("flows",{id:s("id",{length:24}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),name:s("name",{length:150}).notNull(),actions:s("actions"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[S("flows_tenant_id_idx").on(n.tenant_id)]),Ee=O("prompt_settings",{tenant_id:s("tenant_id",{length:191}).primaryKey(),universal_login_experience:s("universal_login_experience",{length:16}).notNull().default("new"),identifier_first:m("identifier_first",{mode:"boolean"}).notNull().default(!0),password_first:m("password_first",{mode:"boolean"}).notNull().default(!1),webauthn_platform_first_factor:m("webauthn_platform_first_factor",{mode:"boolean"}).notNull().default(!1)}),Se=O("email_providers",{tenant_id:s("tenant_id",{length:191}).primaryKey(),name:s("name",{length:255}).notNull(),enabled:m("enabled",{mode:"boolean"}).notNull(),default_from_address:s("default_from_address",{length:255}),credentials:s("credentials",{length:2048}).notNull().default("{}"),settings:s("settings",{length:2048}).notNull().default("{}"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()}),ee=O("hooks",{hook_id:s("hook_id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),url:s("url",{length:512}),trigger_id:s("trigger_id",{length:255}).notNull(),enabled:m("enabled",{mode:"boolean"}).notNull(),created_at_ts:m("created_at_ts").notNull(),updated_at_ts:m("updated_at_ts").notNull(),synchronous:m("synchronous",{mode:"boolean"}).notNull().default(!1),priority:m("priority"),form_id:s("form_id",{length:128}),template_id:s("template_id",{length:64}),code_id:s("code_id",{length:21})},n=>[S("hooks_tenant_id_idx").on(n.tenant_id)]),pe=O("hook_code",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),code:s("code").notNull(),secrets:s("secrets"),created_at_ts:m("created_at_ts").notNull(),updated_at_ts:m("updated_at_ts").notNull()},n=>[S("hook_code_tenant_id_idx").on(n.tenant_id)]),he=O("keys",{kid:s("kid",{length:255}).primaryKey(),tenant_id:s("tenant_id",{length:191}).references(()=>D.id,{onDelete:"cascade"}),created_at:s("created_at",{length:35}).notNull(),revoked_at:s("revoked_at",{length:35}),cert:s("cert",{length:4096}),pkcs7:s("pkcs7",{length:4096}),fingerprint:s("fingerprint",{length:256}),thumbprint:s("thumbprint",{length:256}),current_since:s("current_since",{length:35}),current_until:s("current_until",{length:35}),type:s("type",{length:50}).notNull().default("jwt_signing"),connection:s("connection",{length:255}).references(()=>j.id,{onDelete:"cascade"})}),te=O("custom_text",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),prompt:s("prompt",{length:64}).notNull(),language:s("language",{length:16}).notNull(),custom_text:s("custom_text").notNull(),created_at_ts:m("created_at_ts").notNull(),updated_at_ts:m("updated_at_ts").notNull()},n=>[oe({columns:[n.tenant_id,n.prompt,n.language]})]),K=O("authentication_methods",{id:s("id",{length:26}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),user_id:s("user_id",{length:255}).notNull(),type:s("type",{length:32}).notNull(),phone_number:s("phone_number",{length:32}),totp_secret:s("totp_secret",{length:255}),credential_id:s("credential_id",{length:512}),public_key:s("public_key"),sign_count:m("sign_count"),credential_backed_up:m("credential_backed_up"),transports:s("transports",{length:512}),friendly_name:s("friendly_name",{length:255}),confirmed:m("confirmed").notNull().default(0),created_at_ts:m("created_at_ts").notNull(),updated_at_ts:m("updated_at_ts").notNull()},n=>[S("authentication_methods_tenant_user_idx").on(n.tenant_id,n.user_id),S("authentication_methods_credential_id_idx").on(n.credential_id)]),q=O("logs",{log_id:s("log_id",{length:21}).primaryKey(),category:s("category",{length:255}),tenant_id:s("tenant_id",{length:64}),user_id:s("user_id",{length:64}),ip:s("ip",{length:255}),type:s("type",{length:8}).notNull(),date:s("date",{length:35}).notNull(),client_id:s("client_id",{length:255}),client_name:s("client_name",{length:255}),user_agent:s("user_agent",{length:255}),description:s("description",{length:255}),details:s("details",{length:2048}),isMobile:m("isMobile"),user_name:s("user_name",{length:255}),connection:s("connection",{length:255}),connection_id:s("connection_id",{length:255}),audience:s("audience",{length:255}),scope:s("scope",{length:255}),strategy:s("strategy",{length:255}),strategy_type:s("strategy_type",{length:255}),hostname:s("hostname",{length:255}),auth0_client:s("auth0_client",{length:8192}),session_connection:s("session_connection",{length:255}),country_code:s("country_code",{length:2}),city_name:s("city_name",{length:255}),latitude:s("latitude",{length:255}),longitude:s("longitude",{length:255}),time_zone:s("time_zone",{length:255}),continent_code:s("continent_code",{length:2})},n=>[S("logs_user_id").on(n.user_id),S("logs_tenant_id").on(n.tenant_id),S("logs_date").on(n.date),S("IDX_logs_tenant_date_type_user").on(n.tenant_id,n.date,n.type,n.user_id)]),b=O("outbox_events",{id:s("id",{length:26}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>D.id,{onDelete:"cascade"}),event_type:s("event_type",{length:64}).notNull(),log_type:s("log_type",{length:64}).notNull(),aggregate_type:s("aggregate_type",{length:64}).notNull(),aggregate_id:s("aggregate_id",{length:255}).notNull(),payload:s("payload").notNull(),created_at:s("created_at",{length:35}).notNull(),processed_at:s("processed_at",{length:35}),retry_count:m("retry_count").notNull().default(0),next_retry_at:s("next_retry_at",{length:35}),error:s("error"),claimed_by:s("claimed_by",{length:255}),claim_expires_at:s("claim_expires_at",{length:35}),dead_lettered_at:s("dead_lettered_at",{length:35}),final_error:s("final_error")},n=>[S("idx_outbox_events_tenant_id").on(n.tenant_id),S("idx_outbox_events_processed_at").on(n.processed_at),S("idx_outbox_events_claimed_by").on(n.claimed_by),S("idx_outbox_events_tenant_dead_lettered").on(n.tenant_id,n.dead_lettered_at)]),Pr=Object.freeze(Object.defineProperty({__proto__:null,authenticationCodes:Br,authenticationMethods:K,branding:Le,clientGrants:Y,clients:I,codes:J,connections:j,customDomains:se,customText:te,domains:Jr,emailProviders:Se,flows:re,forms:ie,hookCode:pe,hooks:ee,invites:ne,keys:he,loginSessions:L,logs:q,organizations:E,otps:$r,outboxEvents:b,passwords:A,promptSettings:Ee,refreshTokens:z,resourceServers:C,rolePermissions:le,roles:U,sessions:$,tenants:D,themes:fe,tickets:Qr,universalLoginTemplates:ve,userOrganizations:P,userPermissions:_e,userRoles:ue,users:k},Symbol.toStringTag,{value:"Module"}));function T(n){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(e=>e!==null&&typeof e=="object"?T(e):e);const i={...n};for(const e in i){const t=i[e];t===null?delete i[e]:t!==null&&typeof t=="object"&&(Array.isArray(t)?i[e]=t.map(r=>r!==null&&typeof r=="object"?T(r):r):i[e]=T(t))}return i}function Fr(n,i,e={...n}){for(const t of i)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]));return e}function Ur(n,i,e=n){for(const t of i)n[t]!==void 0&&(e[t]=n[t]?1:0)}function gr(n){const i={};for(const e in n)n[e]!==void 0&&n[e]!==null&&(i[e]=n[e]);return i}function x(n,i){if(n==null)return i;if(typeof n=="string")try{return JSON.parse(n)}catch{return i}return n}function yt(n,i="",e={}){for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)){const r=i?`${i}_${t}`:t,o=n[t];typeof o=="object"&&o!==null&&!Array.isArray(o)?yt(o,r,e):typeof o=="boolean"?e[r]=o?1:0:e[r]=o}return e}function fr(n,i){const e={};for(const[t,r]of Object.entries(n)){const o=i.find(l=>t.startsWith(`${l}_`));if(!o)e[t]=r;else{const l=t.slice(o.length+1);e[o]={...e[o],[l]:r}}}return e}function Kr(n){return typeof n=="string"?parseInt(n,10):typeof n=="bigint"?Number(n):n}function jr(n){return{async get(i){const e=await n.select().from(Le).where(a(Le.tenant_id,i)).get();if(!e)return null;const{tenant_id:t,colors_primary:r,colors_page_background_type:o,colors_page_background_start:l,colors_page_background_end:_,colors_page_background_angle_dev:u,font_url:c,...d}=e;return T({...d,colors:{primary:r,page_background:{type:o,start:l,end:_,angle_deg:u}},font:c?{url:c}:void 0})},async set(i,e){var _,u,c,d,h,f,y,N;const{colors:t,font:r,...o}=e,l={...o,tenant_id:i,colors_primary:t==null?void 0:t.primary,colors_page_background_type:(_=t==null?void 0:t.page_background)==null?void 0:_.type,colors_page_background_start:(u=t==null?void 0:t.page_background)==null?void 0:u.start,colors_page_background_end:(c=t==null?void 0:t.page_background)==null?void 0:c.end,colors_page_background_angle_dev:(d=t==null?void 0:t.page_background)==null?void 0:d.angle_deg,font_url:r==null?void 0:r.url};await n.insert(Le).values(l).onConflictDoUpdate({target:Le.tenant_id,set:{...o,colors_primary:t==null?void 0:t.primary,colors_page_background_type:(h=t==null?void 0:t.page_background)==null?void 0:h.type,colors_page_background_start:(f=t==null?void 0:t.page_background)==null?void 0:f.start,colors_page_background_end:(y=t==null?void 0:t.page_background)==null?void 0:y.end,colors_page_background_angle_dev:(N=t==null?void 0:t.page_background)==null?void 0:N.angle_deg,font_url:r==null?void 0:r.url}})}}}var be=class extends Error{constructor(i=500,e){super(e==null?void 0:e.message,{cause:e==null?void 0:e.cause});p(this,"res");p(this,"status");this.res=e==null?void 0:e.res,this.status=i}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};function ye(n,i,e){const t=i.split(/ OR /i);if(t.length>1){const c=t.map(d=>{const h=d.trim().match(/^([^:]+):(.+)$/);if(h){const[,f,y]=h;if(!f||!y)return null;const N=y.replace(/^"(.*)"$/,"$1"),B=n[f.trim()];return B?a(B,N.trim()):null}return null}).filter(Boolean);return c.length===0?void 0:de(...c)}const r=[];let o="",l=!1;for(let c=0;c<i.length;c++){const d=i[c];d==='"'?(l=!l,o+=d):d===" "&&!l?o.trim()&&(r.push(o.trim()),o=""):o+=d}o.trim()&&r.push(o.trim());const _=r.map(c=>c.replace(/^([^:]+)=/g,"$1:")).map(c=>{let d=c.startsWith("-"),h=null,f="",y=!1,N;if(c.startsWith("-_exists_:"))h=c.substring(10),y=!0,d=!0;else if(c.startsWith("_exists_:"))h=c.substring(9),y=!0,d=!1;else if(c.includes(":")){const B=d?c.substring(1):c,W=B.indexOf(":");h=B.substring(0,W),f=B.substring(W+1),y=!1,f.startsWith(">=")?(N=">=",f=f.substring(2)):f.startsWith(">")?(N=">",f=f.substring(1)):f.startsWith("<=")?(N="<=",f=f.substring(2)):f.startsWith("<")?(N="<",f=f.substring(1)):N="=",f.startsWith('"')&&f.endsWith('"')&&f.length>1&&(f=f.slice(1,-1))}else h=null,f=c,y=!1;return{key:h,value:f,isNegation:d,isExistsQuery:y,operator:N}}),u=[];for(const{key:c,value:d,isNegation:h,isExistsQuery:f,operator:y}of _)if(c){const N=n[c];if(!N){f?u.push(h?w`${w.identifier(c)} IS NULL`:w`${w.identifier(c)} IS NOT NULL`):u.push(w`${w.identifier(c)} ${w.raw(h?"!=":y??"=")} ${d}`);continue}if(f)u.push(h?me(N):Me(N));else if(h)switch(y){case">":u.push(Oe(N,d));break;case">=":u.push(we(N,d));break;case"<":u.push(He(N,d));break;case"<=":u.push(We(N,d));break;default:u.push(kr(N,d))}else switch(y){case">":u.push(We(N,d));break;case">=":u.push(He(N,d));break;case"<":u.push(we(N,d));break;case"<=":u.push(Oe(N,d));break;default:u.push(a(N,d))}}else if(d){const B=(d.includes("|")?[...e,"user_id"]:e).map(W=>{const H=n[W];return H?W==="user_id"?a(H,d):Ie(H,`%${d}%`):null}).filter(Boolean);B.length>0&&u.push(de(...B))}if(u.length!==0)return u.length===1?u[0]:g(...u)}const kt=["global","is_first_party","oidc_conformant","auth0_conformant","sso","sso_disabled","cross_origin_authentication","custom_login_page_on","require_pushed_authorization_requests","require_proof_of_possession"],It=["callbacks","allowed_origins","web_origins","client_aliases","allowed_clients","allowed_logout_urls","grant_types","signing_keys"],zt=["session_transfer","oidc_logout","jwt_configuration","encryption_key","addons","client_metadata","mobile","native_social_login","refresh_token","default_organization","client_authentication_methods","signed_request_object","token_quota"];function Fe(n){const{tenant_id:i,connections:e,...t}=n,r={...t};for(const o of kt)r[o]=!!t[o];for(const o of It)r[o]=x(t[o],[]);for(const o of zt)r[o]=x(t[o],{});return r.connections=x(e,[]),T(r)}function Ct(n){const i={...n};Ur(n,kt,i);for(const e of It)n[e]!==void 0&&(i[e]=JSON.stringify(n[e]||[]));for(const e of zt)n[e]!==void 0&&(i[e]=JSON.stringify(n[e]||{}));return n.connections!==void 0&&(i.connections=JSON.stringify(n.connections||[])),gr(i)}function Mr(n){return{async create(i,e){var l,_;const t=new Date().toISOString(),r={client_id:e.client_id,tenant_id:i,name:e.name,description:e.description,app_type:e.app_type??"regular_web",logo_uri:e.logo_uri,client_secret:e.client_secret,token_endpoint_auth_method:e.token_endpoint_auth_method??"client_secret_basic",cross_origin_loc:e.cross_origin_loc,custom_login_page:e.custom_login_page,custom_login_page_preview:e.custom_login_page_preview,form_template:e.form_template,initiate_login_uri:e.initiate_login_uri,organization_usage:e.organization_usage??"deny",organization_require_behavior:e.organization_require_behavior??"no_prompt",compliance_level:e.compliance_level,par_request_expiry:e.par_request_expiry,created_at:t,updated_at:t};for(const u of kt)r[u]=e[u]??!1;r.oidc_conformant=e.oidc_conformant??!0,r.auth0_conformant=e.auth0_conformant??!0,r.sso_disabled=e.sso_disabled??!1;for(const u of It)r[u]=e[u]||[];for(const u of zt)r[u]=e[u]||{};r.connections=e.connections||[];const o=Ct(r);try{await n.insert(I).values({...o,tenant_id:i})}catch(u){throw(l=u==null?void 0:u.message)!=null&&l.includes("UNIQUE constraint failed")||(_=u==null?void 0:u.message)!=null&&_.includes("duplicate key")?new be(409,{message:"Client already exists"}):u}return Fe({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(I).where(g(a(I.tenant_id,i),a(I.client_id,e))).get();return t?Fe(t):null},async getByClientId(i){const e=await n.select().from(I).where(a(I.client_id,i)).get();return e?{...Fe(e),tenant_id:e.tenant_id}:null},async update(i,e,t){const r=Ct({...t,updated_at:new Date().toISOString()});return delete r.client_id,delete r.tenant_id,await n.update(I).set(r).where(g(a(I.tenant_id,i),a(I.client_id,e))),!0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{};let u=n.select().from(I).where(a(I.tenant_id,i)).$dynamic();if(_){const f=ye(I,_,["name","client_id"]);f&&(u=u.where(g(a(I.tenant_id,i),f)))}if(l!=null&&l.sort_by){const f=I[l.sort_by];f&&(u=u.orderBy(l.sort_order==="desc"?V(f):G(f)))}const d=(await u.offset(t*r).limit(r)).map(Fe);if(!o)return{clients:d};const[h]=await n.select({count:R()}).from(I).where(a(I.tenant_id,i));return{clients:d,start:t*r,limit:r,length:Number((h==null?void 0:h.count)??0)}},async remove(i,e){return(await n.delete(I).where(g(a(I.tenant_id,i),a(I.client_id,e))).returning()).length>0}}}function Vr(n){const{tenant_id:i,is_system:e,options:t,metadata:r,...o}=n;return T({...o,options:x(t,{}),metadata:x(r),is_system:e?!0:void 0})}function Rr(n){return{async listByClient(i,e){const t=await n.select({connections:I.connections}).from(I).where(g(a(I.tenant_id,i),a(I.client_id,e))).get();if(!t)return[];const r=x(t.connections,[])||[];if(r.length===0)return[];const l=(await n.select().from(j).where(g(a(j.tenant_id,i),Ne(j.id,r))).all()).map(Vr);return r.map(_=>l.find(u=>u.id===_)).filter(Boolean)},async updateByClient(i,e,t){return(await n.update(I).set({connections:JSON.stringify([...new Set(t)])}).where(g(a(I.tenant_id,i),a(I.client_id,e))).returning()).length>0},async listByConnection(i,e){return(await n.select({client_id:I.client_id,connections:I.connections}).from(I).where(a(I.tenant_id,i)).all()).filter(r=>(x(r.connections,[])||[]).includes(e)).map(r=>r.client_id)},async addClientToConnection(i,e,t){var _;if(!await n.select({client_id:I.client_id}).from(I).where(g(a(I.tenant_id,i),a(I.client_id,t))).get())return!1;const o=await n.run(w`UPDATE clients SET connections = CASE
1
+ "use strict";var Lr=Object.defineProperty;var Rr=(n,e,t)=>e in n?Lr(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var y=(n,e,t)=>Rr(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const L=Symbol.for("drizzle:entityKind");function ye(n,e){if(!n||typeof n!="object")return!1;if(n instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,L))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=Object.getPrototypeOf(n).constructor;if(t)for(;t;){if(L in t&&t[L]===e[L])return!0;t=Object.getPrototypeOf(t)}return!1}var zi;zi=L;class Qt{constructor(e,t){y(this,"name");y(this,"keyAsName");y(this,"primary");y(this,"notNull");y(this,"default");y(this,"defaultFn");y(this,"onUpdateFn");y(this,"hasDefault");y(this,"isUnique");y(this,"uniqueName");y(this,"uniqueType");y(this,"dataType");y(this,"columnType");y(this,"enumValues");y(this,"generated");y(this,"generatedIdentity");y(this,"config");this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}y(Qt,zi,"Column");var Fi;Fi=L;class No{constructor(e,t,i){y(this,"config");y(this,"$default",this.$defaultFn);y(this,"$onUpdate",this.$onUpdateFn);this.config={name:e,keyAsName:e==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:i,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===""&&(this.config.name=e)}}y(No,Fi,"ColumnBuilder");const bt=Symbol.for("drizzle:Name"),Si=Symbol.for("drizzle:isPgEnum");function Ur(n){return!!n&&typeof n=="function"&&Si in n&&n[Si]===!0}var Pi;Pi=L;class ui{constructor(e,t,i,a=!1,r=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:i,isWith:a,usedTables:r}}}y(ui,Pi,"Subquery");const zr={startActiveSpan(n,e){return e()}},Ct=Symbol.for("drizzle:ViewBaseConfig"),Tn=Symbol.for("drizzle:Schema"),Ni=Symbol.for("drizzle:Columns"),bi=Symbol.for("drizzle:ExtraConfigColumns"),An=Symbol.for("drizzle:OriginalName"),In=Symbol.for("drizzle:BaseName"),an=Symbol.for("drizzle:IsAlias"),Ei=Symbol.for("drizzle:ExtraConfigBuilder"),Fr=Symbol.for("drizzle:IsDrizzleTable");var Mi,qi,Bi,$i,ji,Vi,Zi,Hi,Ki,Qi;Qi=L,Ki=bt,Hi=An,Zi=Tn,Vi=Ni,ji=bi,$i=In,Bi=an,qi=Fr,Mi=Ei;class fe{constructor(e,t,i){y(this,Ki);y(this,Hi);y(this,Zi);y(this,Vi);y(this,ji);y(this,$i);y(this,Bi,!1);y(this,qi,!0);y(this,Mi);this[bt]=this[An]=e,this[Tn]=t,this[In]=i}}y(fe,Qi,"Table"),y(fe,"Symbol",{Name:bt,Schema:Tn,OriginalName:An,Columns:Ni,ExtraConfigColumns:bi,BaseName:In,IsAlias:an,ExtraConfigBuilder:Ei});function bo(n){return n!=null&&typeof n.getSQL=="function"}function Pr(n){var t;const e={sql:"",params:[]};for(const i of n)e.sql+=i.sql,e.params.push(...i.params),(t=i.typings)!=null&&t.length&&(e.typings||(e.typings=[]),e.typings.push(...i.typings));return e}var Gi;Gi=L;class ve{constructor(e){y(this,"value");this.value=Array.isArray(e)?e:[e]}getSQL(){return new de([this])}}y(ve,Gi,"StringChunk");var Ji;Ji=L;const pt=class pt{constructor(e){y(this,"decoder",Eo);y(this,"shouldInlineParams",!1);y(this,"usedTables",[]);this.queryChunks=e;for(const t of e)if(ye(t,fe)){const i=t[fe.Symbol.Schema];this.usedTables.push(i===void 0?t[fe.Symbol.Name]:i+"."+t[fe.Symbol.Name])}}append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return zr.startActiveSpan("drizzle.buildSQL",t=>{const i=this.buildQueryFromSourceParams(this.queryChunks,e);return t==null||t.setAttributes({"drizzle.query.text":i.sql,"drizzle.query.params":JSON.stringify(i.params)}),i})}buildQueryFromSourceParams(e,t){const i=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:a,escapeName:r,escapeParam:l,prepareTyping:d,inlineParams:u,paramStartIndex:f}=i;return Pr(e.map(p=>{var v;if(ye(p,ve))return{sql:p.value.join(""),params:[]};if(ye(p,on))return{sql:r(p.value),params:[]};if(p===void 0)return{sql:"",params:[]};if(Array.isArray(p)){const m=[new ve("(")];for(const[N,T]of p.entries())m.push(T),N<p.length-1&&m.push(new ve(", "));return m.push(new ve(")")),this.buildQueryFromSourceParams(m,i)}if(ye(p,pt))return this.buildQueryFromSourceParams(p.queryChunks,{...i,inlineParams:u||p.shouldInlineParams});if(ye(p,fe)){const m=p[fe.Symbol.Schema],N=p[fe.Symbol.Name];return{sql:m===void 0||p[an]?r(N):r(m)+"."+r(N),params:[]}}if(ye(p,Qt)){const m=a.getColumnCasing(p);if(t.invokeSource==="indexes")return{sql:r(m),params:[]};const N=p.table[fe.Symbol.Schema];return{sql:p.table[an]||N===void 0?r(p.table[fe.Symbol.Name])+"."+r(m):r(N)+"."+r(p.table[fe.Symbol.Name])+"."+r(m),params:[]}}if(ye(p,pi)){const m=p[Ct].schema,N=p[Ct].name;return{sql:m===void 0||p[Ct].isAlias?r(N):r(m)+"."+r(N),params:[]}}if(ye(p,Dt)){if(ye(p.value,Lt))return{sql:l(f.value++,p),params:[p],typings:["none"]};const m=p.value===null?null:p.encoder.mapToDriverValue(p.value);if(ye(m,pt))return this.buildQueryFromSourceParams([m],i);if(u)return{sql:this.mapInlineParam(m,i),params:[]};let N=["none"];return d&&(N=[d(p.encoder)]),{sql:l(f.value++,m),params:[m],typings:N}}return ye(p,Lt)?{sql:l(f.value++,p),params:[p],typings:["none"]}:ye(p,pt.Aliased)&&p.fieldAlias!==void 0?{sql:r(p.fieldAlias),params:[]}:ye(p,ui)?p._.isWith?{sql:r(p._.alias),params:[]}:this.buildQueryFromSourceParams([new ve("("),p._.sql,new ve(") "),new on(p._.alias)],i):Ur(p)?p.schema?{sql:r(p.schema)+"."+r(p.enumName),params:[]}:{sql:r(p.enumName),params:[]}:bo(p)?(v=p.shouldOmitSQLParens)!=null&&v.call(p)?this.buildQueryFromSourceParams([p.getSQL()],i):this.buildQueryFromSourceParams([new ve("("),p.getSQL(),new ve(")")],i):u?{sql:this.mapInlineParam(p,i),params:[]}:{sql:l(f.value++,p),params:[p],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const i=e.toString();return t(i==="[object Object]"?JSON.stringify(e):i)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new pt.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}};y(pt,Ji,"SQL");let de=pt;var Wi;Wi=L;class on{constructor(e){y(this,"brand");this.value=e}getSQL(){return new de([this])}}y(on,Wi,"Name");function Mr(n){return typeof n=="object"&&n!==null&&"mapToDriverValue"in n&&typeof n.mapToDriverValue=="function"}const Eo={mapFromDriverValue:n=>n},xo={mapToDriverValue:n=>n};({...Eo,...xo});var Xi;Xi=L;class Dt{constructor(e,t=xo){y(this,"brand");this.value=e,this.encoder=t}getSQL(){return new de([this])}}y(Dt,Xi,"Param");function A(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new ve(n[0]));for(const[i,a]of e.entries())t.push(a,new ve(n[i+1]));return new de(t)}(n=>{function e(){return new de([])}n.empty=e;function t(u){return new de(u)}n.fromList=t;function i(u){return new de([new ve(u)])}n.raw=i;function a(u,f){const p=[];for(const[v,m]of u.entries())v>0&&f!==void 0&&p.push(f),p.push(m);return new de(p)}n.join=a;function r(u){return new on(u)}n.identifier=r;function l(u){return new Lt(u)}n.placeholder=l;function d(u,f){return new Dt(u,f)}n.param=d})(A||(A={}));(n=>{var t;t=L;const i=class i{constructor(r,l){y(this,"isSelectionField",!1);this.sql=r,this.fieldAlias=l}getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}};y(i,t,"SQL.Aliased");let e=i;n.Aliased=e})(de||(de={}));var Yi;Yi=L;class Lt{constructor(e){this.name=e}getSQL(){return new de([this])}}y(Lt,Yi,"Placeholder");const qr=Symbol.for("drizzle:IsDrizzleView");var ea,ta,na;na=L,ta=Ct,ea=qr;class pi{constructor({name:e,schema:t,selectedFields:i,query:a}){y(this,ta);y(this,ea,!0);this[Ct]={name:e,originalName:e,schema:t,selectedFields:i,query:a,isExisting:!a,isAlias:!1}}getSQL(){return new de([this])}}y(pi,na,"View");Qt.prototype.getSQL=function(){return new de([this])};fe.prototype.getSQL=function(){return new de([this])};ui.prototype.getSQL=function(){return new de([this])};function Gt(n,e){return{name:typeof n=="string"&&n.length>0?n:"",config:typeof n=="object"?n:e}}const ko=typeof TextDecoder>"u"?null:new TextDecoder;function ot(n,e){return Mr(e)&&!bo(n)&&!ye(n,Dt)&&!ye(n,Lt)&&!ye(n,Qt)&&!ye(n,fe)&&!ye(n,pi)?new Dt(n,e):n}const c=(n,e)=>A`${n} = ${ot(e,n)}`,Br=(n,e)=>A`${n} <> ${ot(e,n)}`;function g(...n){const e=n.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new de(e):new de([new ve("("),A.join(e,new ve(" and ")),new ve(")")])}function Ue(...n){const e=n.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new de(e):new de([new ve("("),A.join(e,new ve(" or ")),new ve(")")])}const rn=(n,e)=>A`${n} > ${ot(e,n)}`,sn=(n,e)=>A`${n} >= ${ot(e,n)}`,Xe=(n,e)=>A`${n} < ${ot(e,n)}`,ft=(n,e)=>A`${n} <= ${ot(e,n)}`;function Ye(n,e){return Array.isArray(e)?e.length===0?A`false`:A`${n} in ${e.map(t=>ot(t,n))}`:A`${n} in ${ot(e,n)}`}function Ae(n){return A`${n} is null`}function nn(n){return A`${n} is not null`}function St(n,e){return A`${n} like ${e}`}function ge(n){return A`${n} asc`}function ce(n){return A`${n} desc`}function he(n){return A`count(${A.raw("*")})`.mapWith(Number)}function $r(){const n=e=>{throw new Error(`Actions are not implemented in the Drizzle adapter (called ${e}). Use the Kysely adapter for tenants that require actions.`)};return{create:()=>n("create"),get:()=>n("get"),list:()=>n("list"),update:()=>n("update"),remove:()=>n("remove")}}var ia;ia=L;class Oo{constructor(e,t){y(this,"reference");y(this,"_onUpdate");y(this,"_onDelete");this.reference=()=>{const{name:i,columns:a,foreignColumns:r}=e();return{name:i,columns:a,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e,this}onDelete(e){return this._onDelete=e,this}build(e){return new To(e,this)}}y(Oo,ia,"SQLiteForeignKeyBuilder");var aa;aa=L;class To{constructor(e,t){y(this,"reference");y(this,"onUpdate");y(this,"onDelete");this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}getName(){const{name:e,columns:t,foreignColumns:i}=this.reference(),a=t.map(d=>d.name),r=i.map(d=>d.name),l=[this.table[bt],...a,i[0].table[bt],...r];return e??`${l.join("_")}_fk`}}y(To,aa,"SQLiteForeignKey");function jr(n,e){return`${n[bt]}_${e.join("_")}_unique`}var oa,ra;class ze extends(ra=No,oa=L,ra){constructor(){super(...arguments);y(this,"foreignKeyConfigs",[])}references(t,i={}){return this.foreignKeyConfigs.push({ref:t,actions:i}),this}unique(t){return this.config.isUnique=!0,this.config.uniqueName=t,this}generatedAlwaysAs(t,i){return this.config.generated={as:t,type:"always",mode:(i==null?void 0:i.mode)??"virtual"},this}buildForeignKeys(t,i){return this.foreignKeyConfigs.map(({ref:a,actions:r})=>((l,d)=>{const u=new Oo(()=>{const f=l();return{columns:[t],foreignColumns:[f]}});return d.onUpdate&&u.onUpdate(d.onUpdate),d.onDelete&&u.onDelete(d.onDelete),u.build(i)})(a,r))}}y(ze,oa,"SQLiteColumnBuilder");var sa,la;class Fe extends(la=Qt,sa=L,la){constructor(e,t){t.uniqueName||(t.uniqueName=jr(e,[t.name])),super(e,t),this.table=e}}y(Fe,sa,"SQLiteColumn");var da,ca;class Ao extends(ca=ze,da=L,ca){constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new Io(e,this.config)}}y(Ao,da,"SQLiteBigIntBuilder");var _a,ua;class Io extends(ua=Fe,_a=L,ua){getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){const t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return BigInt(t.toString("utf8"))}return BigInt(ko.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}}y(Io,_a,"SQLiteBigInt");var pa,fa;class Co extends(fa=ze,pa=L,fa){constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new Do(e,this.config)}}y(Co,pa,"SQLiteBlobJsonBuilder");var ha,ga;class Do extends(ga=Fe,ha=L,ga){getSQLType(){return"blob"}mapFromDriverValue(e){if(typeof Buffer<"u"&&Buffer.from){const t=Buffer.isBuffer(e)?e:e instanceof ArrayBuffer?Buffer.from(e):e.buffer?Buffer.from(e.buffer,e.byteOffset,e.byteLength):Buffer.from(e);return JSON.parse(t.toString("utf8"))}return JSON.parse(ko.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}}y(Do,ha,"SQLiteBlobJson");var ma,ya;class Lo extends(ya=ze,ma=L,ya){constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new Ro(e,this.config)}}y(Lo,ma,"SQLiteBlobBufferBuilder");var va,wa;class Ro extends(wa=Fe,va=L,wa){mapFromDriverValue(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}getSQLType(){return"blob"}}y(Ro,va,"SQLiteBlobBuffer");function Vr(n,e){const{name:t,config:i}=Gt(n,e);return(i==null?void 0:i.mode)==="json"?new Co(t):(i==null?void 0:i.mode)==="bigint"?new Ao(t):new Lo(t)}var Sa,Na;class Uo extends(Na=ze,Sa=L,Na){constructor(e,t,i){super(e,"custom","SQLiteCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=i}build(e){return new zo(e,this.config)}}y(Uo,Sa,"SQLiteCustomColumnBuilder");var ba,Ea;class zo extends(Ea=Fe,ba=L,Ea){constructor(t,i){super(t,i);y(this,"sqlName");y(this,"mapTo");y(this,"mapFrom");this.sqlName=i.customTypeParams.dataType(i.fieldConfig),this.mapTo=i.customTypeParams.toDriver,this.mapFrom=i.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue(t){return typeof this.mapFrom=="function"?this.mapFrom(t):t}mapToDriverValue(t){return typeof this.mapTo=="function"?this.mapTo(t):t}}y(zo,ba,"SQLiteCustomColumn");function Zr(n){return(e,t)=>{const{name:i,config:a}=Gt(e,t);return new Uo(i,a,n)}}var xa,ka;class fn extends(ka=ze,xa=L,ka){constructor(e,t,i){super(e,t,i),this.config.autoIncrement=!1}primaryKey(e){return e!=null&&e.autoIncrement&&(this.config.autoIncrement=!0),this.config.hasDefault=!0,super.primaryKey()}}y(fn,xa,"SQLiteBaseIntegerBuilder");var Oa,Ta;class hn extends(Ta=Fe,Oa=L,Ta){constructor(){super(...arguments);y(this,"autoIncrement",this.config.autoIncrement)}getSQLType(){return"integer"}}y(hn,Oa,"SQLiteBaseInteger");var Aa,Ia;class Fo extends(Ia=fn,Aa=L,Ia){constructor(e){super(e,"number","SQLiteInteger")}build(e){return new Po(e,this.config)}}y(Fo,Aa,"SQLiteIntegerBuilder");var Ca,Da;class Po extends(Da=hn,Ca=L,Da){}y(Po,Ca,"SQLiteInteger");var La,Ra;class Mo extends(Ra=fn,La=L,Ra){constructor(e,t){super(e,"date","SQLiteTimestamp"),this.config.mode=t}defaultNow(){return this.default(A`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new qo(e,this.config)}}y(Mo,La,"SQLiteTimestampBuilder");var Ua,za;class qo extends(za=hn,Ua=L,za){constructor(){super(...arguments);y(this,"mode",this.config.mode)}mapFromDriverValue(t){return this.config.mode==="timestamp"?new Date(t*1e3):new Date(t)}mapToDriverValue(t){const i=t.getTime();return this.config.mode==="timestamp"?Math.floor(i/1e3):i}}y(qo,Ua,"SQLiteTimestamp");var Fa,Pa;class Bo extends(Pa=fn,Fa=L,Pa){constructor(e,t){super(e,"boolean","SQLiteBoolean"),this.config.mode=t}build(e){return new $o(e,this.config)}}y(Bo,Fa,"SQLiteBooleanBuilder");var Ma,qa;class $o extends(qa=hn,Ma=L,qa){constructor(){super(...arguments);y(this,"mode",this.config.mode)}mapFromDriverValue(t){return Number(t)===1}mapToDriverValue(t){return t?1:0}}y($o,Ma,"SQLiteBoolean");function w(n,e){const{name:t,config:i}=Gt(n,e);return(i==null?void 0:i.mode)==="timestamp"||(i==null?void 0:i.mode)==="timestamp_ms"?new Mo(t,i.mode):(i==null?void 0:i.mode)==="boolean"?new Bo(t,i.mode):new Fo(t)}var Ba,$a;class jo extends($a=ze,Ba=L,$a){constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new Vo(e,this.config)}}y(jo,Ba,"SQLiteNumericBuilder");var ja,Va;class Vo extends(Va=Fe,ja=L,Va){mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return"numeric"}}y(Vo,ja,"SQLiteNumeric");var Za,Ha;class Zo extends(Ha=ze,Za=L,Ha){constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new Ho(e,this.config)}}y(Zo,Za,"SQLiteNumericNumberBuilder");var Ka,Qa;class Ho extends(Qa=Fe,Ka=L,Qa){constructor(){super(...arguments);y(this,"mapToDriverValue",String)}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}getSQLType(){return"numeric"}}y(Ho,Ka,"SQLiteNumericNumber");var Ga,Ja;class Ko extends(Ja=ze,Ga=L,Ja){constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new Qo(e,this.config)}}y(Ko,Ga,"SQLiteNumericBigIntBuilder");var Wa,Xa;class Qo extends(Xa=Fe,Wa=L,Xa){constructor(){super(...arguments);y(this,"mapFromDriverValue",BigInt);y(this,"mapToDriverValue",String)}getSQLType(){return"numeric"}}y(Qo,Wa,"SQLiteNumericBigInt");function Hr(n,e){const{name:t,config:i}=Gt(n,e),a=i==null?void 0:i.mode;return a==="number"?new Zo(t):a==="bigint"?new Ko(t):new jo(t)}var Ya,eo;class Go extends(eo=ze,Ya=L,eo){constructor(e){super(e,"number","SQLiteReal")}build(e){return new Jo(e,this.config)}}y(Go,Ya,"SQLiteRealBuilder");var to,no;class Jo extends(no=Fe,to=L,no){getSQLType(){return"real"}}y(Jo,to,"SQLiteReal");function Kr(n){return new Go(n??"")}var io,ao;class Wo extends(ao=ze,io=L,ao){constructor(e,t){super(e,"string","SQLiteText"),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new Xo(e,this.config)}}y(Wo,io,"SQLiteTextBuilder");var oo,ro;class Xo extends(ro=Fe,oo=L,ro){constructor(t,i){super(t,i);y(this,"enumValues",this.config.enumValues);y(this,"length",this.config.length)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}y(Xo,oo,"SQLiteText");var so,lo;class Yo extends(lo=ze,so=L,lo){constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new er(e,this.config)}}y(Yo,so,"SQLiteTextJsonBuilder");var co,_o;class er extends(_o=Fe,co=L,_o){getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}y(er,co,"SQLiteTextJson");function s(n,e={}){const{name:t,config:i}=Gt(n,e);return i.mode==="json"?new Yo(t):new Wo(t,i)}function Qr(){return{blob:Vr,customType:Zr,integer:w,numeric:Hr,real:Kr,text:s}}const Gn=Symbol.for("drizzle:SQLiteInlineForeignKeys");var uo,po,fo,ho,go;class Rt extends(go=fe,ho=L,fo=fe.Symbol.Columns,po=Gn,uo=fe.Symbol.ExtraConfigBuilder,go){constructor(){super(...arguments);y(this,fo);y(this,po,[]);y(this,uo)}}y(Rt,ho,"SQLiteTable"),y(Rt,"Symbol",Object.assign({},fe.Symbol,{InlineForeignKeys:Gn}));function Gr(n,e,t,i,a=n){const r=new Rt(n,i,a),l=typeof e=="function"?e(Qr()):e,d=Object.fromEntries(Object.entries(l).map(([f,p])=>{const v=p;v.setName(f);const m=v.build(r);return r[Gn].push(...v.buildForeignKeys(m,r)),[f,m]})),u=Object.assign(r,d);return u[fe.Symbol.Columns]=d,u[fe.Symbol.ExtraConfigColumns]=d,t&&(u[Rt.Symbol.ExtraConfigBuilder]=t),u}const $=(n,e,t)=>Gr(n,e,t);var mo;mo=L;class fi{constructor(e,t){this.name=e,this.unique=t}on(...e){return new tr(this.name,e,this.unique)}}y(fi,mo,"SQLiteIndexBuilderOn");var yo;yo=L;class tr{constructor(e,t,i){y(this,"config");this.config={name:e,columns:t,unique:i,where:void 0}}where(e){return this.config.where=e,this}build(e){return new nr(this.config,e)}}y(tr,yo,"SQLiteIndexBuilder");var vo;vo=L;class nr{constructor(e,t){y(this,"config");this.config={...e,table:t}}}y(nr,vo,"SQLiteIndex");function D(n){return new fi(n,!1)}function ht(n){return new fi(n,!0)}function Te(...n){return n[0].columns?new Jn(n[0].columns,n[0].name):new Jn(n)}var wo;wo=L;class Jn{constructor(e,t){y(this,"columns");y(this,"name");this.columns=e,this.name=t}build(e){return new ir(e,this.columns,this.name)}}y(Jn,wo,"SQLitePrimaryKeyBuilder");var So;So=L;class ir{constructor(e,t,i){y(this,"columns");y(this,"name");this.table=e,this.columns=t,this.name=i}getName(){return this.name??`${this.table[Rt.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}y(ir,So,"SQLitePrimaryKey");const B=$("tenants",{id:s("id",{length:191}).primaryKey(),name:s("name",{length:255}),audience:s("audience",{length:255}),sender_email:s("sender_email",{length:255}),sender_name:s("sender_name",{length:255}),language:s("language",{length:255}),logo:s("logo",{length:255}),primary_color:s("primary_color",{length:255}),secondary_color:s("secondary_color",{length:255}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),support_url:s("support_url",{length:255}),idle_session_lifetime:w("idle_session_lifetime"),session_lifetime:w("session_lifetime"),session_cookie:s("session_cookie"),allowed_logout_urls:s("allowed_logout_urls"),ephemeral_session_lifetime:w("ephemeral_session_lifetime"),idle_ephemeral_session_lifetime:w("idle_ephemeral_session_lifetime"),default_redirection_uri:s("default_redirection_uri"),enabled_locales:s("enabled_locales"),default_directory:s("default_directory",{length:255}),error_page:s("error_page"),flags:s("flags"),friendly_name:s("friendly_name",{length:255}),picture_url:s("picture_url"),support_email:s("support_email",{length:255}),sandbox_version:s("sandbox_version",{length:50}),sandbox_versions_available:s("sandbox_versions_available"),legacy_sandbox_version:s("legacy_sandbox_version",{length:50}),change_password:s("change_password"),guardian_mfa_page:s("guardian_mfa_page"),device_flow:s("device_flow"),default_token_quota:s("default_token_quota"),default_audience:s("default_audience",{length:255}),default_organization:s("default_organization",{length:255}),sessions:s("sessions"),oidc_logout:s("oidc_logout"),allow_organization_name_in_authentication_api:w("allow_organization_name_in_authentication_api"),customize_mfa_in_postlogin_action:w("customize_mfa_in_postlogin_action"),acr_values_supported:s("acr_values_supported"),mtls:s("mtls"),pushed_authorization_requests_supported:w("pushed_authorization_requests_supported"),authorization_response_iss_parameter_supported:w("authorization_response_iss_parameter_supported")}),V=$("users",{user_id:s("user_id",{length:255}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),email:s("email",{length:255}),given_name:s("given_name",{length:255}),family_name:s("family_name",{length:255}),nickname:s("nickname",{length:255}),name:s("name",{length:255}),picture:s("picture",{length:2083}),tags:s("tags",{length:255}),phone_number:s("phone_number",{length:17}),phone_verified:w("phone_verified",{mode:"boolean"}),username:s("username",{length:128}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),linked_to:s("linked_to",{length:255}),last_ip:s("last_ip",{length:255}),login_count:w("login_count").notNull(),last_login:s("last_login",{length:255}),registration_completed_at:s("registration_completed_at",{length:35}),provider:s("provider",{length:255}).notNull(),connection:s("connection",{length:255}),email_verified:w("email_verified",{mode:"boolean"}).notNull(),is_social:w("is_social",{mode:"boolean"}).notNull(),app_metadata:s("app_metadata",{length:4096}).notNull().default("{}"),user_metadata:s("user_metadata").notNull().default("{}"),profileData:s("profileData",{length:2048}),locale:s("locale",{length:255}),middle_name:s("middle_name",{length:100}),preferred_username:s("preferred_username",{length:255}),profile:s("profile"),website:s("website"),gender:s("gender",{length:50}),birthdate:s("birthdate",{length:10}),zoneinfo:s("zoneinfo",{length:100}),address:s("address")},n=>[Te({columns:[n.user_id,n.tenant_id],name:"users_tenants"}),ht("unique_email_provider").on(n.email,n.provider,n.tenant_id),ht("unique_phone_provider").on(n.phone_number,n.provider,n.tenant_id),ht("unique_username_provider").on(n.username,n.provider,n.tenant_id),D("users_email_index").on(n.email),D("users_linked_to_index").on(n.linked_to),D("users_name_index").on(n.name),D("users_phone_tenant_provider_index").on(n.tenant_id,n.phone_number,n.provider)]),te=$("passwords",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:s("user_id",{length:255}).notNull(),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),password:s("password",{length:255}).notNull(),algorithm:s("algorithm",{length:16}).notNull().default("bcrypt"),is_current:w("is_current").notNull().default(1)}),oe=$("sessions",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:s("user_id",{length:255}),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull(),expires_at_ts:w("expires_at_ts"),idle_expires_at_ts:w("idle_expires_at_ts"),authenticated_at_ts:w("authenticated_at_ts"),last_interaction_at_ts:w("last_interaction_at_ts"),used_at_ts:w("used_at_ts"),revoked_at_ts:w("revoked_at_ts"),device:s("device").notNull(),clients:s("clients").notNull(),login_session_id:s("login_session_id",{length:21})},n=>[Te({columns:[n.tenant_id,n.id],name:"sessions_pk"}),D("IDX_sessions_login_session_id").on(n.login_session_id),D("idx_sessions_user_id").on(n.tenant_id,n.user_id),D("idx_sessions_expires_at_ts").on(n.expires_at_ts)]),X=$("refresh_tokens",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),client_id:s("client_id",{length:191}).notNull(),login_id:s("login_id",{length:21}).notNull(),user_id:s("user_id",{length:255}),resource_servers:s("resource_servers").notNull(),device:s("device").notNull(),rotating:w("rotating",{mode:"boolean"}).notNull(),created_at_ts:w("created_at_ts").notNull(),expires_at_ts:w("expires_at_ts"),idle_expires_at_ts:w("idle_expires_at_ts"),last_exchanged_at_ts:w("last_exchanged_at_ts"),revoked_at_ts:w("revoked_at_ts")},n=>[Te({columns:[n.tenant_id,n.id],name:"refresh_tokens_pk"}),D("idx_refresh_tokens_user_id").on(n.tenant_id,n.user_id),D("idx_refresh_tokens_login_id").on(n.login_id),D("idx_refresh_tokens_expires_at_ts").on(n.expires_at_ts)]),J=$("login_sessions",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),session_id:s("session_id",{length:21}),csrf_token:s("csrf_token",{length:21}).notNull(),auth_params:s("auth_params"),authorization_url:s("authorization_url"),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull(),expires_at_ts:w("expires_at_ts").notNull(),ip:s("ip",{length:39}),useragent:s("useragent"),auth0Client:s("auth0Client",{length:255}),state:s("state",{length:50}).notNull().default("pending"),state_data:s("state_data"),failure_reason:s("failure_reason"),user_id:s("user_id",{length:255}),auth_connection:s("auth_connection",{length:255}),auth_strategy_strategy:s("auth_strategy_strategy",{length:64}),auth_strategy_strategy_type:s("auth_strategy_strategy_type",{length:64}),authenticated_at:s("authenticated_at",{length:35})},n=>[Te({columns:[n.tenant_id,n.id],name:"login_sessions_pk"}),D("login_sessions_id_index").on(n.id),D("login_sessions_state_idx").on(n.state),D("login_sessions_state_updated_idx").on(n.state,n.updated_at_ts),D("login_sessions_tenant_user_idx").on(n.tenant_id,n.user_id),D("idx_login_sessions_expires_at_ts").on(n.expires_at_ts)]),re=$("codes",{code_id:s("code_id",{length:191}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:s("user_id",{length:255}),login_id:s("login_id",{length:255}),connection_id:s("connection_id",{length:255}),code_type:s("code_type",{length:255}).notNull(),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),used_at:s("used_at",{length:35}),code_verifier:s("code_verifier",{length:128}),code_challenge:s("code_challenge",{length:128}),code_challenge_method:s("code_challenge_method",{length:5}),redirect_uri:s("redirect_uri",{length:1024}),nonce:s("nonce",{length:1024}),state:s("state",{length:2048})},n=>[Te({columns:[n.code_id,n.code_type],name:"PK_codes_code_id_code_type"}),D("codes_expires_at_index").on(n.expires_at)]),Jr=$("authentication_codes",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),code:s("code",{length:255}).primaryKey(),client_id:s("client_id",{length:255}).notNull(),user_id:s("user_id",{length:255}).notNull(),nonce:s("nonce",{length:255}),state:s("state",{length:8192}),scope:s("scope",{length:1024}),response_type:s("response_type",{length:256}),response_mode:s("response_mode",{length:256}),redirect_uri:s("redirect_uri",{length:1024}),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),used_at:s("used_at",{length:35})}),Wr=$("otps",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),id:s("id",{length:255}).primaryKey(),client_id:s("client_id",{length:255}).notNull(),code:s("code",{length:255}).notNull(),email:s("email",{length:255}).notNull(),user_id:s("user_id",{length:255}),send:s("send",{length:255}),nonce:s("nonce",{length:255}),state:s("state",{length:1024}),scope:s("scope",{length:1024}),response_type:s("response_type",{length:256}),response_mode:s("response_mode",{length:256}),redirect_uri:s("redirect_uri",{length:1024}),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),used_at:s("used_at",{length:35}),audience:s("audience",{length:255}),ip:s("ip",{length:64})},n=>[D("otps_email_index").on(n.email),D("otps_expires_at_index").on(n.expires_at)]),Xr=$("tickets",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),id:s("id",{length:255}).primaryKey(),client_id:s("client_id",{length:255}).notNull(),email:s("email",{length:255}).notNull(),nonce:s("nonce",{length:255}),state:s("state",{length:1024}),scope:s("scope",{length:1024}),response_type:s("response_type",{length:256}),response_mode:s("response_mode",{length:256}),redirect_uri:s("redirect_uri",{length:1024}),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),used_at:s("used_at",{length:35})}),Z=$("clients",{client_id:s("client_id",{length:191}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:s("name",{length:255}).notNull(),description:s("description",{length:140}),global:w("global").notNull().default(0),client_secret:s("client_secret",{length:255}),app_type:s("app_type",{length:64}).default("regular_web"),logo_uri:s("logo_uri",{length:2083}),is_first_party:w("is_first_party").notNull().default(0),oidc_conformant:w("oidc_conformant").notNull().default(1),auth0_conformant:w("auth0_conformant").notNull().default(1),callbacks:s("callbacks").notNull(),allowed_origins:s("allowed_origins").notNull(),web_origins:s("web_origins").notNull(),client_aliases:s("client_aliases").notNull(),allowed_clients:s("allowed_clients").notNull(),allowed_logout_urls:s("allowed_logout_urls").notNull(),session_transfer:s("session_transfer").notNull(),oidc_logout:s("oidc_logout").notNull(),grant_types:s("grant_types").notNull(),jwt_configuration:s("jwt_configuration").notNull(),signing_keys:s("signing_keys").notNull(),encryption_key:s("encryption_key").notNull(),sso:w("sso").notNull().default(0),sso_disabled:w("sso_disabled").notNull().default(1),cross_origin_authentication:w("cross_origin_authentication").notNull().default(0),cross_origin_loc:s("cross_origin_loc",{length:2083}),custom_login_page_on:w("custom_login_page_on").notNull().default(0),custom_login_page:s("custom_login_page"),custom_login_page_preview:s("custom_login_page_preview"),form_template:s("form_template"),addons:s("addons").notNull(),token_endpoint_auth_method:s("token_endpoint_auth_method",{length:64}).default("client_secret_basic"),client_metadata:s("client_metadata").notNull(),mobile:s("mobile").notNull(),initiate_login_uri:s("initiate_login_uri",{length:2083}),native_social_login:s("native_social_login").notNull(),refresh_token:s("refresh_token").notNull(),default_organization:s("default_organization").notNull(),organization_usage:s("organization_usage",{length:32}).default("deny"),organization_require_behavior:s("organization_require_behavior",{length:32}).default("no_prompt"),client_authentication_methods:s("client_authentication_methods").notNull(),require_pushed_authorization_requests:w("require_pushed_authorization_requests").notNull().default(0),require_proof_of_possession:w("require_proof_of_possession").notNull().default(0),signed_request_object:s("signed_request_object").notNull(),compliance_level:s("compliance_level",{length:64}),par_request_expiry:w("par_request_expiry"),token_quota:s("token_quota").notNull(),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),connections:s("connections").notNull().default("[]"),owner_user_id:s("owner_user_id",{length:255}),registration_type:s("registration_type",{length:32}),registration_metadata:s("registration_metadata")},n=>[Te({columns:[n.tenant_id,n.client_id],name:"clients_tenant_id_client_id"}),D("idx_clients_owner_user_id").on(n.tenant_id,n.owner_user_id)]),G=$("client_registration_tokens",{id:s("id",{length:255}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),token_hash:s("token_hash",{length:64}).notNull(),type:s("type",{length:8}).notNull(),client_id:s("client_id",{length:191}),sub:s("sub",{length:255}),constraints:s("constraints"),single_use:w("single_use").notNull().default(0),used_at_ts:w("used_at_ts"),expires_at_ts:w("expires_at_ts"),created_at_ts:w("created_at_ts").notNull(),revoked_at_ts:w("revoked_at_ts")},n=>[ht("idx_client_registration_tokens_hash").on(n.tenant_id,n.token_hash),D("idx_client_registration_tokens_client").on(n.tenant_id,n.client_id)]),me=$("client_grants",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),client_id:s("client_id",{length:191}).notNull(),audience:s("audience",{length:191}).notNull(),scope:s("scope").default("[]"),organization_usage:s("organization_usage",{length:32}),allow_any_organization:w("allow_any_organization").default(0),is_system:w("is_system").default(0),subject_type:s("subject_type",{length:32}),authorization_details_types:s("authorization_details_types").default("[]"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.id],name:"pk_client_grants"}),D("idx_client_grants_audience").on(n.audience)]),pe=$("connections",{id:s("id",{length:255}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:s("name",{length:255}).notNull(),response_type:s("response_type",{length:255}),response_mode:s("response_mode",{length:255}),strategy:s("strategy",{length:64}),options:s("options",{length:8192}).notNull().default("{}"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull(),display_name:s("display_name",{length:255}),is_domain_connection:w("is_domain_connection"),show_as_button:w("show_as_button"),is_system:w("is_system").notNull().default(0),metadata:s("metadata",{length:4096})},n=>[Te({columns:[n.tenant_id,n.id]}),D("connections_tenant_id_index").on(n.tenant_id),ht("connections_id_unique").on(n.id)]),Oe=$("custom_domains",{custom_domain_id:s("custom_domain_id",{length:256}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),domain:s("domain",{length:255}).notNull(),primary:w("primary",{mode:"boolean"}).notNull(),status:s("status",{length:50}).notNull(),type:s("type",{length:50}).notNull(),origin_domain_name:s("origin_domain_name",{length:255}),verification:s("verification",{length:2048}),custom_client_ip_header:s("custom_client_ip_header",{length:50}),tls_policy:s("tls_policy",{length:50}),domain_metadata:s("domain_metadata",{length:2048}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[ht("custom_domains_domain_unique").on(n.domain)]),Yr=$("domains",{id:s("id",{length:255}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),domain:s("domain",{length:255}).notNull(),email_service:s("email_service",{length:255}),email_api_key:s("email_api_key",{length:255}),dkim_private_key:s("dkim_private_key",{length:2048}),dkim_public_key:s("dkim_public_key",{length:2048}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()}),W=$("organizations",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull(),name:s("name",{length:256}).notNull(),display_name:s("display_name",{length:256}),branding:s("branding"),metadata:s("metadata"),enabled_connections:s("enabled_connections"),token_quota:s("token_quota"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[D("idx_organizations_tenant_id").on(n.tenant_id)]),se=$("user_organizations",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull(),user_id:s("user_id",{length:191}).notNull(),organization_id:s("organization_id",{length:21}).notNull(),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[ht("user_organizations_unique").on(n.tenant_id,n.user_id,n.organization_id),D("idx_user_organizations_tenant_id").on(n.tenant_id),D("idx_user_organizations_user_id").on(n.user_id),D("idx_user_organizations_organization_id").on(n.organization_id)]),be=$("invites",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull(),organization_id:s("organization_id",{length:21}).notNull(),inviter:s("inviter").notNull(),invitee:s("invitee").notNull(),client_id:s("client_id",{length:191}).notNull(),connection_id:s("connection_id",{length:21}),invitation_url:s("invitation_url").notNull(),created_at:s("created_at",{length:35}).notNull(),expires_at:s("expires_at",{length:35}).notNull(),app_metadata:s("app_metadata"),user_metadata:s("user_metadata"),roles:s("roles"),ticket_id:s("ticket_id",{length:191}),ttl_sec:w("ttl_sec"),send_invitation_email:w("send_invitation_email")},n=>[D("idx_invites_tenant_id").on(n.tenant_id),D("idx_invites_organization_id").on(n.organization_id),D("idx_invites_expires_at").on(n.expires_at),D("idx_invites_tenant_created").on(n.tenant_id,n.created_at)]),_e=$("roles",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull(),name:s("name",{length:50}).notNull(),description:s("description",{length:255}),is_system:w("is_system").notNull().default(0),metadata:s("metadata",{length:4096}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.id],name:"roles_pk"})]),Ce=$("role_permissions",{tenant_id:s("tenant_id",{length:191}).notNull(),role_id:s("role_id",{length:21}).notNull(),resource_server_identifier:s("resource_server_identifier",{length:191}).notNull(),permission_name:s("permission_name",{length:191}).notNull(),created_at:s("created_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.role_id,n.resource_server_identifier,n.permission_name],name:"role_permissions_pk"}),D("role_permissions_role_fk").on(n.tenant_id,n.role_id),D("role_permissions_permission_fk").on(n.tenant_id,n.resource_server_identifier,n.permission_name)]),Le=$("user_permissions",{tenant_id:s("tenant_id",{length:191}).notNull(),user_id:s("user_id",{length:191}).notNull(),resource_server_identifier:s("resource_server_identifier",{length:191}).notNull(),permission_name:s("permission_name",{length:191}).notNull(),organization_id:s("organization_id",{length:21}).notNull().default(""),created_at:s("created_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.user_id,n.resource_server_identifier,n.permission_name,n.organization_id],name:"user_permissions_pk"}),D("user_permissions_user_fk").on(n.tenant_id,n.user_id),D("user_permissions_permission_fk").on(n.tenant_id,n.resource_server_identifier,n.permission_name),D("user_permissions_organization_fk").on(n.organization_id)]),Re=$("user_roles",{tenant_id:s("tenant_id",{length:191}).notNull(),user_id:s("user_id",{length:191}).notNull(),role_id:s("role_id",{length:21}).notNull(),organization_id:s("organization_id",{length:191}).notNull().default(""),created_at:s("created_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.user_id,n.role_id,n.organization_id],name:"user_roles_pk"}),D("user_roles_user_fk").on(n.tenant_id,n.user_id),D("user_roles_role_fk").on(n.tenant_id,n.role_id),D("user_roles_organization_fk").on(n.organization_id)]),Y=$("resource_servers",{id:s("id",{length:21}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull(),identifier:s("identifier",{length:191}).notNull(),name:s("name",{length:255}).notNull(),scopes:s("scopes",{length:4096}),signing_alg:s("signing_alg",{length:64}),signing_secret:s("signing_secret",{length:2048}),token_lifetime:w("token_lifetime"),token_lifetime_for_web:w("token_lifetime_for_web"),skip_consent_for_verifiable_first_party_clients:w("skip_consent_for_verifiable_first_party_clients"),allow_offline_access:w("allow_offline_access"),verification_key:s("verification_key",{length:4096}),options:s("options",{length:4096}),is_system:w("is_system").notNull().default(0),metadata:s("metadata",{length:4096}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.id],name:"resource_servers_pk"})]),At=$("branding",{tenant_id:s("tenant_id",{length:191}).primaryKey().references(()=>B.id,{onDelete:"cascade"}),logo_url:s("logo_url",{length:512}),favicon_url:s("favicon_url",{length:512}),font_url:s("font_url",{length:512}),colors_primary:s("colors_primary",{length:8}),colors_page_background_type:s("colors_page_background_type",{length:32}),colors_page_background_start:s("colors_page_background_start",{length:8}),colors_page_background_end:s("colors_page_background_end",{length:8}),colors_page_background_angle_dev:w("colors_page_background_angle_dev")}),nt=$("universal_login_templates",{tenant_id:s("tenant_id",{length:191}).primaryKey().references(()=>B.id,{onDelete:"cascade"}),body:s("body").notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()}),Me=$("themes",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),themeId:s("themeId",{length:255}).notNull(),displayName:s("displayName",{length:255}).notNull(),colors_primary_button_label:s("colors_primary_button_label",{length:24}).notNull(),colors_primary_button:s("colors_primary_button",{length:24}).notNull(),colors_secondary_button_border:s("colors_secondary_button_border",{length:24}).notNull(),colors_secondary_button_label:s("colors_secondary_button_label",{length:24}).notNull(),colors_base_focus_color:s("colors_base_focus_color",{length:24}).notNull(),colors_base_hover_color:s("colors_base_hover_color",{length:24}).notNull(),colors_body_text:s("colors_body_text",{length:24}).notNull(),colors_captcha_widget_theme:s("colors_captcha_widget_theme",{length:24}).notNull(),colors_error:s("colors_error",{length:24}).notNull(),colors_header:s("colors_header",{length:24}).notNull(),colors_icons:s("colors_icons",{length:24}).notNull(),colors_input_background:s("colors_input_background",{length:24}).notNull(),colors_input_border:s("colors_input_border",{length:24}).notNull(),colors_input_filled_text:s("colors_input_filled_text",{length:24}).notNull(),colors_input_labels_placeholders:s("colors_input_labels_placeholders",{length:24}).notNull(),colors_links_focused_components:s("colors_links_focused_components",{length:24}).notNull(),colors_success:s("colors_success",{length:24}).notNull(),colors_widget_background:s("colors_widget_background",{length:24}).notNull(),colors_widget_border:s("colors_widget_border",{length:24}).notNull(),borders_button_border_radius:w("borders_button_border_radius").notNull(),borders_button_border_weight:w("borders_button_border_weight").notNull(),borders_buttons_style:s("borders_buttons_style",{length:24}).notNull(),borders_input_border_radius:w("borders_input_border_radius").notNull(),borders_input_border_weight:w("borders_input_border_weight").notNull(),borders_inputs_style:s("borders_inputs_style",{length:24}).notNull(),borders_show_widget_shadow:w("borders_show_widget_shadow",{mode:"boolean"}).notNull(),borders_widget_border_weight:w("borders_widget_border_weight").notNull(),borders_widget_corner_radius:w("borders_widget_corner_radius").notNull(),fonts_body_text_bold:w("fonts_body_text_bold").notNull(),fonts_body_text_size:w("fonts_body_text_size").notNull(),fonts_buttons_text_bold:w("fonts_buttons_text_bold").notNull(),fonts_buttons_text_size:w("fonts_buttons_text_size").notNull(),fonts_font_url:s("fonts_font_url",{length:255}).notNull(),fonts_input_labels_bold:w("fonts_input_labels_bold").notNull(),fonts_input_labels_size:w("fonts_input_labels_size").notNull(),fonts_links_bold:w("fonts_links_bold",{mode:"boolean"}).notNull(),fonts_links_size:w("fonts_links_size").notNull(),fonts_links_style:s("fonts_links_style",{length:24}).notNull(),fonts_reference_text_size:w("fonts_reference_text_size").notNull(),fonts_subtitle_bold:w("fonts_subtitle_bold",{mode:"boolean"}).notNull(),fonts_subtitle_size:w("fonts_subtitle_size").notNull(),fonts_title_bold:w("fonts_title_bold",{mode:"boolean"}).notNull(),fonts_title_size:w("fonts_title_size").notNull(),page_background_background_color:s("page_background_background_color",{length:24}).notNull(),page_background_background_image_url:s("page_background_background_image_url",{length:255}).notNull(),page_background_page_layout:s("page_background_page_layout",{length:24}).notNull(),widget_header_text_alignment:s("widget_header_text_alignment",{length:24}).notNull(),widget_logo_height:w("widget_logo_height").notNull(),widget_logo_position:s("widget_logo_position",{length:24}).notNull(),widget_logo_url:s("widget_logo_url",{length:255}).notNull(),widget_social_buttons_layout:s("widget_social_buttons_layout",{length:24}).notNull(),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.themeId],name:"themes_pkey"}),D("themes_tenant_id_idx").on(n.tenant_id)]),Ee=$("forms",{id:s("id",{length:255}).primaryKey(),name:s("name",{length:255}).notNull(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),messages:s("messages",{length:255}),languages:s("languages",{length:255}),translations:s("translations",{length:4096}),nodes:s("nodes",{length:4096}),start:s("start",{length:255}),ending:s("ending",{length:255}),style:s("style",{length:1042}),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[D("forms_tenant_id_idx").on(n.tenant_id)]),xe=$("flows",{id:s("id",{length:24}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:s("name",{length:150}).notNull(),actions:s("actions"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()},n=>[D("flows_tenant_id_idx").on(n.tenant_id)]),It=$("prompt_settings",{tenant_id:s("tenant_id",{length:191}).primaryKey(),universal_login_experience:s("universal_login_experience",{length:16}).notNull().default("new"),identifier_first:w("identifier_first",{mode:"boolean"}).notNull().default(!0),password_first:w("password_first",{mode:"boolean"}).notNull().default(!1),webauthn_platform_first_factor:w("webauthn_platform_first_factor",{mode:"boolean"}).notNull().default(!1)}),it=$("email_providers",{tenant_id:s("tenant_id",{length:191}).primaryKey(),name:s("name",{length:255}).notNull(),enabled:w("enabled",{mode:"boolean"}).notNull(),default_from_address:s("default_from_address",{length:255}),credentials:s("credentials",{length:2048}).notNull().default("{}"),settings:s("settings",{length:2048}).notNull().default("{}"),created_at:s("created_at",{length:35}).notNull(),updated_at:s("updated_at",{length:35}).notNull()}),we=$("hooks",{hook_id:s("hook_id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),url:s("url",{length:512}),trigger_id:s("trigger_id",{length:255}).notNull(),enabled:w("enabled",{mode:"boolean"}).notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull(),synchronous:w("synchronous",{mode:"boolean"}).notNull().default(!1),priority:w("priority"),form_id:s("form_id",{length:128}),template_id:s("template_id",{length:64}),code_id:s("code_id",{length:21})},n=>[D("hooks_tenant_id_idx").on(n.tenant_id)]),qe=$("hook_code",{id:s("id",{length:21}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),code:s("code").notNull(),secrets:s("secrets"),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()},n=>[D("hook_code_tenant_id_idx").on(n.tenant_id)]),Be=$("keys",{kid:s("kid",{length:255}).primaryKey(),tenant_id:s("tenant_id",{length:191}).references(()=>B.id,{onDelete:"cascade"}),created_at:s("created_at",{length:35}).notNull(),revoked_at:s("revoked_at",{length:35}),cert:s("cert",{length:4096}),pkcs7:s("pkcs7",{length:4096}),fingerprint:s("fingerprint",{length:256}),thumbprint:s("thumbprint",{length:256}),current_since:s("current_since",{length:35}),current_until:s("current_until",{length:35}),type:s("type",{length:50}).notNull().default("jwt_signing"),connection:s("connection",{length:255}).references(()=>pe.id,{onDelete:"cascade"})}),Se=$("custom_text",{tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),prompt:s("prompt",{length:64}).notNull(),language:s("language",{length:16}).notNull(),custom_text:s("custom_text").notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()},n=>[Te({columns:[n.tenant_id,n.prompt,n.language]})]),ue=$("authentication_methods",{id:s("id",{length:26}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:s("user_id",{length:255}).notNull(),type:s("type",{length:32}).notNull(),phone_number:s("phone_number",{length:32}),totp_secret:s("totp_secret",{length:255}),credential_id:s("credential_id",{length:512}),public_key:s("public_key"),sign_count:w("sign_count"),credential_backed_up:w("credential_backed_up"),transports:s("transports",{length:512}),friendly_name:s("friendly_name",{length:255}),confirmed:w("confirmed").notNull().default(0),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()},n=>[D("authentication_methods_tenant_user_idx").on(n.tenant_id,n.user_id),D("authentication_methods_credential_id_idx").on(n.credential_id)]),Q=$("logs",{log_id:s("log_id",{length:21}).primaryKey(),category:s("category",{length:255}),tenant_id:s("tenant_id",{length:64}),user_id:s("user_id",{length:64}),ip:s("ip",{length:255}),type:s("type",{length:8}).notNull(),date:s("date",{length:35}).notNull(),client_id:s("client_id",{length:255}),client_name:s("client_name",{length:255}),user_agent:s("user_agent",{length:255}),description:s("description",{length:255}),details:s("details",{length:2048}),isMobile:w("isMobile"),user_name:s("user_name",{length:255}),connection:s("connection",{length:255}),connection_id:s("connection_id",{length:255}),audience:s("audience",{length:255}),scope:s("scope",{length:255}),strategy:s("strategy",{length:255}),strategy_type:s("strategy_type",{length:255}),hostname:s("hostname",{length:255}),auth0_client:s("auth0_client",{length:8192}),session_connection:s("session_connection",{length:255}),country_code:s("country_code",{length:2}),city_name:s("city_name",{length:255}),latitude:s("latitude",{length:255}),longitude:s("longitude",{length:255}),time_zone:s("time_zone",{length:255}),continent_code:s("continent_code",{length:2})},n=>[D("logs_user_id").on(n.user_id),D("logs_tenant_id").on(n.tenant_id),D("logs_date").on(n.date),D("IDX_logs_tenant_date_type_user").on(n.tenant_id,n.date,n.type,n.user_id)]),F=$("outbox_events",{id:s("id",{length:26}).primaryKey(),tenant_id:s("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),event_type:s("event_type",{length:64}).notNull(),log_type:s("log_type",{length:64}).notNull(),aggregate_type:s("aggregate_type",{length:64}).notNull(),aggregate_id:s("aggregate_id",{length:255}).notNull(),payload:s("payload").notNull(),created_at:s("created_at",{length:35}).notNull(),processed_at:s("processed_at",{length:35}),retry_count:w("retry_count").notNull().default(0),next_retry_at:s("next_retry_at",{length:35}),error:s("error"),claimed_by:s("claimed_by",{length:255}),claim_expires_at:s("claim_expires_at",{length:35}),dead_lettered_at:s("dead_lettered_at",{length:35}),final_error:s("final_error")},n=>[D("idx_outbox_events_tenant_id").on(n.tenant_id),D("idx_outbox_events_processed_at").on(n.processed_at),D("idx_outbox_events_claimed_by").on(n.claimed_by),D("idx_outbox_events_tenant_dead_lettered").on(n.tenant_id,n.dead_lettered_at)]),es=Object.freeze(Object.defineProperty({__proto__:null,authenticationCodes:Jr,authenticationMethods:ue,branding:At,clientGrants:me,clientRegistrationTokens:G,clients:Z,codes:re,connections:pe,customDomains:Oe,customText:Se,domains:Yr,emailProviders:it,flows:xe,forms:Ee,hookCode:qe,hooks:we,invites:be,keys:Be,loginSessions:J,logs:Q,organizations:W,otps:Wr,outboxEvents:F,passwords:te,promptSettings:It,refreshTokens:X,resourceServers:Y,rolePermissions:Ce,roles:_e,sessions:oe,tenants:B,themes:Me,tickets:Xr,universalLoginTemplates:nt,userOrganizations:se,userPermissions:Le,userRoles:Re,users:V},Symbol.toStringTag,{value:"Module"}));function K(n){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(t=>t!==null&&typeof t=="object"?K(t):t);const e={...n};for(const t in e){const i=e[t];i===null?delete e[t]:i!==null&&typeof i=="object"&&(Array.isArray(i)?e[t]=i.map(a=>a!==null&&typeof a=="object"?K(a):a):e[t]=K(i))}return e}function ts(n,e,t={...n}){for(const i of e)n[i]!==void 0&&(t[i]=JSON.stringify(n[i]));return t}function ns(n,e,t=n){for(const i of e)n[i]!==void 0&&(t[i]=n[i]?1:0)}function ar(n){const e={};for(const t in n)n[t]!==void 0&&n[t]!==null&&(e[t]=n[t]);return e}function z(n,e){if(n==null)return e;if(typeof n=="string")try{return JSON.parse(n)}catch{return e}return n}function Wn(n,e="",t={}){for(const i in n)if(Object.prototype.hasOwnProperty.call(n,i)){const a=e?`${e}_${i}`:i,r=n[i];typeof r=="object"&&r!==null&&!Array.isArray(r)?Wn(r,a,t):typeof r=="boolean"?t[a]=r?1:0:t[a]=r}return t}function or(n,e){const t={};for(const[i,a]of Object.entries(n)){const r=e.find(l=>i.startsWith(`${l}_`));if(!r)t[i]=a;else{const l=i.slice(r.length+1);t[r]={...t[r],[l]:a}}}return t}function is(n){return typeof n=="string"?parseInt(n,10):typeof n=="bigint"?Number(n):n}function as(n){return{async get(e){const t=await n.select().from(At).where(c(At.tenant_id,e)).get();if(!t)return null;const{tenant_id:i,colors_primary:a,colors_page_background_type:r,colors_page_background_start:l,colors_page_background_end:d,colors_page_background_angle_dev:u,font_url:f,...p}=t;return K({...p,colors:{primary:a,page_background:{type:r,start:l,end:d,angle_deg:u}},font:f?{url:f}:void 0})},async set(e,t){var d,u,f,p,v,m,N,T;const{colors:i,font:a,...r}=t,l={...r,tenant_id:e,colors_primary:i==null?void 0:i.primary,colors_page_background_type:(d=i==null?void 0:i.page_background)==null?void 0:d.type,colors_page_background_start:(u=i==null?void 0:i.page_background)==null?void 0:u.start,colors_page_background_end:(f=i==null?void 0:i.page_background)==null?void 0:f.end,colors_page_background_angle_dev:(p=i==null?void 0:i.page_background)==null?void 0:p.angle_deg,font_url:a==null?void 0:a.url};await n.insert(At).values(l).onConflictDoUpdate({target:At.tenant_id,set:{...r,colors_primary:i==null?void 0:i.primary,colors_page_background_type:(v=i==null?void 0:i.page_background)==null?void 0:v.type,colors_page_background_start:(m=i==null?void 0:i.page_background)==null?void 0:m.start,colors_page_background_end:(N=i==null?void 0:i.page_background)==null?void 0:N.end,colors_page_background_angle_dev:(T=i==null?void 0:i.page_background)==null?void 0:T.angle_deg,font_url:a==null?void 0:a.url}})}}}var rt=class extends Error{constructor(e=500,t){super(t==null?void 0:t.message,{cause:t==null?void 0:t.cause});y(this,"res");y(this,"status");this.res=t==null?void 0:t.res,this.status=e}getResponse(){return this.res?new Response(this.res.body,{status:this.status,headers:this.res.headers}):new Response(this.message,{status:this.status})}};function je(n,e,t){const i=e.split(/ OR /i);if(i.length>1){const f=i.map(p=>{const v=p.trim().match(/^([^:]+):(.+)$/);if(v){const[,m,N]=v;if(!m||!N)return null;const T=N.replace(/^"(.*)"$/,"$1"),ee=n[m.trim()];return ee?c(ee,T.trim()):null}return null}).filter(Boolean);return f.length===0?void 0:Ue(...f)}const a=[];let r="",l=!1;for(let f=0;f<e.length;f++){const p=e[f];p==='"'?(l=!l,r+=p):p===" "&&!l?r.trim()&&(a.push(r.trim()),r=""):r+=p}r.trim()&&a.push(r.trim());const d=a.map(f=>f.replace(/^([^:]+)=/g,"$1:")).map(f=>{let p=f.startsWith("-"),v=null,m="",N=!1,T;if(f.startsWith("-_exists_:"))v=f.substring(10),N=!0,p=!0;else if(f.startsWith("_exists_:"))v=f.substring(9),N=!0,p=!1;else if(f.includes(":")){const ee=p?f.substring(1):f,ie=ee.indexOf(":");v=ee.substring(0,ie),m=ee.substring(ie+1),N=!1,m.startsWith(">=")?(T=">=",m=m.substring(2)):m.startsWith(">")?(T=">",m=m.substring(1)):m.startsWith("<=")?(T="<=",m=m.substring(2)):m.startsWith("<")?(T="<",m=m.substring(1)):T="=",m.startsWith('"')&&m.endsWith('"')&&m.length>1&&(m=m.slice(1,-1))}else v=null,m=f,N=!1;return{key:v,value:m,isNegation:p,isExistsQuery:N,operator:T}}),u=[];for(const{key:f,value:p,isNegation:v,isExistsQuery:m,operator:N}of d)if(f){const T=n[f];if(!T){m?u.push(v?A`${A.identifier(f)} IS NULL`:A`${A.identifier(f)} IS NOT NULL`):u.push(A`${A.identifier(f)} ${A.raw(v?"!=":N??"=")} ${p}`);continue}if(m)u.push(v?Ae(T):nn(T));else if(v)switch(N){case">":u.push(ft(T,p));break;case">=":u.push(Xe(T,p));break;case"<":u.push(sn(T,p));break;case"<=":u.push(rn(T,p));break;default:u.push(Br(T,p))}else switch(N){case">":u.push(rn(T,p));break;case">=":u.push(sn(T,p));break;case"<":u.push(Xe(T,p));break;case"<=":u.push(ft(T,p));break;default:u.push(c(T,p))}}else if(p){const ee=(p.includes("|")?[...t,"user_id"]:t).map(ie=>{const ae=n[ie];return ae?ie==="user_id"?c(ae,p):St(ae,`%${p}%`):null}).filter(Boolean);ee.length>0&&u.push(Ue(...ee))}if(u.length!==0)return u.length===1?u[0]:g(...u)}const hi=["global","is_first_party","oidc_conformant","auth0_conformant","sso","sso_disabled","cross_origin_authentication","custom_login_page_on","require_pushed_authorization_requests","require_proof_of_possession"],gi=["callbacks","allowed_origins","web_origins","client_aliases","allowed_clients","allowed_logout_urls","grant_types","signing_keys"],mi=["session_transfer","oidc_logout","jwt_configuration","encryption_key","addons","client_metadata","mobile","native_social_login","refresh_token","default_organization","client_authentication_methods","signed_request_object","token_quota","registration_metadata"];function Wt(n){const{tenant_id:e,connections:t,...i}=n,a={...i};for(const r of hi)a[r]=!!i[r];for(const r of gi)a[r]=z(i[r],[]);for(const r of mi)a[r]=z(i[r],{});return a.connections=z(t,[]),K(a)}function xi(n){const e={...n};ns(n,hi,e);for(const t of gi)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]||[]));for(const t of mi)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]||{}));return n.connections!==void 0&&(e.connections=JSON.stringify(n.connections||[])),ar(e)}function os(n){return{async create(e,t){var l,d;const i=new Date().toISOString(),a={client_id:t.client_id,tenant_id:e,name:t.name,description:t.description,app_type:t.app_type??"regular_web",logo_uri:t.logo_uri,client_secret:t.client_secret,token_endpoint_auth_method:t.token_endpoint_auth_method??"client_secret_basic",cross_origin_loc:t.cross_origin_loc,custom_login_page:t.custom_login_page,custom_login_page_preview:t.custom_login_page_preview,form_template:t.form_template,initiate_login_uri:t.initiate_login_uri,organization_usage:t.organization_usage??"deny",organization_require_behavior:t.organization_require_behavior??"no_prompt",compliance_level:t.compliance_level,par_request_expiry:t.par_request_expiry,created_at:i,updated_at:i};for(const u of hi)a[u]=t[u]??!1;a.oidc_conformant=t.oidc_conformant??!0,a.auth0_conformant=t.auth0_conformant??!0,a.sso_disabled=t.sso_disabled??!1;for(const u of gi)a[u]=t[u]||[];for(const u of mi)a[u]=t[u]||{};a.connections=t.connections||[];const r=xi(a);try{await n.insert(Z).values({...r,tenant_id:e})}catch(u){throw(l=u==null?void 0:u.message)!=null&&l.includes("UNIQUE constraint failed")||(d=u==null?void 0:u.message)!=null&&d.includes("duplicate key")?new rt(409,{message:"Client already exists"}):u}return Wt({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(Z).where(g(c(Z.tenant_id,e),c(Z.client_id,t))).get();return i?Wt(i):null},async getByClientId(e){const t=await n.select().from(Z).where(c(Z.client_id,e)).get();return t?{...Wt(t),tenant_id:t.tenant_id}:null},async update(e,t,i){const a=xi({...i,updated_at:new Date().toISOString()});return delete a.client_id,delete a.tenant_id,await n.update(Z).set(a).where(g(c(Z.tenant_id,e),c(Z.client_id,t))),!0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{};let u=n.select().from(Z).where(c(Z.tenant_id,e)).$dynamic();if(d){const m=je(Z,d,["name","client_id"]);m&&(u=u.where(g(c(Z.tenant_id,e),m)))}if(l!=null&&l.sort_by){const m=Z[l.sort_by];m&&(u=u.orderBy(l.sort_order==="desc"?ce(m):ge(m)))}const p=(await u.offset(i*a).limit(a)).map(Wt);if(!r)return{clients:p};const[v]=await n.select({count:he()}).from(Z).where(c(Z.tenant_id,e));return{clients:p,start:i*a,limit:a,length:Number((v==null?void 0:v.count)??0)}},async remove(e,t){return(await n.delete(Z).where(g(c(Z.tenant_id,e),c(Z.client_id,t))).returning()).length>0}}}function rs(n){const{tenant_id:e,is_system:t,options:i,metadata:a,...r}=n;return K({...r,options:z(i,{}),metadata:z(a),is_system:t?!0:void 0})}function ss(n){return{async listByClient(e,t){const i=await n.select({connections:Z.connections}).from(Z).where(g(c(Z.tenant_id,e),c(Z.client_id,t))).get();if(!i)return[];const a=z(i.connections,[])||[];if(a.length===0)return[];const l=(await n.select().from(pe).where(g(c(pe.tenant_id,e),Ye(pe.id,a))).all()).map(rs);return a.map(d=>l.find(u=>u.id===d)).filter(Boolean)},async updateByClient(e,t,i){return(await n.update(Z).set({connections:JSON.stringify([...new Set(i)])}).where(g(c(Z.tenant_id,e),c(Z.client_id,t))).returning()).length>0},async listByConnection(e,t){return(await n.select({client_id:Z.client_id,connections:Z.connections}).from(Z).where(c(Z.tenant_id,e)).all()).filter(a=>(z(a.connections,[])||[]).includes(t)).map(a=>a.client_id)},async addClientToConnection(e,t,i){var d;if(!await n.select({client_id:Z.client_id}).from(Z).where(g(c(Z.tenant_id,e),c(Z.client_id,i))).get())return!1;const r=await n.run(A`UPDATE clients SET connections = CASE
2
2
  WHEN connections IS NULL OR connections = '[]' OR connections = ''
3
- THEN json_array(${e})
4
- WHEN EXISTS (SELECT 1 FROM json_each(connections) WHERE value = ${e})
3
+ THEN json_array(${t})
4
+ WHEN EXISTS (SELECT 1 FROM json_each(connections) WHERE value = ${t})
5
5
  THEN connections
6
- ELSE json_insert(connections, '$[#]', ${e})
6
+ ELSE json_insert(connections, '$[#]', ${t})
7
7
  END
8
- WHERE tenant_id = ${i} AND client_id = ${t}`);return(o.changes??((_=o.meta)==null?void 0:_.changes)??0)>0},async removeClientFromConnection(i,e,t){var l;const r=await n.run(w`UPDATE clients SET connections = (
8
+ WHERE tenant_id = ${e} AND client_id = ${i}`);return(r.changes??((d=r.meta)==null?void 0:d.changes)??0)>0},async removeClientFromConnection(e,t,i){var l;const a=await n.run(A`UPDATE clients SET connections = (
9
9
  SELECT COALESCE(json_group_array(je.value), '[]')
10
10
  FROM json_each(COALESCE(connections, '[]')) AS je
11
- WHERE je.value != ${e}
11
+ WHERE je.value != ${t}
12
12
  )
13
- WHERE tenant_id = ${i} AND client_id = ${t}`);return(r.changes??((l=r.meta)==null?void 0:l.changes)??0)>0}}}let Wr="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Hr=n=>crypto.getRandomValues(new Uint8Array(n)),Gr=(n,i,e)=>{let t=256-256%n.length;if(t===256){let o=n.length-1;return(l=i)=>{if(!l)return"";let _="";for(;;){let u=e(l),c=l;for(;c--;)if(_+=n[u[c]&o],_.length>=l)return _}}}let r=Math.ceil(1.6*256*i/t);return(o=i)=>{if(!o)return"";let l="";for(;;){let _=e(r),u=r;for(;u--;)if(_[u]<t&&(l+=n[_[u]%n.length],l.length>=o))return l}}},Yr=(n,i=21)=>Gr(n,i|0,Hr),ae=(n=21)=>{let i="",e=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)i+=Wr[e[n]&63];return i};function tt(n){const{tenant_id:i,scope:e,authorization_details_types:t,allow_any_organization:r,is_system:o,...l}=n;return T({...l,scope:x(e,[]),authorization_details_types:x(t,[]),allow_any_organization:!!r,is_system:!!o})}function Xr(n){return{async create(i,e){const t=new Date().toISOString(),o={id:e.id||ae(),tenant_id:i,client_id:e.client_id,audience:e.audience,scope:JSON.stringify(e.scope||[]),organization_usage:e.organization_usage,allow_any_organization:e.allow_any_organization?1:0,is_system:e.is_system?1:0,subject_type:e.subject_type,authorization_details_types:JSON.stringify(e.authorization_details_types||[]),created_at:t,updated_at:t};return await n.insert(Y).values(o),tt({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(Y).where(g(a(Y.tenant_id,i),a(Y.id,e))).get();return t?tt(t):null},async update(i,e,t){const{scope:r,authorization_details_types:o,allow_any_organization:l,is_system:_,...u}=t,c={...u,updated_at:new Date().toISOString()};return r!==void 0&&(c.scope=JSON.stringify(r)),o!==void 0&&(c.authorization_details_types=JSON.stringify(o)),l!==void 0&&(c.allow_any_organization=l?1:0),_!==void 0&&(c.is_system=_?1:0),(await n.update(Y).set(c).where(g(a(Y.tenant_id,i),a(Y.id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{},u=_?ye(Y,_,["client_id","audience"]):void 0,c=u?g(a(Y.tenant_id,i),u):a(Y.tenant_id,i);let d=n.select().from(Y).where(c).$dynamic();if(l!=null&&l.sort_by){const N=Y[l.sort_by];N&&(d=d.orderBy(l.sort_order==="desc"?V(N):G(N)))}else d=d.orderBy(G(Y.created_at));const f=(await d.offset(t*r).limit(r)).map(tt);if(!o)return{client_grants:f};const[y]=await n.select({count:R()}).from(Y).where(c);return{client_grants:f,start:t*r,limit:r,length:Number((y==null?void 0:y.count)??0)}},async remove(i,e){return(await n.delete(Y).where(g(a(Y.tenant_id,i),a(Y.id,e))).returning()).length>0}}}function nt(n){const{tenant_id:i,...e}=n;return T(e)}function Zr(n){return{async create(i,e){const t={...e,tenant_id:i,created_at:e.created_at||new Date().toISOString(),expires_at:e.expires_at};return await n.insert(J).values(t),nt(t)},async get(i,e,t){if(!i)throw new Error("tenant_id is required");const r=await n.select().from(J).where(g(a(J.tenant_id,i),a(J.code_id,e),a(J.code_type,t))).get();return r?nt(r):null},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l}=e||{};let _=n.select().from(J).where(a(J.tenant_id,i)).$dynamic();if(l!=null&&l.sort_by){const h=J[l.sort_by];h&&(_=_.orderBy(l.sort_order==="desc"?V(h):G(h)))}const c=(await _.offset(t*r).limit(r)).map(nt);if(!o)return{codes:c};const[d]=await n.select({count:R()}).from(J).where(a(J.tenant_id,i));return{codes:c,start:t*r,limit:r,length:Number((d==null?void 0:d.count)??0)}},async used(i,e){return(await n.update(J).set({used_at:new Date().toISOString()}).where(g(a(J.tenant_id,i),a(J.code_id,e))).returning()).length>0},async consume(i,e){return(await n.update(J).set({used_at:new Date().toISOString()}).where(g(a(J.tenant_id,i),a(J.code_id,e),me(J.used_at))).returning()).length>0},async remove(i,e){return(await n.delete(J).where(g(a(J.tenant_id,i),a(J.code_id,e))).returning()).length>0}}}function es(){const{customAlphabet:n}=require("nanoid");return`con_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function it(n){const{tenant_id:i,is_system:e,options:t,metadata:r,...o}=n;return T({...o,options:x(t,{}),metadata:x(r),is_system:e?!0:void 0})}function ts(n){return{async create(i,e){var o,l;const t=new Date().toISOString(),r={id:e.id||es(),...e,tenant_id:i,options:JSON.stringify(e.options||{}),metadata:e.metadata?JSON.stringify(e.metadata):void 0,is_system:e.is_system?1:0,created_at:t,updated_at:t};try{await n.insert(j).values(r)}catch(_){throw(o=_==null?void 0:_.message)!=null&&o.includes("UNIQUE constraint failed")||(l=_==null?void 0:_.message)!=null&&l.includes("duplicate key")?new be(409,{message:"Connection already exists"}):_}return it(r)},async get(i,e){const t=await n.select().from(j).where(g(a(j.tenant_id,i),a(j.id,e))).get();return t?it(t):null},async update(i,e,t){const r={updated_at:new Date().toISOString()};return t.name!==void 0&&(r.name=t.name),t.strategy!==void 0&&(r.strategy=t.strategy),t.options!==void 0&&(r.options=JSON.stringify(t.options)),t.metadata!==void 0&&(r.metadata=JSON.stringify(t.metadata)),t.display_name!==void 0&&(r.display_name=t.display_name),t.response_type!==void 0&&(r.response_type=t.response_type),t.response_mode!==void 0&&(r.response_mode=t.response_mode),await n.update(j).set(r).where(g(a(j.tenant_id,i),a(j.id,e))),!0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{};let u=a(j.tenant_id,i);if(_){const y=ye(j,_,["name"]);y&&(u=g(u,y))}let c=n.select().from(j).where(u).$dynamic();if(l!=null&&l.sort_by){const y=j[l.sort_by];y&&(c=c.orderBy(l.sort_order==="desc"?V(y):G(y)))}const h=(await c.offset(t*r).limit(r)).map(it);if(!o)return{connections:h};const[f]=await n.select({count:R()}).from(j).where(u);return{connections:h,start:t*r,limit:r,length:Number((f==null?void 0:f.count)??0)}},async remove(i,e){return(await n.delete(j).where(g(a(j.tenant_id,i),a(j.id,e))).returning()).length>0}}}function Ue(n){const{tenant_id:i,domain_metadata:e,...t}=n;return T({...t,primary:!!t.primary,domain_metadata:x(e)})}function ns(n){return{async create(i,e){const t=new Date().toISOString(),o={custom_domain_id:e.custom_domain_id||ae(),tenant_id:i,domain:e.domain,primary:e.primary??!1,status:e.status||"pending",type:e.type,origin_domain_name:e.origin_domain_name,verification:e.verification,custom_client_ip_header:e.custom_client_ip_header,tls_policy:e.tls_policy,domain_metadata:e.domain_metadata?JSON.stringify(e.domain_metadata):void 0,created_at:t,updated_at:t};return await n.insert(se).values(o),Ue({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(se).where(g(a(se.tenant_id,i),a(se.custom_domain_id,e))).get();return t?Ue(t):null},async getByDomain(i){const e=await n.select().from(se).where(a(se.domain,i)).get();return e?{...Ue(e),tenant_id:e.tenant_id}:null},async list(i){return(await n.select().from(se).where(a(se.tenant_id,i)).all()).map(Ue)},async update(i,e,t){const r={updated_at:new Date().toISOString()};return t.domain!==void 0&&(r.domain=t.domain),t.primary!==void 0&&(r.primary=t.primary),t.status!==void 0&&(r.status=t.status),t.type!==void 0&&(r.type=t.type),t.origin_domain_name!==void 0&&(r.origin_domain_name=t.origin_domain_name),t.verification!==void 0&&(r.verification=t.verification),t.custom_client_ip_header!==void 0&&(r.custom_client_ip_header=t.custom_client_ip_header),t.tls_policy!==void 0&&(r.tls_policy=t.tls_policy),t.domain_metadata!==void 0&&(r.domain_metadata=JSON.stringify(t.domain_metadata)),(await n.update(se).set(r).where(g(a(se.tenant_id,i),a(se.custom_domain_id,e))).returning()).length>0},async remove(i,e){return(await n.delete(se).where(g(a(se.tenant_id,i),a(se.custom_domain_id,e))).returning()).length>0}}}function is(n){return{async get(i,e,t){const r=await n.select().from(te).where(g(a(te.tenant_id,i),a(te.prompt,e),a(te.language,t))).get();if(!r)return null;try{return JSON.parse(r.custom_text)}catch{return null}},async set(i,e,t,r){const o=Date.now(),l=JSON.stringify(r);await n.insert(te).values({tenant_id:i,prompt:e,language:t,custom_text:l,created_at_ts:o,updated_at_ts:o}).onConflictDoUpdate({target:[te.tenant_id,te.prompt,te.language],set:{custom_text:l,updated_at_ts:o}})},async delete(i,e,t){await n.delete(te).where(g(a(te.tenant_id,i),a(te.prompt,e),a(te.language,t)))},async list(i){return await n.select({prompt:te.prompt,language:te.language}).from(te).where(a(te.tenant_id,i)).all()}}}function rs(n){return{async create(i,e){const t=new Date().toISOString();await n.insert(Se).values({tenant_id:i,name:e.name,enabled:e.enabled,default_from_address:e.default_from_address,credentials:JSON.stringify(e.credentials||{}),settings:JSON.stringify(e.settings||{}),created_at:t,updated_at:t})},async get(i){const e=await n.select().from(Se).where(a(Se.tenant_id,i)).get();if(!e)return null;const{tenant_id:t,...r}=e;return T({...r,enabled:!!r.enabled,credentials:x(r.credentials,{}),settings:x(r.settings,{})})},async update(i,e){const t={updated_at:new Date().toISOString()};e.name!==void 0&&(t.name=e.name),e.enabled!==void 0&&(t.enabled=e.enabled),e.default_from_address!==void 0&&(t.default_from_address=e.default_from_address),e.credentials!==void 0&&(t.credentials=JSON.stringify(e.credentials)),e.settings!==void 0&&(t.settings=JSON.stringify(e.settings)),await n.update(Se).set(t).where(a(Se.tenant_id,i))},async remove(i){await n.delete(Se).where(a(Se.tenant_id,i))}}}function ss(n){return{async create(i,e){const t=new Date().toISOString(),r=`af_${ae()}`;return await n.insert(re).values({id:r,tenant_id:i,name:e.name,actions:JSON.stringify(e.actions||[]),created_at:t,updated_at:t}),{id:r,name:e.name,actions:e.actions||[],created_at:t,updated_at:t}},async get(i,e){const t=await n.select().from(re).where(g(a(re.tenant_id,i),a(re.id,e))).get();if(!t)return null;const{tenant_id:r,actions:o,...l}=t;return T({...l,actions:x(o,[])})},async update(i,e,t){const r={updated_at:new Date().toISOString()};return t.name!==void 0&&(r.name=t.name),t.actions!==void 0&&(r.actions=JSON.stringify(t.actions)),(await n.update(re).set(r).where(g(a(re.tenant_id,i),a(re.id,e))).returning()).length===0?null:this.get(i,e)},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l}=e||{};let _=n.select().from(re).where(a(re.tenant_id,i)).$dynamic();if(l!=null&&l.sort_by){const h=re[l.sort_by];h&&(_=_.orderBy(l.sort_order==="desc"?V(h):G(h)))}const c=(await _.offset(t*r).limit(r)).map(h=>{const{tenant_id:f,actions:y,...N}=h;return T({...N,actions:x(y,[])})});if(!o)return{flows:c};const[d]=await n.select({count:R()}).from(re).where(a(re.tenant_id,i));return{flows:c,start:t*r,limit:r,length:Number((d==null?void 0:d.count)??0)}},async remove(i,e){return(await n.delete(re).where(g(a(re.tenant_id,i),a(re.id,e))).returning()).length>0}}}const Ke=["nodes","start","ending"];function os(n){return{async create(i,e){const t=new Date().toISOString(),r=ae(),o={id:r,tenant_id:i,name:e.name,messages:e.messages,languages:e.languages,translations:e.translations,style:e.style,created_at:t,updated_at:t};for(const l of Ke)o[l]=JSON.stringify(e[l]||(l==="nodes"?[]:{}));return await n.insert(ie).values(o),{id:r,...e,created_at:t,updated_at:t}},async get(i,e){const t=await n.select().from(ie).where(g(a(ie.tenant_id,i),a(ie.id,e))).get();if(!t)return null;const{tenant_id:r,...o}=t,l={...o};for(const _ of Ke)l[_]=x(o[_]);return T(l)},async update(i,e,t){const r={updated_at:new Date().toISOString()};for(const[l,_]of Object.entries(t))_!==void 0&&(Ke.includes(l)?r[l]=JSON.stringify(_):r[l]=_);return(await n.update(ie).set(r).where(g(a(ie.tenant_id,i),a(ie.id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l}=e||{};let _=n.select().from(ie).where(a(ie.tenant_id,i)).$dynamic();if(l!=null&&l.sort_by){const h=ie[l.sort_by];h&&(_=_.orderBy(l.sort_order==="desc"?V(h):G(h)))}const c=(await _.offset(t*r).limit(r)).map(h=>{const{tenant_id:f,...y}=h,N={...y};for(const B of Ke)N[B]=x(y[B]);return T(N)});if(!o)return{forms:c};const[d]=await n.select({count:R()}).from(ie).where(a(ie.tenant_id,i));return{forms:c,start:t*r,limit:r,length:Number((d==null?void 0:d.count)??0)}},async remove(i,e){return(await n.delete(ie).where(g(a(ie.tenant_id,i),a(ie.id,e))).returning()).length>0}}}function pr(n){if(n!=null){if(typeof n=="number")return new Date(n).toISOString();if(typeof n=="string"){if(n==="")return;const i=parseFloat(n);return!isNaN(i)&&/^\d+(\.\d+)?$/.test(n)?new Date(i).toISOString():n}}}function wt(n,i=new Date(0).toISOString()){return pr(n)??i}function Q(n){if(!n||n==="")return null;const i=new Date(n);return isNaN(i.getTime())?null:i.getTime()}function Pe(n,i,e=[]){const t={};for(const r of i){const o=r.replace(/_ts$/,"");t[o]=wt(n[r])}for(const r of e){const o=r.replace(/_ts$/,"");t[o]=pr(n[r])}return t}const as=Yr("0123456789abcdefghijklmnopqrstuvwxyz",17);function ls(){return`hc_${as()}`}function At(n){const{created_at_ts:i,updated_at_ts:e,secrets:t,...r}=n,o=Pe({created_at_ts:i,updated_at_ts:e},["created_at_ts","updated_at_ts"]);return{...r,...o,secrets:t?JSON.parse(t):void 0}}function _s(n){return{async create(i,e){const t=Date.now(),o={id:ls(),tenant_id:i,code:e.code,secrets:e.secrets?JSON.stringify(e.secrets):null,created_at_ts:t,updated_at_ts:t};return await n.insert(pe).values(o),At({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(pe).where(g(a(pe.tenant_id,i),a(pe.id,e))).get();return t?At(t):null},async update(i,e,t){const r={updated_at_ts:Date.now()};return t.code!==void 0&&(r.code=t.code),t.secrets!==void 0&&(r.secrets=JSON.stringify(t.secrets)),(await n.update(pe).set(r).where(g(a(pe.tenant_id,i),a(pe.id,e))).returning()).length>0},async remove(i,e){return(await n.delete(pe).where(g(a(pe.tenant_id,i),a(pe.id,e))).returning()).length>0}}}function us(){const{customAlphabet:n}=require("nanoid");return`h_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function rt(n){const{tenant_id:i,created_at_ts:e,updated_at_ts:t,...r}=n,o=Pe({created_at_ts:e,updated_at_ts:t},["created_at_ts","updated_at_ts"]);return T({...r,enabled:!!r.enabled,synchronous:!!r.synchronous,...o})}function ds(n){return{async create(i,e){const t=Date.now(),o={hook_id:e.hook_id||us(),tenant_id:i,trigger_id:e.trigger_id,url:e.url,enabled:e.enabled??!0,synchronous:e.synchronous??!1,priority:e.priority,form_id:e.form_id,template_id:e.template_id,code_id:e.code_id,created_at_ts:t,updated_at_ts:t};return await n.insert(ee).values(o),rt({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(ee).where(g(a(ee.tenant_id,i),a(ee.hook_id,e))).get();return t?rt(t):null},async update(i,e,t){const r={updated_at_ts:Date.now()};return t.trigger_id!==void 0&&(r.trigger_id=t.trigger_id),t.url!==void 0&&(r.url=t.url),t.enabled!==void 0&&(r.enabled=t.enabled),t.synchronous!==void 0&&(r.synchronous=t.synchronous),t.priority!==void 0&&(r.priority=t.priority),t.form_id!==void 0&&(r.form_id=t.form_id),t.template_id!==void 0&&(r.template_id=t.template_id),t.code_id!==void 0&&(r.code_id=t.code_id),(await n.update(ee).set(r).where(g(a(ee.tenant_id,i),a(ee.hook_id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{},u=_?ye(ee,_,["url","form_id","template_id","code_id"]):void 0,c=u?g(a(ee.tenant_id,i),u):a(ee.tenant_id,i);let d=n.select().from(ee).where(c).$dynamic();if(l!=null&&l.sort_by){const N=ee[l.sort_by];N&&(d=d.orderBy(l.sort_order==="desc"?V(N):G(N)))}const f=(await d.offset(t*r).limit(r)).map(rt);if(!o)return{hooks:f};const[y]=await n.select({count:R()}).from(ee).where(c);return{hooks:f,start:t*r,limit:r,length:Number((y==null?void 0:y.count)??0)}},async remove(i,e){return(await n.delete(ee).where(g(a(ee.tenant_id,i),a(ee.hook_id,e))).returning()).length>0}}}function cs(){const{customAlphabet:n}=require("nanoid");return`inv_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const Nt=["inviter","invitee","app_metadata","user_metadata","roles"];function st(n){const{tenant_id:i,send_invitation_email:e,...t}=n,r={...t};for(const o of Nt)r[o]=x(t[o],o==="roles"?[]:{});return r.send_invitation_email=!!e,T(r)}function gs(n){return{async create(i,e){var u,c;const t=e.id||cs(),r=e.ttl_sec||604800,o=new Date,l=new Date(o.getTime()+r*1e3).toISOString(),_={id:t,tenant_id:i,organization_id:e.organization_id,client_id:e.client_id,connection_id:e.connection_id,invitation_url:e.invitation_url,ticket_id:e.ticket_id,ttl_sec:r,send_invitation_email:e.send_invitation_email!==!1?1:0,created_at:o.toISOString(),expires_at:l};for(const d of Nt)e[d]!==void 0&&(_[d]=JSON.stringify(e[d]));try{await n.insert(ne).values(_)}catch(d){throw(u=d==null?void 0:d.message)!=null&&u.includes("UNIQUE constraint failed")||(c=d==null?void 0:d.message)!=null&&c.includes("duplicate key")?new be(409,{message:"Invite already exists"}):d}return st({..._,tenant_id:i})},async get(i,e){const t=await n.select().from(ne).where(g(a(ne.tenant_id,i),a(ne.id,e))).get();return t?st(t):null},async update(i,e,t){const r={};for(const l of Nt)t[l]!==void 0&&(r[l]=JSON.stringify(t[l]));return t.connection_id!==void 0&&(r.connection_id=t.connection_id),t.ttl_sec!==void 0&&(r.ttl_sec=t.ttl_sec,r.expires_at=new Date(Date.now()+t.ttl_sec*1e3).toISOString()),(await n.update(ne).set(r).where(g(a(ne.tenant_id,i),a(ne.id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l}=e||{};let _=n.select().from(ne).where(a(ne.tenant_id,i)).$dynamic();if(l!=null&&l.sort_by){const h=ne[l.sort_by];h&&(_=_.orderBy(l.sort_order==="desc"?V(h):G(h)))}const c=(await _.offset(t*r).limit(r)).map(st);if(!o)return{invites:c};const[d]=await n.select({count:R()}).from(ne).where(a(ne.tenant_id,i));return{invites:c,start:t*r,limit:r,length:Number((d==null?void 0:d.count)??0)}},async remove(i,e){return(await n.delete(ne).where(g(a(ne.tenant_id,i),a(ne.id,e))).returning()).length>0}}}function fs(n){return{async create(i){await n.insert(he).values({...i,created_at:new Date().toDateString()})},async list(i){const{page:e=0,per_page:t=50,include_totals:r=!1,sort:o}=i||{},l=new Date().toISOString();let _=n.select().from(he).where(de(We(he.revoked_at,l),me(he.revoked_at))).$dynamic();if(o!=null&&o.sort_by){const h=he[o.sort_by];h&&(_=_.orderBy(o.sort_order==="desc"?V(h):G(h)))}const c=(await _.offset(e*t).limit(t)).map(h=>{const{created_at:f,...y}=h;return T(y)});if(!r)return{signingKeys:c};const[d]=await n.select({count:R()}).from(he).where(de(We(he.revoked_at,l),me(he.revoked_at)));return{signingKeys:c,start:e*t,limit:t,length:Kr((d==null?void 0:d.count)??0)}},async update(i,e){return(await n.update(he).set(e).where(a(he.kid,i)).returning()).length>0}}}const vt="0123456789ABCDEFGHJKMNPQRSTVWXYZ",ot=vt.length;function ps(){let e=Date.now(),t="";for(let o=10;o>0;o--)t=vt.charAt(e%ot)+t,e=Math.floor(e/ot);const r=new Uint8Array(16);crypto.getRandomValues(r);for(let o=0;o<16;o++)t+=vt.charAt(r[o]%ot);return t}function Bt(n){const{tenant_id:i,created_at_ts:e,updated_at_ts:t,expires_at_ts:r,state_data:o,auth_params:l,..._}=n,u=Pe({created_at_ts:e,updated_at_ts:t,expires_at_ts:r},["created_at_ts","updated_at_ts","expires_at_ts"]),c={};for(const[h,f]of Object.entries(_))f!=null&&(c[h]=f);const d=fr(c,["auth_strategy"]);return T({...d,authParams:typeof l=="string"&&l.length>0?JSON.parse(l):{},...u,state_data:x(o)})}function hs(n){return{async create(i,e){var l,_;const t=Date.now(),o={id:ps(),tenant_id:i,session_id:e.session_id,csrf_token:e.csrf_token,auth_params:JSON.stringify(e.authParams||{}),authorization_url:e.authorization_url?e.authorization_url.substring(0,1024):void 0,ip:e.ip,useragent:e.useragent,auth0Client:e.auth0Client,state:e.state||"pending",state_data:e.state_data?JSON.stringify(e.state_data):void 0,failure_reason:e.failure_reason,user_id:e.user_id,auth_connection:e.auth_connection,auth_strategy_strategy:(l=e.auth_strategy)==null?void 0:l.strategy,auth_strategy_strategy_type:(_=e.auth_strategy)==null?void 0:_.strategy_type,authenticated_at:e.authenticated_at,created_at_ts:t,updated_at_ts:t,expires_at_ts:e.expires_at?Q(e.expires_at):t+1e3*60*60*24};return await n.insert(L).values(o),Bt({...o,tenant_id:i})},async get(i,e){const t=i?g(a(L.tenant_id,i),a(L.id,e)):a(L.id,e),r=await n.select().from(L).where(t).get();return r?Bt(r):null},async update(i,e,t){var o,l,_;const r={updated_at_ts:Date.now()};if(t.session_id!==void 0&&(r.session_id=t.session_id),t.state!==void 0&&(r.state=t.state),t.state_data!==void 0&&(r.state_data=JSON.stringify(t.state_data)),t.failure_reason!==void 0&&(r.failure_reason=t.failure_reason),t.user_id!==void 0&&(r.user_id=t.user_id),t.auth_connection!==void 0&&(r.auth_connection=t.auth_connection),t.auth_strategy!==void 0&&(r.auth_strategy_strategy=(o=t.auth_strategy)==null?void 0:o.strategy,r.auth_strategy_strategy_type=(l=t.auth_strategy)==null?void 0:l.strategy_type),t.authenticated_at!==void 0&&(r.authenticated_at=t.authenticated_at),t.authorization_url!==void 0&&(r.authorization_url=(_=t.authorization_url)==null?void 0:_.substring(0,1024)),t.expires_at!==void 0&&(r.expires_at_ts=Q(t.expires_at)),t.authParams!==void 0){const u=await n.select({auth_params:L.auth_params}).from(L).where(g(a(L.tenant_id,i),a(L.id,e))).get(),c=u!=null&&u.auth_params&&typeof u.auth_params=="string"&&u.auth_params.length>0?JSON.parse(u.auth_params):{};r.auth_params=JSON.stringify({...c,...t.authParams})}return await n.update(L).set(r).where(g(a(L.tenant_id,i),a(L.id,e))),!0},async remove(i,e){return(await n.delete(L).where(g(a(L.tenant_id,i),a(L.id,e))).returning()).length>0}}}function at(n){const{tenant_id:i,isMobile:e,auth0_client:t,details:r,country_code:o,city_name:l,latitude:_,longitude:u,time_zone:c,continent_code:d,scope:h,...f}=n,y={...f,isMobile:!!e,auth0_client:x(t),details:x(r),scope:h?h.split(","):void 0};return o&&(y.location_info=T({country_code:o,city_name:l,latitude:_,longitude:u,time_zone:c,continent_code:d})),T(y)}function ms(n){return{async create(i,e){var o,l;const r={log_id:e.log_id||ae(),tenant_id:i,type:e.type,date:e.date||new Date().toISOString(),category:e.category,user_id:e.user_id,ip:e.ip,client_id:e.client_id,client_name:e.client_name,user_agent:(o=e.user_agent)==null?void 0:o.substring(0,256),description:(l=e.description)==null?void 0:l.substring(0,256),isMobile:e.isMobile?1:0,user_name:e.user_name,connection:e.connection,connection_id:e.connection_id,audience:e.audience,scope:Array.isArray(e.scope)?e.scope.join(","):e.scope,strategy:e.strategy,strategy_type:e.strategy_type,hostname:e.hostname,session_connection:e.session_connection};return e.auth0_client&&(r.auth0_client=JSON.stringify(e.auth0_client)),e.details&&(r.details=JSON.stringify(e.details).substring(0,8192)),e.location_info&&(r.country_code=e.location_info.country_code,r.city_name=e.location_info.city_name,r.latitude=e.location_info.latitude,r.longitude=e.location_info.longitude,r.time_zone=e.location_info.time_zone,r.continent_code=e.location_info.continent_code),await n.insert(q).values(r),at({...r,tenant_id:i})},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{};let u=n.select().from(q).where(a(q.tenant_id,i)).$dynamic();if(_){const f=ye(q,_,["user_id","ip","type","client_id"]);f&&(u=u.where(g(a(q.tenant_id,i),f)))}if(l!=null&&l.sort_by){const f=q[l.sort_by];f&&(u=u.orderBy(l.sort_order==="desc"?V(f):G(f)))}else u=u.orderBy(V(q.date));const d=(await u.offset(t*r).limit(r)).map(at);if(!o)return{logs:d};const[h]=await n.select({count:R()}).from(q).where(a(q.tenant_id,i));return{logs:d,start:t*r,limit:r,length:Number((h==null?void 0:h.count)??0)}},async get(i,e){const t=await n.select().from(q).where(g(a(q.tenant_id,i),a(q.log_id,e))).get();return t?at(t):null}}}const St="0123456789ABCDEFGHJKMNPQRSTVWXYZ",lt=St.length;function ys(){let e=Date.now(),t="";for(let o=10;o>0;o--)t=St.charAt(e%lt)+t,e=Math.floor(e/lt);const r=new Uint8Array(16);crypto.getRandomValues(r);for(let o=0;o<16;o++)t+=St.charAt(r[o]%lt);return t}function je(n){const{tenant_id:i,created_at_ts:e,updated_at_ts:t,credential_backed_up:r,confirmed:o,transports:l,..._}=n;return T({..._,confirmed:!!o,credential_backed_up:r!=null?!!r:void 0,transports:x(l),created_at:wt(e),updated_at:wt(t)})}function ws(n){return{async create(i,e){const t=Date.now(),o={id:e.id||ys(),tenant_id:i,user_id:e.user_id,type:e.type,phone_number:e.phone_number,totp_secret:e.totp_secret,credential_id:e.credential_id,public_key:e.public_key,sign_count:e.sign_count,credential_backed_up:e.credential_backed_up!=null?e.credential_backed_up?1:0:null,transports:e.transports?JSON.stringify(e.transports):null,friendly_name:e.friendly_name,confirmed:e.confirmed?1:0,created_at_ts:t,updated_at_ts:t};return await n.insert(K).values(o),je({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(K).where(g(a(K.tenant_id,i),a(K.id,e))).get();return t?je(t):null},async getByCredentialId(i,e){const t=await n.select().from(K).where(g(a(K.tenant_id,i),a(K.credential_id,e))).get();return t?je(t):null},async list(i,e){return(await n.select().from(K).where(g(a(K.tenant_id,i),a(K.user_id,e))).all()).map(je)},async update(i,e,t){const r={updated_at_ts:Date.now()};t.type!==void 0&&(r.type=t.type),t.phone_number!==void 0&&(r.phone_number=t.phone_number),t.totp_secret!==void 0&&(r.totp_secret=t.totp_secret),t.credential_id!==void 0&&(r.credential_id=t.credential_id),t.public_key!==void 0&&(r.public_key=t.public_key),t.sign_count!==void 0&&(r.sign_count=t.sign_count),t.credential_backed_up!==void 0&&(r.credential_backed_up=t.credential_backed_up?1:0),t.transports!==void 0&&(r.transports=JSON.stringify(t.transports)),t.friendly_name!==void 0&&(r.friendly_name=t.friendly_name),t.confirmed!==void 0&&(r.confirmed=t.confirmed?1:0),await n.update(K).set(r).where(g(a(K.tenant_id,i),a(K.id,e)));const o=await this.get(i,e);if(!o)throw new Error(`Authentication method ${e} not found after update`);return o},async remove(i,e){return(await n.delete(K).where(g(a(K.tenant_id,i),a(K.id,e))).returning()).length>0}}}function Ns(){const{customAlphabet:n}=require("nanoid");return`org_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function _t(n){const{tenant_id:i,branding:e,metadata:t,enabled_connections:r,token_quota:o,...l}=n;return T({...l,branding:x(e,{}),metadata:x(t,{}),enabled_connections:x(r,[]),token_quota:x(o,{})})}function vs(n){return{async create(i,e){var l,_;const t=new Date().toISOString(),o={id:e.id||Ns(),tenant_id:i,name:e.name,display_name:e.display_name,branding:JSON.stringify(e.branding||{}),metadata:JSON.stringify(e.metadata||{}),enabled_connections:JSON.stringify(e.enabled_connections||[]),token_quota:JSON.stringify(e.token_quota||{}),created_at:t,updated_at:t};try{await n.insert(E).values(o)}catch(u){throw(l=u==null?void 0:u.message)!=null&&l.includes("UNIQUE constraint failed")||(_=u==null?void 0:u.message)!=null&&_.includes("AlreadyExists")?new be(409,{message:"Organization already exists"}):u}return _t({...o,tenant_id:i})},async get(i,e){let t=await n.select().from(E).where(g(a(E.tenant_id,i),a(E.id,e))).get();return t||(t=await n.select().from(E).where(g(a(E.tenant_id,i),a(E.name,e))).get()),t?_t(t):null},async update(i,e,t){const r={updated_at:new Date().toISOString()};return t.name!==void 0&&(r.name=t.name),t.display_name!==void 0&&(r.display_name=t.display_name),t.branding!==void 0&&(r.branding=JSON.stringify(t.branding)),t.metadata!==void 0&&(r.metadata=JSON.stringify(t.metadata)),t.enabled_connections!==void 0&&(r.enabled_connections=JSON.stringify(t.enabled_connections)),t.token_quota!==void 0&&(r.token_quota=JSON.stringify(t.token_quota)),(await n.update(E).set(r).where(g(a(E.tenant_id,i),a(E.id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{};let u=n.select().from(E).where(a(E.tenant_id,i)).$dynamic();if(_&&(u=u.where(de(Ie(E.name,`%${_}%`),Ie(E.display_name,`%${_}%`)))),l!=null&&l.sort_by){const y=E[l.sort_by];y&&(u=u.orderBy(l.sort_order==="desc"?V(y):G(y)))}const d=(await u.offset(t*r).limit(r)).map(_t);if(!o)return{organizations:d};const h=[a(E.tenant_id,i)];_&&h.push(de(Ie(E.name,`%${_}%`),Ie(E.display_name,`%${_}%`)));const[f]=await n.select({count:R()}).from(E).where(g(...h));return{organizations:d,start:t*r,limit:r,length:Number((f==null?void 0:f.count)??0)}},async remove(i,e){return(await n.delete(E).where(g(a(E.tenant_id,i),a(E.id,e))).returning()).length>0}}}function ut(n){const{tenant_id:i,is_current:e,...t}=n;return{...t,is_current:!!e}}function Ss(n){return{async create(i,e){const t=new Date().toISOString(),r=e.id||ae();e.is_current!==!1&&await n.update(A).set({is_current:0}).where(g(a(A.tenant_id,i),a(A.user_id,e.user_id)));const o={id:r,tenant_id:i,user_id:e.user_id,password:e.password,algorithm:e.algorithm||"bcrypt",is_current:e.is_current!==!1?1:0,created_at:t,updated_at:t};return await n.insert(A).values(o),ut({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(A).where(g(a(A.tenant_id,i),a(A.user_id,e),a(A.is_current,1))).get();return t?ut(t):null},async list(i,e,t){let r=n.select().from(A).where(g(a(A.tenant_id,i),a(A.user_id,e))).orderBy(V(A.created_at)).$dynamic();return t&&(r=r.limit(t)),(await r).map(ut)},async update(i,e){const t={updated_at:new Date().toISOString()};return e.password!==void 0&&(t.password=e.password),e.algorithm!==void 0&&(t.algorithm=e.algorithm),e.is_current!==void 0&&(t.is_current=e.is_current?1:0),e.id?await n.update(A).set(t).where(g(a(A.tenant_id,i),a(A.id,e.id))):await n.update(A).set(t).where(g(a(A.tenant_id,i),a(A.user_id,e.user_id),a(A.is_current,1))),!0}}}function xs(n){return{async get(i){const e=await n.select().from(Ee).where(a(Ee.tenant_id,i)).get();return e?{universal_login_experience:e.universal_login_experience,identifier_first:!!e.identifier_first,password_first:!!e.password_first,webauthn_platform_first_factor:!!e.webauthn_platform_first_factor}:{universal_login_experience:"new",identifier_first:!0,password_first:!1,webauthn_platform_first_factor:!1}},async set(i,e){await n.insert(Ee).values({tenant_id:i,universal_login_experience:e.universal_login_experience,identifier_first:e.identifier_first,password_first:e.password_first,webauthn_platform_first_factor:e.webauthn_platform_first_factor}).onConflictDoUpdate({target:Ee.tenant_id,set:{universal_login_experience:e.universal_login_experience,identifier_first:e.identifier_first,password_first:e.password_first,webauthn_platform_first_factor:e.webauthn_platform_first_factor}})}}}function dt(n){const{tenant_id:i,created_at_ts:e,expires_at_ts:t,idle_expires_at_ts:r,last_exchanged_at_ts:o,revoked_at_ts:l,device:_,resource_servers:u,rotating:c,...d}=n,h=Pe({created_at_ts:e,expires_at_ts:t,idle_expires_at_ts:r,last_exchanged_at_ts:o,revoked_at_ts:l},["created_at_ts"],["expires_at_ts","idle_expires_at_ts","last_exchanged_at_ts","revoked_at_ts"]);return T({...d,...h,rotating:!!c,device:x(_,{}),resource_servers:x(u,[])})}function $t(n,i){return Math.max(n??0,i??0)}function bs(n){return{async create(i,e){const t=Date.now(),r={id:e.id||ae(),tenant_id:i,client_id:e.client_id,login_id:e.login_id,user_id:e.user_id,device:JSON.stringify(e.device||{}),resource_servers:JSON.stringify(e.resource_servers||[]),rotating:e.rotating??!1,created_at_ts:t,expires_at_ts:Q(e.expires_at),idle_expires_at_ts:Q(e.idle_expires_at),last_exchanged_at_ts:Q(e.last_exchanged_at)};await n.run(w`BEGIN`);try{await n.insert(z).values(r);const o=$t(r.expires_at_ts,r.idle_expires_at_ts);o>0&&r.login_id&&await n.update(L).set({expires_at_ts:o,updated_at_ts:t}).where(g(a(L.tenant_id,i),a(L.id,r.login_id),we(L.expires_at_ts,o))),await n.run(w`COMMIT`)}catch(o){throw await n.run(w`ROLLBACK`),o}return dt({...r,tenant_id:i})},async get(i,e){const t=await n.select().from(z).where(g(a(z.tenant_id,i),a(z.id,e))).get();return t?dt(t):null},async update(i,e,t){const r={};t.device!==void 0&&(r.device=JSON.stringify(t.device)),t.resource_servers!==void 0&&(r.resource_servers=JSON.stringify(t.resource_servers)),t.rotating!==void 0&&(r.rotating=t.rotating),t.expires_at!==void 0&&(r.expires_at_ts=Q(t.expires_at)),t.idle_expires_at!==void 0&&(r.idle_expires_at_ts=Q(t.idle_expires_at)),t.last_exchanged_at!==void 0&&(r.last_exchanged_at_ts=Q(t.last_exchanged_at)),t.revoked_at!==void 0&&(r.revoked_at_ts=Q(t.revoked_at));const o=r.expires_at_ts!==void 0||r.idle_expires_at_ts!==void 0;await n.run(w`BEGIN`);try{const _=(await n.update(z).set(r).where(g(a(z.tenant_id,i),a(z.id,e))).returning()).length>0;if(_&&o){const u=await n.select({login_id:z.login_id,expires_at_ts:z.expires_at_ts,idle_expires_at_ts:z.idle_expires_at_ts}).from(z).where(g(a(z.tenant_id,i),a(z.id,e))).get();if(u!=null&&u.login_id){const c=$t(u.expires_at_ts,u.idle_expires_at_ts);c>0&&await n.update(L).set({expires_at_ts:c,updated_at_ts:Date.now()}).where(g(a(L.tenant_id,i),a(L.id,u.login_id),we(L.expires_at_ts,c)))}}return await n.run(w`COMMIT`),_}catch(l){throw await n.run(w`ROLLBACK`),l}},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{};let u=n.select().from(z).where(a(z.tenant_id,i)).$dynamic();if(_){const f=ye(z,_,["user_id"]);f&&(u=u.where(g(a(z.tenant_id,i),f)))}if(l!=null&&l.sort_by){const f=z[l.sort_by];f&&(u=u.orderBy(l.sort_order==="desc"?V(f):G(f)))}const d=(await u.offset(t*r).limit(r)).map(dt);if(!o)return{refresh_tokens:d};const[h]=await n.select({count:R()}).from(z).where(a(z.tenant_id,i));return{refresh_tokens:d,start:t*r,limit:r,length:Number((h==null?void 0:h.count)??0)}},async remove(i,e){return(await n.delete(z).where(g(a(z.tenant_id,i),a(z.id,e))).returning()).length>0},async revokeByLoginSession(i,e,t){return(await n.update(z).set({revoked_at_ts:Q(t)}).where(g(a(z.tenant_id,i),a(z.login_id,e),me(z.revoked_at_ts))).returning()).length}}}function Ds(){const{customAlphabet:n}=require("nanoid");return`api_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const xt=["skip_consent_for_verifiable_first_party_clients","allow_offline_access","is_system"],Qt=new Set(["id","tenant_id","identifier","name","scopes","signing_alg","signing_secret","token_lifetime","token_lifetime_for_web","skip_consent_for_verifiable_first_party_clients","allow_offline_access","verification_key","options","is_system","metadata","created_at","updated_at"]);function ct(n){const{tenant_id:i,verification_key:e,scopes:t,options:r,metadata:o,...l}=n,_={...l};_.scopes=x(t,[]),_.options=x(r,{}),_.metadata=x(o),e!==void 0&&(_.verificationKey=e);for(const u of xt)l[u]!==void 0&&l[u]!==null&&(_[u]=!!l[u]);return T(_)}function Os(n){return{async create(i,e){const t=new Date().toISOString(),o={id:e.id||Ds(),tenant_id:i,identifier:e.identifier,name:e.name,signing_alg:e.signing_alg,signing_secret:e.signing_secret,token_lifetime:e.token_lifetime,token_lifetime_for_web:e.token_lifetime_for_web,scopes:JSON.stringify(e.scopes||[]),options:JSON.stringify(e.options||{}),metadata:e.metadata?JSON.stringify(e.metadata):void 0,verification_key:e.verificationKey||e.verification_key,created_at:t,updated_at:t};for(const l of xt)e[l]!==void 0&&(o[l]=e[l]?1:0);return o.is_system===void 0&&(o.is_system=0),await n.insert(C).values(o),ct({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(C).where(g(a(C.tenant_id,i),a(C.id,e))).get();return t?ct(t):null},async update(i,e,t){const r={updated_at:new Date().toISOString()};t.name!==void 0&&(r.name=t.name),t.identifier!==void 0&&(r.identifier=t.identifier),t.signing_alg!==void 0&&(r.signing_alg=t.signing_alg),t.signing_secret!==void 0&&(r.signing_secret=t.signing_secret),t.token_lifetime!==void 0&&(r.token_lifetime=t.token_lifetime),t.token_lifetime_for_web!==void 0&&(r.token_lifetime_for_web=t.token_lifetime_for_web),t.scopes!==void 0&&(r.scopes=JSON.stringify(t.scopes)),t.options!==void 0&&(r.options=w`json_patch(COALESCE(${C.options}, '{}'), ${JSON.stringify(t.options)})`),t.metadata!==void 0&&(r.metadata=JSON.stringify(t.metadata)),t.verificationKey!==void 0&&(r.verification_key=t.verificationKey);for(const l of xt)t[l]!==void 0&&(r[l]=t[l]?1:0);return(await n.update(C).set(r).where(g(a(C.tenant_id,i),a(C.id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{},u=Math.max(0,Math.floor(Number(t)||0)),c=Math.min(Math.max(1,Math.floor(Number(r)||50)),500),d=[a(C.tenant_id,i)];if(_){const B=_.match(/^([^:]+):(.+)$/);if(B){const[,W,H]=B,ke=W==null?void 0:W.startsWith("-"),qe=ke?W==null?void 0:W.substring(1):W;if(qe&&Qt.has(qe)&&!ke){const yr=C[qe];d.push(Ie(yr,`%${H}%`))}}}let h=n.select().from(C).where(g(...d)).$dynamic();if(l!=null&&l.sort_by&&Qt.has(l.sort_by)){const B=C[l.sort_by];h=h.orderBy(l.sort_order==="desc"?V(B):G(B))}const y=(await h.offset(u*c).limit(c)).map(ct);if(!o)return{resource_servers:y};const[N]=await n.select({count:R()}).from(C).where(g(...d));return{resource_servers:y,start:u*c,limit:c,length:Number((N==null?void 0:N.count)??0)}},async remove(i,e){return(await n.delete(C).where(g(a(C.tenant_id,i),a(C.id,e))).returning()).length>0}}}function ks(n){return{async assign(i,e,t){const r=new Date().toISOString();return await n.insert(le).values(t.map(o=>({tenant_id:i,role_id:e,resource_server_identifier:o.resource_server_identifier,permission_name:o.permission_name,created_at:r}))).onConflictDoNothing(),!0},async list(i,e,t){const r=await n.select({resource_server_identifier:le.resource_server_identifier,permission_name:le.permission_name,created_at:le.created_at}).from(le).where(g(a(le.tenant_id,i),a(le.role_id,e))).all(),o=[...new Set(r.map(_=>_.resource_server_identifier))],l=new Map;if(o.length>0){const _=await n.select({identifier:C.identifier,name:C.name}).from(C).where(g(a(C.tenant_id,i),Ne(C.identifier,o))).all();for(const u of _)l.set(u.identifier,u.name)}return r.map(_=>({..._,resource_server_name:l.get(_.resource_server_identifier)||_.resource_server_identifier}))},async remove(i,e,t){const r=t.map(l=>g(a(le.resource_server_identifier,l.resource_server_identifier),a(le.permission_name,l.permission_name)));return(await n.delete(le).where(g(a(le.tenant_id,i),a(le.role_id,e),de(...r))).returning()).length>0}}}function Is(n){return{async create(i,e,t,r){var o,l;try{await n.insert(_e).values({tenant_id:i,user_id:e,resource_server_identifier:t.resource_server_identifier,permission_name:t.permission_name,organization_id:r||"",created_at:new Date().toISOString()})}catch(_){if((o=_==null?void 0:_.message)!=null&&o.includes("UNIQUE constraint")||(l=_==null?void 0:_.message)!=null&&l.includes("SQLITE_CONSTRAINT_PRIMARYKEY"))return!0;throw _}return!0},async list(i,e,t,r){let o=[a(_e.tenant_id,i),a(_e.user_id,e)];r&&o.push(a(_e.organization_id,r));const l=await n.select().from(_e).where(g(...o)).all();return await Promise.all(l.map(async u=>{const c=await n.select({name:C.name}).from(C).where(g(a(C.tenant_id,i),a(C.identifier,u.resource_server_identifier))).get();return{resource_server_identifier:u.resource_server_identifier,permission_name:u.permission_name,resource_server_name:(c==null?void 0:c.name)||u.resource_server_identifier,organization_id:u.organization_id===""?void 0:u.organization_id}}))},async remove(i,e,t,r){return(await n.delete(_e).where(g(a(_e.tenant_id,i),a(_e.user_id,e),a(_e.resource_server_identifier,t.resource_server_identifier),a(_e.permission_name,t.permission_name),a(_e.organization_id,r||""))).returning()).length>0}}}function gt(n){const{tenant_id:i,is_system:e,metadata:t,...r}=n;return T({...r,is_system:e?!0:void 0,metadata:x(t)})}function zs(n){return{async create(i,e){const t=new Date().toISOString(),o={id:e.id||ae(),tenant_id:i,name:e.name,description:e.description,is_system:e.is_system?1:0,metadata:e.metadata?JSON.stringify(e.metadata):void 0,created_at:t,updated_at:t};return await n.insert(U).values(o),gt({...o,tenant_id:i})},async get(i,e){const t=await n.select().from(U).where(g(a(U.tenant_id,i),a(U.id,e))).get();return t?gt(t):null},async update(i,e,t){const r={updated_at:new Date().toISOString()};return t.name!==void 0&&(r.name=t.name),t.description!==void 0&&(r.description=t.description),t.is_system!==void 0&&(r.is_system=t.is_system?1:0),t.metadata!==void 0&&(r.metadata=JSON.stringify(t.metadata)),(await n.update(U).set(r).where(g(a(U.tenant_id,i),a(U.id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{},u=_?ye(U,_,["name"]):void 0,c=u?g(a(U.tenant_id,i),u):a(U.tenant_id,i);let d=n.select().from(U).where(c).$dynamic();if(l!=null&&l.sort_by){const N=U[l.sort_by];N&&(d=d.orderBy(l.sort_order==="desc"?V(N):G(N)))}const f=(await d.offset(t*r).limit(r)).map(gt);if(!o)return{roles:f};const[y]=await n.select({count:R()}).from(U).where(c);return{roles:f,start:t*r,limit:r,length:Number((y==null?void 0:y.count)??0)}},async remove(i,e){return(await n.delete(U).where(g(a(U.tenant_id,i),a(U.id,e))).returning()).length>0}}}const Ts=["created_at_ts","updated_at_ts"],qs=["expires_at_ts","idle_expires_at_ts","authenticated_at_ts","last_interaction_at_ts","used_at_ts","revoked_at_ts"];function ft(n){const{tenant_id:i,created_at_ts:e,updated_at_ts:t,expires_at_ts:r,idle_expires_at_ts:o,authenticated_at_ts:l,last_interaction_at_ts:_,used_at_ts:u,revoked_at_ts:c,device:d,clients:h,...f}=n,y=Pe({created_at_ts:e,updated_at_ts:t,expires_at_ts:r,idle_expires_at_ts:o,authenticated_at_ts:l,last_interaction_at_ts:_,used_at_ts:u,revoked_at_ts:c},[...Ts],[...qs]);return T({...f,...y,device:x(d,{}),clients:x(h,[])})}function Ls(n){return{async create(i,e){const t=Date.now(),r={id:e.id||ae(),tenant_id:i,user_id:e.user_id,login_session_id:e.login_session_id,device:JSON.stringify(e.device||{}),clients:JSON.stringify(e.clients||[]),created_at_ts:t,updated_at_ts:t,expires_at_ts:Q(e.expires_at),idle_expires_at_ts:Q(e.idle_expires_at),authenticated_at_ts:e.authenticated_at?Q(e.authenticated_at):t,last_interaction_at_ts:e.last_interaction_at?Q(e.last_interaction_at):t,used_at_ts:Q(e.used_at),revoked_at_ts:Q(e.revoked_at)};return await n.insert($).values(r),ft({...r,tenant_id:i})},async get(i,e){const t=await n.select().from($).where(g(a($.tenant_id,i),a($.id,e))).get();return t?ft(t):null},async update(i,e,t){const r={updated_at_ts:Date.now()};return t.user_id!==void 0&&(r.user_id=t.user_id),t.login_session_id!==void 0&&(r.login_session_id=t.login_session_id),t.device!==void 0&&(r.device=JSON.stringify(t.device)),t.clients!==void 0&&(r.clients=JSON.stringify(t.clients)),t.expires_at!==void 0&&(r.expires_at_ts=Q(t.expires_at)),t.idle_expires_at!==void 0&&(r.idle_expires_at_ts=Q(t.idle_expires_at)),t.authenticated_at!==void 0&&(r.authenticated_at_ts=Q(t.authenticated_at)),t.last_interaction_at!==void 0&&(r.last_interaction_at_ts=Q(t.last_interaction_at)),t.used_at!==void 0&&(r.used_at_ts=Q(t.used_at)),t.revoked_at!==void 0&&(r.revoked_at_ts=Q(t.revoked_at)),(await n.update($).set(r).where(g(a($.tenant_id,i),a($.id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,sort:l,q:_}=e||{},u=_?ye($,_,["user_id"]):void 0,c=u?g(a($.tenant_id,i),u):a($.tenant_id,i);let d=n.select().from($).where(c).$dynamic();if(l!=null&&l.sort_by){const N=$[l.sort_by];N&&(d=d.orderBy(l.sort_order==="desc"?V(N):G(N)))}const f=(await d.offset(t*r).limit(r)).map(ft);if(!o)return{sessions:f};const[y]=await n.select({count:R()}).from($).where(c);return{sessions:f,start:t*r,limit:r,length:Number((y==null?void 0:y.count)??0)}},async remove(i,e){return(await n.delete($).where(g(a($.tenant_id,i),a($.id,e))).returning()).length>0}}}const hr=["session_cookie","enabled_locales","error_page","flags","sandbox_versions_available","change_password","guardian_mfa_page","sessions","oidc_logout","device_flow","default_token_quota","allowed_logout_urls","acr_values_supported","mtls","mfa"],mr=["allow_organization_name_in_authentication_api","customize_mfa_in_postlogin_action","pushed_authorization_requests_supported","authorization_response_iss_parameter_supported"];function Jt(n){const i={...n};for(const e of hr)typeof i[e]=="string"&&(i[e]=x(i[e]));for(const e of mr)i[e]!==void 0&&i[e]!==null&&(i[e]=i[e]===1);return T(i)}function Pt(n){const i={...n};Fr(n,hr,i);for(const e of mr)n[e]!==void 0&&(i[e]=n[e]?1:0);return gr(i)}function Es(n){return{async create(i){var r,o;const e={id:i.id||ae(),created_at:new Date().toISOString(),updated_at:new Date().toISOString(),...i},t=Pt(e);try{await n.insert(D).values(t)}catch(l){throw(r=l==null?void 0:l.message)!=null&&r.includes("UNIQUE constraint failed")||(o=l==null?void 0:l.message)!=null&&o.includes("duplicate key")||(l==null?void 0:l.code)==="SQLITE_CONSTRAINT"?new be(409,{message:`Tenant with ID '${e.id}' already exists`}):l}return e},async get(i){const e=await n.select().from(D).where(a(D.id,i)).get();return e?Jt(e):null},async list(i){const{page:e=0,per_page:t=50,include_totals:r=!1,sort:o,q:l}=i||{};let _=n.select().from(D).$dynamic();if(l){const h=ye(D,l,["friendly_name"]);h&&(_=_.where(h))}if(o!=null&&o.sort_by){const h=D[o.sort_by];h&&(_=_.orderBy(o.sort_order==="desc"?V(h):G(h)))}const c=(await _.offset(e*t).limit(t)).map(Jt);if(!r)return{tenants:c};const[d]=await n.select({count:R()}).from(D);return{tenants:c,start:e*t,limit:t,length:Number((d==null?void 0:d.count)??0)}},async update(i,e){const t=Pt({...e,id:i,updated_at:new Date().toISOString()});await n.update(D).set(t).where(a(D.id,i))},async remove(i){return(await n.delete(D).where(a(D.id,i)).returning()).length>0}}}const Cs=["colors","borders","fonts","page_background","widget"];function Ft(n){const{tenant_id:i,...e}=n,t=fr(e,Cs);return t.borders&&(t.borders.show_widget_shadow=!!t.borders.show_widget_shadow),t.fonts&&(t.fonts.links_bold=!!t.fonts.links_bold,t.fonts.subtitle_bold=!!t.fonts.subtitle_bold,t.fonts.title_bold=!!t.fonts.title_bold),T(t)}function As(n){return{async create(i,e,t){const r=new Date().toISOString(),o=t||ae(),_={...yt(e),tenant_id:i,themeId:o,created_at:r,updated_at:r};return await n.insert(fe).values(_),Ft({..._,tenant_id:i})},async get(i,e){const t=await n.select().from(fe).where(g(a(fe.tenant_id,i),a(fe.themeId,e))).get();return t?Ft(t):null},async update(i,e,t){const r=yt(t);return r.updated_at=new Date().toISOString(),await n.update(fe).set(r).where(g(a(fe.tenant_id,i),a(fe.themeId,e))),!0},async remove(i,e){return(await n.delete(fe).where(g(a(fe.tenant_id,i),a(fe.themeId,e))).returning()).length>0}}}function Bs(n){return{async get(i){const e=await n.select({body:ve.body}).from(ve).where(a(ve.tenant_id,i)).get();return e?{body:e.body}:null},async set(i,e){const t=Date.now();await n.insert(ve).values({tenant_id:i,body:e.body,created_at_ts:t,updated_at_ts:t}).onConflictDoUpdate({target:ve.tenant_id,set:{body:e.body,updated_at_ts:t}})},async delete(i){await n.delete(ve).where(a(ve.tenant_id,i))}}}function Ut(n,i){const e={connection:n.connection,provider:n.provider,user_id:n.user_id,isSocial:!!n.is_social};return i?e.isPrimary=!0:e.profileData={email:n.email,email_verified:!!n.email_verified,...typeof n.profileData=="string"?x(n.profileData,{}):{}},e}function pt(n,i=[]){const{tenant_id:e,app_metadata:t,user_metadata:r,address:o,email_verified:l,phone_verified:_,is_social:u,linked_to:c,profileData:d,...h}=n,f=Ut(n,!0),y=i.map(N=>Ut(N,!1));return T({...h,email:n.email||"",email_verified:!!l,phone_verified:_!=null?!!_:void 0,is_social:!!u,app_metadata:x(t,{}),user_metadata:x(r,{}),address:x(o),identities:[f,...y]})}function $s(n){const i=async(e,t)=>{var _,u;const r=new Date().toISOString(),o={user_id:t.user_id,tenant_id:e,email:t.email,given_name:t.given_name,family_name:t.family_name,nickname:t.nickname,name:t.name,picture:t.picture,tags:t.tags,phone_number:t.phone_number,phone_verified:t.phone_verified??!1,username:t.username,linked_to:t.linked_to,last_ip:t.last_ip,login_count:t.login_count??0,last_login:t.last_login,provider:t.provider,connection:t.connection,email_verified:t.email_verified??!1,is_social:t.is_social??!1,app_metadata:JSON.stringify(t.app_metadata||{}),user_metadata:JSON.stringify(t.user_metadata||{}),address:t.address?JSON.stringify(t.address):void 0,profileData:t.profileData?JSON.stringify(t.profileData):void 0,locale:t.locale,middle_name:t.middle_name,preferred_username:t.preferred_username,profile:t.profile,website:t.website,gender:t.gender,birthdate:t.birthdate,zoneinfo:t.zoneinfo,created_at:t.created_at||r,updated_at:t.updated_at||r},l=t.password?ae():void 0;try{if(t.password&&l){await n.run(w`BEGIN`);try{await n.insert(k).values(o),await n.insert(A).values({id:l,tenant_id:e,user_id:t.user_id,password:t.password.hash||t.password,algorithm:t.password.algorithm||"bcrypt",is_current:1,created_at:r,updated_at:r}),await n.run(w`COMMIT`)}catch(c){throw await n.run(w`ROLLBACK`),c}}else await n.insert(k).values(o)}catch(c){throw(_=c==null?void 0:c.message)!=null&&_.includes("UNIQUE constraint")||(u=c==null?void 0:c.message)!=null&&u.includes("AlreadyExists")?new be(409,{message:"User already exists"}):(console.error("User upsert failed:",c==null?void 0:c.code,c==null?void 0:c.message),new be(500,{message:"Internal server error"}))}return pt(o)};return{create:i,rawCreate:i,async get(e,t){const r=await n.select().from(k).where(g(a(k.tenant_id,e),a(k.user_id,t))).get();if(!r)return null;const o=await n.select().from(k).where(g(a(k.tenant_id,e),a(k.linked_to,t))).all();return pt(r,o)},async update(e,t,r){const o={updated_at:new Date().toISOString()},l=["email","given_name","family_name","nickname","name","picture","tags","phone_number","username","linked_to","last_ip","login_count","last_login","provider","connection","locale","middle_name","preferred_username","profile","website","gender","birthdate","zoneinfo"];for(const u of l)r[u]!==void 0&&(o[u]=r[u]);return r.email_verified!==void 0&&(o.email_verified=r.email_verified),r.phone_verified!==void 0&&(o.phone_verified=r.phone_verified),r.is_social!==void 0&&(o.is_social=r.is_social),r.app_metadata!==void 0&&(o.app_metadata=JSON.stringify(r.app_metadata)),r.user_metadata!==void 0&&(o.user_metadata=JSON.stringify(r.user_metadata)),r.address!==void 0&&(o.address=JSON.stringify(r.address)),r.profileData!==void 0&&(o.profileData=JSON.stringify(r.profileData)),(await n.update(k).set(o).where(g(a(k.tenant_id,e),a(k.user_id,t))).returning()).length>0},async list(e,t){const{page:r=0,per_page:o=50,include_totals:l=!1,sort:_,q:u}=t||{},c=[a(k.tenant_id,e),me(k.linked_to)];if(u){const H=ye(k,u,["email","name","nickname","username"]);H&&c.push(H)}const d=g(...c);let h=n.select().from(k).where(d).$dynamic();if(_!=null&&_.sort_by){const H=k[_.sort_by];H&&(h=h.orderBy(_.sort_order==="desc"?V(H):G(H)))}const f=await h.offset(r*o).limit(o),y=f.map(H=>H.user_id);let N=[];y.length>0&&(N=await n.select().from(k).where(g(a(k.tenant_id,e),Ne(k.linked_to,y))));const B=f.map(H=>{const ke=N.filter(qe=>qe.linked_to===H.user_id);return pt(H,ke)});if(!l)return{users:B};const[W]=await n.select({count:R()}).from(k).where(d);return{users:B,start:r*o,limit:o,length:Number((W==null?void 0:W.count)??0)}},async remove(e,t){await n.run(w`BEGIN`);try{const r=await n.select({user_id:k.user_id}).from(k).where(g(a(k.tenant_id,e),a(k.linked_to,t))),o=[t,...r.map(_=>_.user_id)];await n.delete(K).where(g(a(K.tenant_id,e),Ne(K.user_id,o))),await n.delete(A).where(g(a(A.tenant_id,e),Ne(A.user_id,o))),await n.delete(k).where(g(a(k.tenant_id,e),a(k.linked_to,t)));const l=await n.delete(k).where(g(a(k.tenant_id,e),a(k.user_id,t))).returning();return await n.run(w`COMMIT`),l.length>0}catch(r){throw await n.run(w`ROLLBACK`),r}},async unlink(e,t,r,o){const l=`${r}|${o}`;return(await n.update(k).set({linked_to:null}).where(g(a(k.tenant_id,e),a(k.user_id,l),a(k.linked_to,t))).returning()).length>0}}}function Qs(n){return{async create(i,e,t,r){var o,l;try{await n.insert(ue).values({tenant_id:i,user_id:e,role_id:t,organization_id:r||"",created_at:new Date().toISOString()})}catch(_){if((o=_==null?void 0:_.message)!=null&&o.includes("UNIQUE constraint")||(l=_==null?void 0:_.message)!=null&&l.includes("SQLITE_CONSTRAINT_PRIMARYKEY"))return!0;throw _}return!0},async list(i,e,t,r){let o=[a(ue.tenant_id,i),a(ue.user_id,e)];r&&o.push(a(ue.organization_id,r));const l=await n.select({role_id:ue.role_id}).from(ue).where(g(...o)).all();return l.length===0?[]:(await Promise.all(l.map(async u=>{const c=await n.select().from(U).where(g(a(U.tenant_id,i),a(U.id,u.role_id))).get();if(!c)return null;const{tenant_id:d,is_system:h,metadata:f,...y}=c;return T({...y,is_system:h?!0:void 0,metadata:x(f)})}))).filter(Boolean)},async remove(i,e,t,r){return(await n.delete(ue).where(g(a(ue.tenant_id,i),a(ue.user_id,e),a(ue.role_id,t),a(ue.organization_id,r||""))).returning()).length>0}}}function Js(n){return{async create(i,e){var u,c;const t=new Date().toISOString(),o={id:e.id||ae(),tenant_id:i,user_id:e.user_id,organization_id:e.organization_id,created_at:t,updated_at:t};try{await n.insert(P).values(o)}catch(d){throw(u=d==null?void 0:d.message)!=null&&u.includes("UNIQUE constraint")||(c=d==null?void 0:d.message)!=null&&c.includes("duplicate key")?new be(409,{message:"User organization already exists"}):d}const{tenant_id:l,..._}=o;return _},async get(i,e){const t=await n.select().from(P).where(g(a(P.tenant_id,i),a(P.id,e))).get();if(!t)return null;const{tenant_id:r,...o}=t;return o},async update(i,e,t){const r={updated_at:new Date().toISOString()};return t.user_id!==void 0&&(r.user_id=t.user_id),t.organization_id!==void 0&&(r.organization_id=t.organization_id),(await n.update(P).set(r).where(g(a(P.tenant_id,i),a(P.id,e))).returning()).length>0},async list(i,e){const{page:t=0,per_page:r=50,include_totals:o=!1,q:l}=e||{},_=a(P.tenant_id,i);let u=_;if(l){const f=ye(P,l,["user_id","organization_id"]);f&&(u=g(_,f))}const d=(await n.select().from(P).where(u).offset(t*r).limit(r)).map(f=>{const{tenant_id:y,...N}=f;return N});if(!o)return{userOrganizations:d};const[h]=await n.select({count:R()}).from(P).where(u);return{userOrganizations:d,start:t*r,limit:r,length:Number((h==null?void 0:h.count)??0)}},async listUserOrganizations(i,e,t){const{page:r=0,per_page:o=50,include_totals:l=!1}=t||{},_=await n.select().from(P).where(g(a(P.tenant_id,i),a(P.user_id,e))).offset(r*o).limit(o).all(),c=(await Promise.all(_.map(async h=>{const f=await n.select().from(E).where(g(a(E.tenant_id,i),a(E.id,h.organization_id))).get();if(!f)return null;const{tenant_id:y,branding:N,metadata:B,enabled_connections:W,token_quota:H,...ke}=f;return T({...ke,branding:x(N,{}),metadata:x(B,{}),enabled_connections:x(W,[]),token_quota:x(H,{})})}))).filter(Boolean);if(!l)return{organizations:c};const[d]=await n.select({count:R()}).from(P).where(g(a(P.tenant_id,i),a(P.user_id,e)));return{organizations:c,start:r*o,limit:o,length:Number((d==null?void 0:d.count)??0)}},async remove(i,e){return(await n.delete(P).where(g(a(P.tenant_id,i),a(P.id,e))).returning()).length>0}}}const Kt=["s","seacft","seccft","sepft","sertft","ssa"],Ps=["pwd_leak","signup_pwd_leak","reset_pwd_leak"];function Fs(n){return{async getDaily(i,e){const t=new Date,r=(e==null?void 0:e.from)||new Date(t.getTime()-30*24*60*60*1e3).toISOString().split("T")[0],o=(e==null?void 0:e.to)||t.toISOString().split("T")[0];return(await n.select({date:w`substr(${q.date}, 1, 10)`.as("date"),logins:w`SUM(CASE WHEN ${q.type} IN (${w.join(Kt.map(_=>w`${_}`),w`, `)}) THEN 1 ELSE 0 END)`.as("logins"),signups:w`SUM(CASE WHEN ${q.type} = 'ss' THEN 1 ELSE 0 END)`.as("signups"),leaked_passwords:w`SUM(CASE WHEN ${q.type} IN (${w.join(Ps.map(_=>w`${_}`),w`, `)}) THEN 1 ELSE 0 END)`.as("leaked_passwords")}).from(q).where(g(a(q.tenant_id,i),He(q.date,r),Oe(q.date,`${o}T23:59:59.999Z`))).groupBy(w`substr(${q.date}, 1, 10)`).orderBy(w`substr(${q.date}, 1, 10)`).all()).map(_=>({date:_.date,logins:Number(_.logins)||0,signups:Number(_.signups)||0,leaked_passwords:Number(_.leaked_passwords)||0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}))},async getActiveUsers(i){const e=new Date(Date.now()-2592e6).toISOString(),[t]=await n.select({count:w`COUNT(DISTINCT ${q.user_id})`.as("count")}).from(q).where(g(a(q.tenant_id,i),He(q.date,e),w`${q.type} IN (${w.join(Kt.map(r=>w`${r}`),w`, `)})`));return Number(t==null?void 0:t.count)||0}}}function jt(n){return{...n,payload:x(n.payload,{})}}function Us(n){return{async create(i,e){const t=ae(),r=new Date().toISOString();return await n.insert(b).values({id:t,tenant_id:i,event_type:e.event_type,log_type:e.log_type,aggregate_type:e.aggregate_type,aggregate_id:e.aggregate_id,payload:JSON.stringify({...e,id:t}),created_at:r,processed_at:null,retry_count:0,next_retry_at:null,error:null,claimed_by:null,claim_expires_at:null}),t},async getByIds(i){return i.length===0?[]:(await n.select().from(b).where(Ne(b.id,i)).all()).map(jt)},async getUnprocessed(i){const e=new Date().toISOString();return(await n.select().from(b).where(g(me(b.processed_at),de(me(b.next_retry_at),Oe(b.next_retry_at,e)),de(me(b.claimed_by),Oe(b.claim_expires_at,e)))).orderBy(b.created_at,b.id).limit(i).all()).map(jt)},async claimEvents(i,e,t){if(i.length===0)return[];const r=new Date().toISOString(),o=new Date(Date.now()+t).toISOString();return await n.update(b).set({claimed_by:e,claim_expires_at:o}).where(g(Ne(b.id,i),me(b.processed_at),de(me(b.claimed_by),Oe(b.claim_expires_at,r)))),(await n.select({id:b.id}).from(b).where(g(Ne(b.id,i),a(b.claimed_by,e))).all()).map(_=>_.id)},async markProcessed(i){i.length!==0&&await n.update(b).set({processed_at:new Date().toISOString()}).where(Ne(b.id,i))},async markRetry(i,e,t){await n.update(b).set({error:e,next_retry_at:t,retry_count:w`${b.retry_count} + 1`,claimed_by:null,claim_expires_at:null}).where(a(b.id,i))},async cleanup(i){return(await n.delete(b).where(g(w`${b.processed_at} IS NOT NULL`,Oe(b.processed_at,i))).returning()).length},async deadLetter(i,e){const t=new Date().toISOString();await n.update(b).set({processed_at:t,dead_lettered_at:t,final_error:e}).where(a(b.id,i))},async listFailed(i,e={}){const{page:t=0,per_page:r=50,include_totals:o=!1}=e,_=(await n.select().from(b).where(g(a(b.tenant_id,i),Me(b.dead_lettered_at))).orderBy(V(b.dead_lettered_at),G(b.id)).offset(t*r).limit(r).all()).map(c=>({...x(c.payload,{}),id:c.id,created_at:c.created_at,processed_at:c.processed_at,retry_count:c.retry_count,next_retry_at:c.next_retry_at,error:c.error,dead_lettered_at:c.dead_lettered_at,final_error:c.final_error}));let u=_.length;if(o){const[c]=await n.select({total:R()}).from(b).where(g(a(b.tenant_id,i),Me(b.dead_lettered_at)));u=Number((c==null?void 0:c.total)??_.length)}return{events:_,start:t*r,limit:r,length:u}},async replay(i,e){return(await n.update(b).set({processed_at:null,dead_lettered_at:null,final_error:null,retry_count:0,next_retry_at:null,error:null}).where(g(a(b.id,i),a(b.tenant_id,e),Me(b.dead_lettered_at))).returning()).length>0}}}const Ks=7*24*60*60*1e3;function js(n){return async i=>{const e=Date.now()-Ks;try{let t=[de(we(z.expires_at_ts,e),we(z.idle_expires_at_ts,e))];i!=null&&i.tenant_id&&t.push(a(z.tenant_id,i.tenant_id)),await n.delete(z).where(g(...t)),t=[de(we($.expires_at_ts,e),we($.idle_expires_at_ts,e))],i!=null&&i.tenant_id&&t.push(a($.tenant_id,i.tenant_id)),i!=null&&i.user_id&&t.push(a($.user_id,i.user_id)),await n.delete($).where(g(...t)),t=[we(L.expires_at_ts,e)],i!=null&&i.tenant_id&&t.push(a(L.tenant_id,i.tenant_id)),await n.delete(L).where(g(...t))}catch(t){console.error("Session cleanup error:",t)}}}function Ms(n,i={useTransactions:!0}){const e={actions:Ir(),branding:jr(n),clients:Mr(n),clientConnections:Rr(n),clientGrants:Xr(n),codes:Zr(n),connections:ts(n),customDomains:ns(n),customText:is(n),emailProviders:rs(n),flows:ss(n),forms:os(n),hookCode:_s(n),hooks:ds(n),invites:gs(n),keys:fs(n),loginSessions:hs(n),logs:ms(n),authenticationMethods:ws(n),organizations:vs(n),passwords:Ss(n),promptSettings:xs(n),refreshTokens:bs(n),resourceServers:Os(n),rolePermissions:ks(n),userPermissions:Is(n),roles:zs(n),sessions:Ls(n),sessionCleanup:js(n),tenants:Es(n),themes:As(n),universalLoginTemplates:Bs(n),users:$s(n),userRoles:Qs(n),userOrganizations:Js(n),stats:Fs(n),outbox:Us(n),async transaction(t){if(i.useTransactions===!1)return t(e);await n.run(w`BEGIN`);try{const r=await t(e);return await n.run(w`COMMIT`),r}catch(r){throw await n.run(w`ROLLBACK`),r}}};return e}exports.default=Ms;exports.sqlite=Pr;
13
+ WHERE tenant_id = ${e} AND client_id = ${i}`);return(a.changes??((l=a.meta)==null?void 0:l.changes)??0)>0}}}let ls="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",ds=n=>crypto.getRandomValues(new Uint8Array(n)),cs=(n,e,t)=>{let i=256-256%n.length;if(i===256){let r=n.length-1;return(l=e)=>{if(!l)return"";let d="";for(;;){let u=t(l),f=l;for(;f--;)if(d+=n[u[f]&r],d.length>=l)return d}}}let a=Math.ceil(1.6*256*e/i);return(r=e)=>{if(!r)return"";let l="";for(;;){let d=t(a),u=a;for(;u--;)if(d[u]<i&&(l+=n[d[u]%n.length],l.length>=r))return l}}},_s=(n,e=21)=>cs(n,e|0,ds),Ie=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=ls[t[n]&63];return e};function Cn(n){const{tenant_id:e,scope:t,authorization_details_types:i,allow_any_organization:a,is_system:r,...l}=n;return K({...l,scope:z(t,[]),authorization_details_types:z(i,[]),allow_any_organization:!!a,is_system:!!r})}function us(n){return{async create(e,t){const i=new Date().toISOString(),r={id:t.id||Ie(),tenant_id:e,client_id:t.client_id,audience:t.audience,scope:JSON.stringify(t.scope||[]),organization_usage:t.organization_usage,allow_any_organization:t.allow_any_organization?1:0,is_system:t.is_system?1:0,subject_type:t.subject_type,authorization_details_types:JSON.stringify(t.authorization_details_types||[]),created_at:i,updated_at:i};return await n.insert(me).values(r),Cn({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(me).where(g(c(me.tenant_id,e),c(me.id,t))).get();return i?Cn(i):null},async update(e,t,i){const{scope:a,authorization_details_types:r,allow_any_organization:l,is_system:d,...u}=i,f={...u,updated_at:new Date().toISOString()};return a!==void 0&&(f.scope=JSON.stringify(a)),r!==void 0&&(f.authorization_details_types=JSON.stringify(r)),l!==void 0&&(f.allow_any_organization=l?1:0),d!==void 0&&(f.is_system=d?1:0),(await n.update(me).set(f).where(g(c(me.tenant_id,e),c(me.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{},u=d?je(me,d,["client_id","audience"]):void 0,f=u?g(c(me.tenant_id,e),u):c(me.tenant_id,e);let p=n.select().from(me).where(f).$dynamic();if(l!=null&&l.sort_by){const T=me[l.sort_by];T&&(p=p.orderBy(l.sort_order==="desc"?ce(T):ge(T)))}else p=p.orderBy(ge(me.created_at));const m=(await p.offset(i*a).limit(a)).map(Cn);if(!r)return{client_grants:m};const[N]=await n.select({count:he()}).from(me).where(f);return{client_grants:m,start:i*a,limit:a,length:Number((N==null?void 0:N.count)??0)}},async remove(e,t){return(await n.delete(me).where(g(c(me.tenant_id,e),c(me.id,t))).returning()).length>0}}}function ps(n,e){var t={};for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.indexOf(i)<0&&(t[i]=n[i]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,i=Object.getOwnPropertySymbols(n);a<i.length;a++)e.indexOf(i[a])<0&&Object.prototype.propertyIsEnumerable.call(n,i[a])&&(t[i[a]]=n[i[a]]);return t}function fs(n,e){var t;return((t=n==null?void 0:n._def)===null||t===void 0?void 0:t.typeName)===e}function Tt(n,e){const t=n.ZodType.prototype[e];n.ZodType.prototype[e]=function(...i){const a=t.apply(this,i);return a._def.openapi=this._def.openapi,a}}function hs(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(a,r){var l,d,u,f,p,v;const m=typeof a=="string"?r:a,N=m??{},{param:T}=N,ee=ps(N,["param"]),ie=Object.assign(Object.assign({},(l=this._def.openapi)===null||l===void 0?void 0:l._internal),typeof a=="string"?{refId:a}:void 0),ae=Object.assign(Object.assign(Object.assign({},(d=this._def.openapi)===null||d===void 0?void 0:d.metadata),ee),!((f=(u=this._def.openapi)===null||u===void 0?void 0:u.metadata)===null||f===void 0)&&f.param||T?{param:Object.assign(Object.assign({},(v=(p=this._def.openapi)===null||p===void 0?void 0:p.metadata)===null||v===void 0?void 0:v.param),T)}:void 0),Ge=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(ie).length>0?{_internal:ie}:void 0),Object.keys(ae).length>0?{metadata:ae}:void 0)}));if(fs(this,"ZodObject")){const ut=this.extend;Ge.extend=function(...vn){var wn,Sn,Nn,bn,En,xn,kn;const On=ut.apply(this,vn);return On._def.openapi={_internal:{extendedFrom:!((Sn=(wn=this._def.openapi)===null||wn===void 0?void 0:wn._internal)===null||Sn===void 0)&&Sn.refId?{refId:(bn=(Nn=this._def.openapi)===null||Nn===void 0?void 0:Nn._internal)===null||bn===void 0?void 0:bn.refId,schema:this}:(xn=(En=this._def.openapi)===null||En===void 0?void 0:En._internal)===null||xn===void 0?void 0:xn.extendedFrom},metadata:(kn=On._def.openapi)===null||kn===void 0?void 0:kn.metadata},On}}return Ge},Tt(n,"optional"),Tt(n,"nullable"),Tt(n,"default"),Tt(n,"transform"),Tt(n,"refine");const e=n.ZodObject.prototype.deepPartial;n.ZodObject.prototype.deepPartial=function(){const a=this._def.shape(),r=e.apply(this),l=r._def.shape();return Object.entries(l).forEach(([d,u])=>{var f,p;u._def.openapi=(p=(f=a[d])===null||f===void 0?void 0:f._def)===null||p===void 0?void 0:p.openapi}),r._def.openapi=void 0,r};const t=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...a){const r=t.apply(this,a);return r._def.openapi=void 0,r};const i=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...a){const r=i.apply(this,a);return r._def.openapi=void 0,r}}new Set(".\\+*[^]$()");var H;(function(n){n.assertEqual=a=>{};function e(a){}n.assertIs=e;function t(a){throw new Error}n.assertNever=t,n.arrayToEnum=a=>{const r={};for(const l of a)r[l]=l;return r},n.getValidEnumValues=a=>{const r=n.objectKeys(a).filter(d=>typeof a[a[d]]!="number"),l={};for(const d of r)l[d]=a[d];return n.objectValues(l)},n.objectValues=a=>n.objectKeys(a).map(function(r){return a[r]}),n.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{const r=[];for(const l in a)Object.prototype.hasOwnProperty.call(a,l)&&r.push(l);return r},n.find=(a,r)=>{for(const l of a)if(r(l))return l},n.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function i(a,r=" | "){return a.map(l=>typeof l=="string"?`'${l}'`:l).join(r)}n.joinValues=i,n.jsonStringifyReplacer=(a,r)=>typeof r=="bigint"?r.toString():r})(H||(H={}));var Xn;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Xn||(Xn={}));const x=H.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),We=n=>{switch(typeof n){case"undefined":return x.undefined;case"string":return x.string;case"number":return Number.isNaN(n)?x.nan:x.number;case"boolean":return x.boolean;case"function":return x.function;case"bigint":return x.bigint;case"symbol":return x.symbol;case"object":return Array.isArray(n)?x.array:n===null?x.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?x.promise:typeof Map<"u"&&n instanceof Map?x.map:typeof Set<"u"&&n instanceof Set?x.set:typeof Date<"u"&&n instanceof Date?x.date:x.object;default:return x.unknown}},S=H.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Ke extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(r){return r.message},i={_errors:[]},a=r=>{for(const l of r.issues)if(l.code==="invalid_union")l.unionErrors.map(a);else if(l.code==="invalid_return_type")a(l.returnTypeError);else if(l.code==="invalid_arguments")a(l.argumentsError);else if(l.path.length===0)i._errors.push(t(l));else{let d=i,u=0;for(;u<l.path.length;){const f=l.path[u];u===l.path.length-1?(d[f]=d[f]||{_errors:[]},d[f]._errors.push(t(l))):d[f]=d[f]||{_errors:[]},d=d[f],u++}}};return a(this),i}static assert(e){if(!(e instanceof Ke))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,H.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const a of this.issues)if(a.path.length>0){const r=a.path[0];t[r]=t[r]||[],t[r].push(e(a))}else i.push(e(a));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}Ke.create=n=>new Ke(n);const ln=(n,e)=>{let t;switch(n.code){case S.invalid_type:n.received===x.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case S.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,H.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:t=`Unrecognized key(s) in object: ${H.joinValues(n.keys,", ")}`;break;case S.invalid_union:t="Invalid input";break;case S.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${H.joinValues(n.options)}`;break;case S.invalid_enum_value:t=`Invalid enum value. Expected ${H.joinValues(n.options)}, received '${n.received}'`;break;case S.invalid_arguments:t="Invalid function arguments";break;case S.invalid_return_type:t="Invalid function return type";break;case S.invalid_date:t="Invalid date";break;case S.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:H.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case S.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case S.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case S.custom:t="Invalid input";break;case S.invalid_intersection_types:t="Intersection results could not be merged";break;case S.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case S.not_finite:t="Number must be finite";break;default:t=e.defaultError,H.assertNever(n)}return{message:t}};let gs=ln;function rr(){return gs}const sr=n=>{const{data:e,path:t,errorMaps:i,issueData:a}=n,r=[...t,...a.path||[]],l={...a,path:r};if(a.message!==void 0)return{...a,path:r,message:a.message};let d="";const u=i.filter(f=>!!f).slice().reverse();for(const f of u)d=f(l,{data:e,defaultError:d}).message;return{...a,path:r,message:d}};function E(n,e){const t=rr(),i=sr({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ln?void 0:ln].filter(a=>!!a)});n.common.issues.push(i)}class ke{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const a of t){if(a.status==="aborted")return R;a.status==="dirty"&&e.dirty(),i.push(a.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const a of t){const r=await a.key,l=await a.value;i.push({key:r,value:l})}return ke.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const a of t){const{key:r,value:l}=a;if(r.status==="aborted"||l.status==="aborted")return R;r.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),r.value!=="__proto__"&&(typeof l.value<"u"||a.alwaysSet)&&(i[r.value]=l.value)}return{status:e.value,value:i}}}const R=Object.freeze({status:"aborted"}),Nt=n=>({status:"dirty",value:n}),De=n=>({status:"valid",value:n}),Yn=n=>n.status==="aborted",ei=n=>n.status==="dirty",mt=n=>n.status==="valid",Ut=n=>typeof Promise<"u"&&n instanceof Promise;var C;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(C||(C={}));class Qe{constructor(e,t,i,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const ki=(n,e)=>{if(mt(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new Ke(n.common.issues);return this._error=t,this._error}}};function M(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:a}=n;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(l,d)=>{const{message:u}=n;return l.code==="invalid_enum_value"?{message:u??d.defaultError}:typeof d.data>"u"?{message:u??i??d.defaultError}:l.code!=="invalid_type"?{message:d.defaultError}:{message:u??t??d.defaultError}},description:a}}class q{get description(){return this._def.description}_getType(e){return We(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:We(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ke,ctx:{common:e.parent.common,data:e.data,parsedType:We(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ut(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:(t==null?void 0:t.async)??!1,contextualErrorMap:t==null?void 0:t.errorMap},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:We(e)},a=this._parseSync({data:e,path:i.path,parent:i});return ki(i,a)}"~validate"(e){var i,a;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:We(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return mt(r)?{value:r.value}:{issues:t.common.issues}}catch(r){(a=(i=r==null?void 0:r.message)==null?void 0:i.toLowerCase())!=null&&a.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>mt(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t==null?void 0:t.errorMap,async:!0},path:(t==null?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:We(e)},a=this._parse({data:e,path:i.path,parent:i}),r=await(Ut(a)?a:Promise.resolve(a));return ki(i,r)}refine(e,t){const i=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,r)=>{const l=e(a),d=()=>r.addIssue({code:S.custom,...i(a)});return typeof Promise<"u"&&l instanceof Promise?l.then(u=>u?!0:(d(),!1)):l?!0:(d(),!1)})}refinement(e,t){return this._refinement((i,a)=>e(i)?!0:(a.addIssue(typeof t=="function"?t(i,a):t),!1))}_refinement(e){return new tt({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return He.create(this,this._def)}nullable(){return dt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $e.create(this)}promise(){return jt.create(this,this._def)}or(e){return Pt.create([this,e],this._def)}and(e){return Mt.create(this,e,this._def)}transform(e){return new tt({...M(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Vt({...M(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new yi({typeName:U.ZodBranded,type:this,...M(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Zt({...M(this._def),innerType:this,catchValue:t,typeName:U.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return mn.create(this,e)}readonly(){return Ht.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const ms=/^c[^\s-]{8,}$/i,ys=/^[0-9a-z]+$/,vs=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ws=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ss=/^[a-z0-9_-]{21}$/i,Ns=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bs=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Es=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Dn;const ks=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Os=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ts=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,As=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Is=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Cs=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,lr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ds=new RegExp(`^${lr}$`);function dr(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Ls(n){return new RegExp(`^${dr(n)}$`)}function cr(n){let e=`${lr}T${dr(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Rs(n,e){return!!((e==="v4"||!e)&&ks.test(n)||(e==="v6"||!e)&&Ts.test(n))}function Us(n,e){if(!Ns.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(i));return!(typeof a!="object"||a===null||"typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function zs(n,e){return!!((e==="v4"||!e)&&Os.test(n)||(e==="v6"||!e)&&As.test(n))}class Ze extends q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==x.string){const r=this._getOrReturnCtx(e);return E(r,{code:S.invalid_type,expected:x.string,received:r.parsedType}),R}const i=new ke;let a;for(const r of this._def.checks)if(r.kind==="min")e.data.length<r.value&&(a=this._getOrReturnCtx(e,a),E(a,{code:S.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="max")e.data.length>r.value&&(a=this._getOrReturnCtx(e,a),E(a,{code:S.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="length"){const l=e.data.length>r.value,d=e.data.length<r.value;(l||d)&&(a=this._getOrReturnCtx(e,a),l?E(a,{code:S.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):d&&E(a,{code:S.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),i.dirty())}else if(r.kind==="email")Es.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"email",code:S.invalid_string,message:r.message}),i.dirty());else if(r.kind==="emoji")Dn||(Dn=new RegExp(xs,"u")),Dn.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"emoji",code:S.invalid_string,message:r.message}),i.dirty());else if(r.kind==="uuid")ws.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"uuid",code:S.invalid_string,message:r.message}),i.dirty());else if(r.kind==="nanoid")Ss.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"nanoid",code:S.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid")ms.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"cuid",code:S.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid2")ys.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"cuid2",code:S.invalid_string,message:r.message}),i.dirty());else if(r.kind==="ulid")vs.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"ulid",code:S.invalid_string,message:r.message}),i.dirty());else if(r.kind==="url")try{new URL(e.data)}catch{a=this._getOrReturnCtx(e,a),E(a,{validation:"url",code:S.invalid_string,message:r.message}),i.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"regex",code:S.invalid_string,message:r.message}),i.dirty())):r.kind==="trim"?e.data=e.data.trim():r.kind==="includes"?e.data.includes(r.value,r.position)||(a=this._getOrReturnCtx(e,a),E(a,{code:S.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()):r.kind==="toLowerCase"?e.data=e.data.toLowerCase():r.kind==="toUpperCase"?e.data=e.data.toUpperCase():r.kind==="startsWith"?e.data.startsWith(r.value)||(a=this._getOrReturnCtx(e,a),E(a,{code:S.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()):r.kind==="endsWith"?e.data.endsWith(r.value)||(a=this._getOrReturnCtx(e,a),E(a,{code:S.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()):r.kind==="datetime"?cr(r).test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{code:S.invalid_string,validation:"datetime",message:r.message}),i.dirty()):r.kind==="date"?Ds.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{code:S.invalid_string,validation:"date",message:r.message}),i.dirty()):r.kind==="time"?Ls(r).test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{code:S.invalid_string,validation:"time",message:r.message}),i.dirty()):r.kind==="duration"?bs.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"duration",code:S.invalid_string,message:r.message}),i.dirty()):r.kind==="ip"?Rs(e.data,r.version)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"ip",code:S.invalid_string,message:r.message}),i.dirty()):r.kind==="jwt"?Us(e.data,r.alg)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"jwt",code:S.invalid_string,message:r.message}),i.dirty()):r.kind==="cidr"?zs(e.data,r.version)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"cidr",code:S.invalid_string,message:r.message}),i.dirty()):r.kind==="base64"?Is.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"base64",code:S.invalid_string,message:r.message}),i.dirty()):r.kind==="base64url"?Cs.test(e.data)||(a=this._getOrReturnCtx(e,a),E(a,{validation:"base64url",code:S.invalid_string,message:r.message}),i.dirty()):H.assertNever(r);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(a=>e.test(a),{validation:t,code:S.invalid_string,...C.errToObj(i)})}_addCheck(e){return new Ze({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...C.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...C.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...C.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t==null?void 0:t.position,...C.errToObj(t==null?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...C.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...C.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...C.errToObj(t)})}nonempty(e){return this.min(1,C.errToObj(e))}trim(){return new Ze({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ze({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ze({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Ze.create=n=>new Ze({checks:[],typeName:U.ZodString,coerce:(n==null?void 0:n.coerce)??!1,...M(n)});function Fs(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,a=t>i?t:i,r=Number.parseInt(n.toFixed(a).replace(".","")),l=Number.parseInt(e.toFixed(a).replace(".",""));return r%l/10**a}class yt extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==x.number){const r=this._getOrReturnCtx(e);return E(r,{code:S.invalid_type,expected:x.number,received:r.parsedType}),R}let i;const a=new ke;for(const r of this._def.checks)r.kind==="int"?H.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{code:S.invalid_type,expected:"integer",received:"float",message:r.message}),a.dirty()):r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),E(i,{code:S.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),a.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),E(i,{code:S.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),a.dirty()):r.kind==="multipleOf"?Fs(e.data,r.value)!==0&&(i=this._getOrReturnCtx(e,i),E(i,{code:S.not_multiple_of,multipleOf:r.value,message:r.message}),a.dirty()):r.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),E(i,{code:S.not_finite,message:r.message}),a.dirty()):H.assertNever(r);return{status:a.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,i,a){return new yt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(a)}]})}_addCheck(e){return new yt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&H.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}yt.create=n=>new yt({checks:[],typeName:U.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...M(n)});class Et extends q{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==x.bigint)return this._getInvalidInput(e);let i;const a=new ke;for(const r of this._def.checks)r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),E(i,{code:S.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),a.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),E(i,{code:S.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),a.dirty()):r.kind==="multipleOf"?e.data%r.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),E(i,{code:S.not_multiple_of,multipleOf:r.value,message:r.message}),a.dirty()):H.assertNever(r);return{status:a.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return E(t,{code:S.invalid_type,expected:x.bigint,received:t.parsedType}),R}gte(e,t){return this.setLimit("min",e,!0,C.toString(t))}gt(e,t){return this.setLimit("min",e,!1,C.toString(t))}lte(e,t){return this.setLimit("max",e,!0,C.toString(t))}lt(e,t){return this.setLimit("max",e,!1,C.toString(t))}setLimit(e,t,i,a){return new Et({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(a)}]})}_addCheck(e){return new Et({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Et.create=n=>new Et({checks:[],typeName:U.ZodBigInt,coerce:(n==null?void 0:n.coerce)??!1,...M(n)});class dn extends q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==x.boolean){const i=this._getOrReturnCtx(e);return E(i,{code:S.invalid_type,expected:x.boolean,received:i.parsedType}),R}return De(e.data)}}dn.create=n=>new dn({typeName:U.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...M(n)});class zt extends q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==x.date){const r=this._getOrReturnCtx(e);return E(r,{code:S.invalid_type,expected:x.date,received:r.parsedType}),R}if(Number.isNaN(e.data.getTime())){const r=this._getOrReturnCtx(e);return E(r,{code:S.invalid_date}),R}const i=new ke;let a;for(const r of this._def.checks)r.kind==="min"?e.data.getTime()<r.value&&(a=this._getOrReturnCtx(e,a),E(a,{code:S.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()):r.kind==="max"?e.data.getTime()>r.value&&(a=this._getOrReturnCtx(e,a),E(a,{code:S.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()):H.assertNever(r);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new zt({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:C.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:C.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}zt.create=n=>new zt({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:U.ZodDate,...M(n)});class ti extends q{_parse(e){if(this._getType(e)!==x.symbol){const i=this._getOrReturnCtx(e);return E(i,{code:S.invalid_type,expected:x.symbol,received:i.parsedType}),R}return De(e.data)}}ti.create=n=>new ti({typeName:U.ZodSymbol,...M(n)});class cn extends q{_parse(e){if(this._getType(e)!==x.undefined){const i=this._getOrReturnCtx(e);return E(i,{code:S.invalid_type,expected:x.undefined,received:i.parsedType}),R}return De(e.data)}}cn.create=n=>new cn({typeName:U.ZodUndefined,...M(n)});class _n extends q{_parse(e){if(this._getType(e)!==x.null){const i=this._getOrReturnCtx(e);return E(i,{code:S.invalid_type,expected:x.null,received:i.parsedType}),R}return De(e.data)}}_n.create=n=>new _n({typeName:U.ZodNull,...M(n)});class Ft extends q{constructor(){super(...arguments),this._any=!0}_parse(e){return De(e.data)}}Ft.create=n=>new Ft({typeName:U.ZodAny,...M(n)});class un extends q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return De(e.data)}}un.create=n=>new un({typeName:U.ZodUnknown,...M(n)});class et extends q{_parse(e){const t=this._getOrReturnCtx(e);return E(t,{code:S.invalid_type,expected:x.never,received:t.parsedType}),R}}et.create=n=>new et({typeName:U.ZodNever,...M(n)});class ni extends q{_parse(e){if(this._getType(e)!==x.undefined){const i=this._getOrReturnCtx(e);return E(i,{code:S.invalid_type,expected:x.void,received:i.parsedType}),R}return De(e.data)}}ni.create=n=>new ni({typeName:U.ZodVoid,...M(n)});class $e extends q{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),a=this._def;if(t.parsedType!==x.array)return E(t,{code:S.invalid_type,expected:x.array,received:t.parsedType}),R;if(a.exactLength!==null){const l=t.data.length>a.exactLength.value,d=t.data.length<a.exactLength.value;(l||d)&&(E(t,{code:l?S.too_big:S.too_small,minimum:d?a.exactLength.value:void 0,maximum:l?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),i.dirty())}if(a.minLength!==null&&t.data.length<a.minLength.value&&(E(t,{code:S.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),i.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(E(t,{code:S.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,d)=>a.type._parseAsync(new Qe(t,l,t.path,d)))).then(l=>ke.mergeArray(i,l));const r=[...t.data].map((l,d)=>a.type._parseSync(new Qe(t,l,t.path,d)));return ke.mergeArray(i,r)}get element(){return this._def.type}min(e,t){return new $e({...this._def,minLength:{value:e,message:C.toString(t)}})}max(e,t){return new $e({...this._def,maxLength:{value:e,message:C.toString(t)}})}length(e,t){return new $e({...this._def,exactLength:{value:e,message:C.toString(t)}})}nonempty(e){return this.min(1,e)}}$e.create=(n,e)=>new $e({type:n,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...M(e)});function wt(n){if(n instanceof le){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=He.create(wt(i))}return new le({...n._def,shape:()=>e})}else return n instanceof $e?new $e({...n._def,type:wt(n.element)}):n instanceof He?He.create(wt(n.unwrap())):n instanceof dt?dt.create(wt(n.unwrap())):n instanceof st?st.create(n.items.map(e=>wt(e))):n}class le extends q{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=H.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==x.object){const f=this._getOrReturnCtx(e);return E(f,{code:S.invalid_type,expected:x.object,received:f.parsedType}),R}const{status:i,ctx:a}=this._processInputParams(e),{shape:r,keys:l}=this._getCached(),d=[];if(!(this._def.catchall instanceof et&&this._def.unknownKeys==="strip"))for(const f in a.data)l.includes(f)||d.push(f);const u=[];for(const f of l){const p=r[f],v=a.data[f];u.push({key:{status:"valid",value:f},value:p._parse(new Qe(a,v,a.path,f)),alwaysSet:f in a.data})}if(this._def.catchall instanceof et){const f=this._def.unknownKeys;if(f==="passthrough")for(const p of d)u.push({key:{status:"valid",value:p},value:{status:"valid",value:a.data[p]}});else if(f==="strict")d.length>0&&(E(a,{code:S.unrecognized_keys,keys:d}),i.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const p of d){const v=a.data[p];u.push({key:{status:"valid",value:p},value:f._parse(new Qe(a,v,a.path,p)),alwaysSet:p in a.data})}}return a.common.async?Promise.resolve().then(async()=>{const f=[];for(const p of u){const v=await p.key,m=await p.value;f.push({key:v,value:m,alwaysSet:p.alwaysSet})}return f}).then(f=>ke.mergeObjectSync(i,f)):ke.mergeObjectSync(i,u)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new le({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var r,l;const a=((l=(r=this._def).errorMap)==null?void 0:l.call(r,t,i).message)??i.defaultError;return t.code==="unrecognized_keys"?{message:C.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new le({...this._def,unknownKeys:"strip"})}passthrough(){return new le({...this._def,unknownKeys:"passthrough"})}extend(e){return new le({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new le({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:U.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new le({...this._def,catchall:e})}pick(e){const t={};for(const i of H.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new le({...this._def,shape:()=>t})}omit(e){const t={};for(const i of H.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new le({...this._def,shape:()=>t})}deepPartial(){return wt(this)}partial(e){const t={};for(const i of H.objectKeys(this.shape)){const a=this.shape[i];e&&!e[i]?t[i]=a:t[i]=a.optional()}return new le({...this._def,shape:()=>t})}required(e){const t={};for(const i of H.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof He;)r=r._def.innerType;t[i]=r}return new le({...this._def,shape:()=>t})}keyof(){return _r(H.objectKeys(this.shape))}}le.create=(n,e)=>new le({shape:()=>n,unknownKeys:"strip",catchall:et.create(),typeName:U.ZodObject,...M(e)});le.strictCreate=(n,e)=>new le({shape:()=>n,unknownKeys:"strict",catchall:et.create(),typeName:U.ZodObject,...M(e)});le.lazycreate=(n,e)=>new le({shape:n,unknownKeys:"strip",catchall:et.create(),typeName:U.ZodObject,...M(e)});class Pt extends q{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function a(r){for(const d of r)if(d.result.status==="valid")return d.result;for(const d of r)if(d.result.status==="dirty")return t.common.issues.push(...d.ctx.common.issues),d.result;const l=r.map(d=>new Ke(d.ctx.common.issues));return E(t,{code:S.invalid_union,unionErrors:l}),R}if(t.common.async)return Promise.all(i.map(async r=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(a);{let r;const l=[];for(const u of i){const f={...t,common:{...t.common,issues:[]},parent:null},p=u._parseSync({data:t.data,path:t.path,parent:f});if(p.status==="valid")return p;p.status==="dirty"&&!r&&(r={result:p,ctx:f}),f.common.issues.length&&l.push(f.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;const d=l.map(u=>new Ke(u));return E(t,{code:S.invalid_union,unionErrors:d}),R}}get options(){return this._def.options}}Pt.create=(n,e)=>new Pt({options:n,typeName:U.ZodUnion,...M(e)});const Je=n=>n instanceof pn?Je(n.schema):n instanceof tt?Je(n.innerType()):n instanceof Bt?[n.value]:n instanceof lt?n.options:n instanceof $t?H.objectValues(n.enum):n instanceof Vt?Je(n._def.innerType):n instanceof cn?[void 0]:n instanceof _n?[null]:n instanceof He?[void 0,...Je(n.unwrap())]:n instanceof dt?[null,...Je(n.unwrap())]:n instanceof yi||n instanceof Ht?Je(n.unwrap()):n instanceof Zt?Je(n._def.innerType):[];class gn extends q{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==x.object)return E(t,{code:S.invalid_type,expected:x.object,received:t.parsedType}),R;const i=this.discriminator,a=t.data[i],r=this.optionsMap.get(a);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(E(t,{code:S.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),R)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const a=new Map;for(const r of t){const l=Je(r.shape[e]);if(!l.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const d of l){if(a.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);a.set(d,r)}}return new gn({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,...M(i)})}}function ii(n,e){const t=We(n),i=We(e);if(n===e)return{valid:!0,data:n};if(t===x.object&&i===x.object){const a=H.objectKeys(e),r=H.objectKeys(n).filter(d=>a.indexOf(d)!==-1),l={...n,...e};for(const d of r){const u=ii(n[d],e[d]);if(!u.valid)return{valid:!1};l[d]=u.data}return{valid:!0,data:l}}else if(t===x.array&&i===x.array){if(n.length!==e.length)return{valid:!1};const a=[];for(let r=0;r<n.length;r++){const l=n[r],d=e[r],u=ii(l,d);if(!u.valid)return{valid:!1};a.push(u.data)}return{valid:!0,data:a}}else return t===x.date&&i===x.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Mt extends q{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),a=(r,l)=>{if(Yn(r)||Yn(l))return R;const d=ii(r.value,l.value);return d.valid?((ei(r)||ei(l))&&t.dirty(),{status:t.value,value:d.data}):(E(i,{code:S.invalid_intersection_types}),R)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([r,l])=>a(r,l)):a(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Mt.create=(n,e,t)=>new Mt({left:n,right:e,typeName:U.ZodIntersection,...M(t)});class st extends q{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==x.array)return E(i,{code:S.invalid_type,expected:x.array,received:i.parsedType}),R;if(i.data.length<this._def.items.length)return E(i,{code:S.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&i.data.length>this._def.items.length&&(E(i,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...i.data].map((l,d)=>{const u=this._def.items[d]||this._def.rest;return u?u._parse(new Qe(i,l,i.path,d)):null}).filter(l=>!!l);return i.common.async?Promise.all(r).then(l=>ke.mergeArray(t,l)):ke.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new st({...this._def,rest:e})}}st.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new st({items:n,typeName:U.ZodTuple,rest:null,...M(e)})};class qt extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==x.object)return E(i,{code:S.invalid_type,expected:x.object,received:i.parsedType}),R;const a=[],r=this._def.keyType,l=this._def.valueType;for(const d in i.data)a.push({key:r._parse(new Qe(i,d,i.path,d)),value:l._parse(new Qe(i,i.data[d],i.path,d)),alwaysSet:d in i.data});return i.common.async?ke.mergeObjectAsync(t,a):ke.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof q?new qt({keyType:e,valueType:t,typeName:U.ZodRecord,...M(i)}):new qt({keyType:Ze.create(),valueType:e,typeName:U.ZodRecord,...M(t)})}}class ai extends q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==x.map)return E(i,{code:S.invalid_type,expected:x.map,received:i.parsedType}),R;const a=this._def.keyType,r=this._def.valueType,l=[...i.data.entries()].map(([d,u],f)=>({key:a._parse(new Qe(i,d,i.path,[f,"key"])),value:r._parse(new Qe(i,u,i.path,[f,"value"]))}));if(i.common.async){const d=new Map;return Promise.resolve().then(async()=>{for(const u of l){const f=await u.key,p=await u.value;if(f.status==="aborted"||p.status==="aborted")return R;(f.status==="dirty"||p.status==="dirty")&&t.dirty(),d.set(f.value,p.value)}return{status:t.value,value:d}})}else{const d=new Map;for(const u of l){const f=u.key,p=u.value;if(f.status==="aborted"||p.status==="aborted")return R;(f.status==="dirty"||p.status==="dirty")&&t.dirty(),d.set(f.value,p.value)}return{status:t.value,value:d}}}}ai.create=(n,e,t)=>new ai({valueType:e,keyType:n,typeName:U.ZodMap,...M(t)});class xt extends q{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==x.set)return E(i,{code:S.invalid_type,expected:x.set,received:i.parsedType}),R;const a=this._def;a.minSize!==null&&i.data.size<a.minSize.value&&(E(i,{code:S.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&i.data.size>a.maxSize.value&&(E(i,{code:S.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const r=this._def.valueType;function l(u){const f=new Set;for(const p of u){if(p.status==="aborted")return R;p.status==="dirty"&&t.dirty(),f.add(p.value)}return{status:t.value,value:f}}const d=[...i.data.values()].map((u,f)=>r._parse(new Qe(i,u,i.path,f)));return i.common.async?Promise.all(d).then(u=>l(u)):l(d)}min(e,t){return new xt({...this._def,minSize:{value:e,message:C.toString(t)}})}max(e,t){return new xt({...this._def,maxSize:{value:e,message:C.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}xt.create=(n,e)=>new xt({valueType:n,minSize:null,maxSize:null,typeName:U.ZodSet,...M(e)});class pn extends q{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}pn.create=(n,e)=>new pn({getter:n,typeName:U.ZodLazy,...M(e)});class Bt extends q{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return E(t,{received:t.data,code:S.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:e.data}}get value(){return this._def.value}}Bt.create=(n,e)=>new Bt({value:n,typeName:U.ZodLiteral,...M(e)});function _r(n,e){return new lt({values:n,typeName:U.ZodEnum,...M(e)})}class lt extends q{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return E(t,{expected:H.joinValues(i),received:t.parsedType,code:S.invalid_type}),R}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return E(t,{received:t.data,code:S.invalid_enum_value,options:i}),R}return De(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return lt.create(e,{...this._def,...t})}exclude(e,t=this._def){return lt.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}lt.create=_r;class $t extends q{_parse(e){const t=H.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==x.string&&i.parsedType!==x.number){const a=H.objectValues(t);return E(i,{expected:H.joinValues(a),received:i.parsedType,code:S.invalid_type}),R}if(this._cache||(this._cache=new Set(H.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=H.objectValues(t);return E(i,{received:i.data,code:S.invalid_enum_value,options:a}),R}return De(e.data)}get enum(){return this._def.values}}$t.create=(n,e)=>new $t({values:n,typeName:U.ZodNativeEnum,...M(e)});class jt extends q{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==x.promise&&t.common.async===!1)return E(t,{code:S.invalid_type,expected:x.promise,received:t.parsedType}),R;const i=t.parsedType===x.promise?t.data:Promise.resolve(t.data);return De(i.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}}jt.create=(n,e)=>new jt({type:n,typeName:U.ZodPromise,...M(e)});class tt extends q{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),a=this._def.effect||null,r={addIssue:l=>{E(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),a.type==="preprocess"){const l=a.transform(i.data,r);if(i.common.async)return Promise.resolve(l).then(async d=>{if(t.value==="aborted")return R;const u=await this._def.schema._parseAsync({data:d,path:i.path,parent:i});return u.status==="aborted"?R:u.status==="dirty"||t.value==="dirty"?Nt(u.value):u});{if(t.value==="aborted")return R;const d=this._def.schema._parseSync({data:l,path:i.path,parent:i});return d.status==="aborted"?R:d.status==="dirty"||t.value==="dirty"?Nt(d.value):d}}if(a.type==="refinement"){const l=d=>{const u=a.refinement(d,r);if(i.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return d};if(i.common.async===!1){const d=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return d.status==="aborted"?R:(d.status==="dirty"&&t.dirty(),l(d.value),{status:t.value,value:d.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(d=>d.status==="aborted"?R:(d.status==="dirty"&&t.dirty(),l(d.value).then(()=>({status:t.value,value:d.value}))))}if(a.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!mt(l))return R;const d=a.transform(l.value,r);if(d instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:d}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(l=>mt(l)?Promise.resolve(a.transform(l.value,r)).then(d=>({status:t.value,value:d})):R);H.assertNever(a)}}tt.create=(n,e,t)=>new tt({schema:n,typeName:U.ZodEffects,effect:e,...M(t)});tt.createWithPreprocess=(n,e,t)=>new tt({schema:e,effect:{type:"preprocess",transform:n},typeName:U.ZodEffects,...M(t)});class He extends q{_parse(e){return this._getType(e)===x.undefined?De(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}He.create=(n,e)=>new He({innerType:n,typeName:U.ZodOptional,...M(e)});class dt extends q{_parse(e){return this._getType(e)===x.null?De(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}dt.create=(n,e)=>new dt({innerType:n,typeName:U.ZodNullable,...M(e)});class Vt extends q{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===x.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Vt.create=(n,e)=>new Vt({innerType:n,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...M(e)});class Zt extends q{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Ut(a)?a.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new Ke(i.common.issues)},input:i.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new Ke(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Zt.create=(n,e)=>new Zt({innerType:n,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...M(e)});class oi extends q{_parse(e){if(this._getType(e)!==x.nan){const i=this._getOrReturnCtx(e);return E(i,{code:S.invalid_type,expected:x.nan,received:i.parsedType}),R}return{status:"valid",value:e.data}}}oi.create=n=>new oi({typeName:U.ZodNaN,...M(n)});class yi extends q{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class mn extends q{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?R:r.status==="dirty"?(t.dirty(),Nt(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{const a=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?R:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:i.path,parent:i})}}static create(e,t){return new mn({in:e,out:t,typeName:U.ZodPipeline})}}class Ht extends q{_parse(e){const t=this._def.innerType._parse(e),i=a=>(mt(a)&&(a.value=Object.freeze(a.value)),a);return Ut(t)?t.then(a=>i(a)):i(t)}unwrap(){return this._def.innerType}}Ht.create=(n,e)=>new Ht({innerType:n,typeName:U.ZodReadonly,...M(e)});function ri(n,e={},t){return Ft.create()}var U;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(U||(U={}));const o=Ze.create,I=yt.create,h=dn.create,j=Ft.create,at=un.create;et.create;const b=$e.create,_=le.create,Pe=Pt.create,kt=gn.create;Mt.create;st.create;const P=qt.create,O=Bt.create,k=lt.create,gt=$t.create;jt.create;He.create;dt.create;const Ps=Object.freeze(Object.defineProperty({__proto__:null,DIRTY:Nt,INVALID:R,OK:De,ParseStatus:ke,Schema:q,ZodAny:Ft,ZodArray:$e,ZodBigInt:Et,ZodBoolean:dn,ZodBranded:yi,ZodCatch:Zt,ZodDate:zt,ZodDefault:Vt,ZodDiscriminatedUnion:gn,ZodEffects:tt,ZodEnum:lt,ZodError:Ke,get ZodFirstPartyTypeKind(){return U},ZodIntersection:Mt,ZodIssueCode:S,ZodLazy:pn,ZodLiteral:Bt,ZodMap:ai,ZodNaN:oi,ZodNativeEnum:$t,ZodNever:et,ZodNull:_n,ZodNullable:dt,ZodNumber:yt,ZodObject:le,ZodOptional:He,ZodParsedType:x,ZodPipeline:mn,ZodPromise:jt,ZodReadonly:Ht,ZodRecord:qt,ZodSchema:q,ZodSet:xt,ZodString:Ze,ZodSymbol:ti,ZodTransformer:tt,ZodTuple:st,ZodType:q,ZodUndefined:cn,ZodUnion:Pt,ZodUnknown:un,ZodVoid:ni,addIssueToContext:E,any:j,array:b,boolean:h,custom:ri,datetimeRegex:cr,defaultErrorMap:ln,discriminatedUnion:kt,enum:k,getErrorMap:rr,getParsedType:We,isAborted:Yn,isAsync:Ut,isDirty:ei,isValid:mt,literal:O,makeIssue:sr,nativeEnum:gt,number:I,object:_,get objectUtil(){return Xn},record:P,string:o,union:Pe,unknown:at,get util(){return H}},Symbol.toStringTag,{value:"Module"}));hs(Ps);const Ve=_({created_at:o(),updated_at:o()}),Ms=_({id:o(),version:o().optional()}),qs=_({name:o(),version:o()}),Bs=_({name:o(),value:o()}),ur=_({name:o().max(255),code:o().max(1e5),supported_triggers:b(Ms).optional(),runtime:o().max(50).optional(),dependencies:b(qs).optional(),secrets:b(Bs).optional()});ur.partial().extend({status:k(["draft","built"]).optional(),deployed_at:o().optional()});ur.extend({id:o(),tenant_id:o(),status:k(["draft","built"]).default("built"),deployed_at:o().optional(),secrets:b(_({name:o(),value:o().optional()})).optional(),...Ve.shape});const $s=k(["user_action","admin_action","system","api"]),js=_({type:k(["user","admin","system","api_key","client_credentials"]),id:o().optional(),email:o().optional(),org_id:o().optional(),org_name:o().optional(),scopes:b(o()).optional(),client_id:o().optional()}),Vs=_({type:o(),id:o(),before:P(at()).optional(),after:P(at()).optional(),diff:P(_({old:at(),new:at()})).optional()}),Zs=_({method:o(),path:o(),query:P(o()).optional(),body:at().optional(),ip:o(),user_agent:o().optional(),correlation_id:o().optional()}),Hs=_({status_code:I(),body:at().optional()}),Ks=_({country_code:o(),city_name:o(),latitude:o(),longitude:o(),time_zone:o(),continent_code:o()}),Qs=_({name:o(),version:o(),env:P(o()).optional()}),Gs=_({tenant_id:o(),event_type:o(),log_type:o(),description:o().optional(),category:$s,actor:js,target:Vs,request:Zs,response:Hs.optional(),connection:o().optional(),strategy:o().optional(),strategy_type:o().optional(),audience:o().optional(),scope:o().optional(),location:Ks.optional(),auth0_client:Qs.optional(),hostname:o(),is_mobile:h().optional(),timestamp:o()});Gs.extend({id:o()});k(["AUTH0","EMAIL","REDIRECT"]);k(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]);k(["VERIFY_EMAIL"]);const Js=_({require_mx_record:h().optional(),block_aliases:h().optional(),block_free_emails:h().optional(),block_disposable_emails:h().optional(),blocklist:b(o()).optional(),allowlist:b(o()).optional()}),Ws=_({id:o(),alias:o().max(100).optional(),type:O("AUTH0"),action:O("UPDATE_USER"),allow_failure:h().optional(),mask_output:h().optional(),params:_({connection_id:o().optional(),user_id:o(),changes:P(o(),j())})}),Xs=_({id:o(),alias:o().max(100).optional(),type:O("EMAIL"),action:O("VERIFY_EMAIL"),allow_failure:h().optional(),mask_output:h().optional(),params:_({email:o(),rules:Js.optional()})}),Ys=k(["change-email","account","custom"]),el=_({id:o(),alias:o().max(100).optional(),type:O("REDIRECT"),action:O("REDIRECT_USER"),allow_failure:h().optional(),mask_output:h().optional(),params:_({target:Ys.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:o().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),tl=Pe([Ws,Xs,el]),nl=_({name:o().min(1).max(150).openapi({description:"The name of the flow"}),actions:b(tl).optional().default([]).openapi({description:"The list of actions to execute in sequence"})});nl.extend({...Ve.shape,id:o().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})});_({page:o().min(0).optional().default("0").transform(n=>parseInt(n,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o().min(1).optional().default("10").transform(n=>parseInt(n,10)).openapi({description:"The number of items per page"}),include_totals:o().optional().default("false").transform(n=>n==="true").openapi({description:"If the total number of items should be included in the response"}),sort:o().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:o().optional().openapi({description:"A lucene query string used to filter the results"})});_({start:I(),limit:I(),length:I(),total:I().optional()});const il=_({email:o().optional(),email_verified:h().optional(),name:o().optional(),username:o().optional(),given_name:o().optional(),phone_number:o().optional(),phone_verified:h().optional(),family_name:o().optional()}).catchall(j()),al=_({connection:o(),user_id:o(),provider:o(),isSocial:h(),email:o().optional(),email_verified:h().optional(),phone_number:o().optional(),phone_verified:h().optional(),username:o().optional(),access_token:o().optional(),access_token_secret:o().optional(),refresh_token:o().optional(),profileData:il.optional()}),ol=_({formatted:o().optional(),street_address:o().optional(),locality:o().optional(),region:o().optional(),postal_code:o().optional(),country:o().optional()}).optional(),pr=_({email:o().optional().transform(n=>n&&n.toLowerCase()),username:o().refine(n=>!n.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:o().optional(),phone_verified:h().optional(),given_name:o().optional(),family_name:o().optional(),nickname:o().optional(),name:o().optional(),picture:o().optional(),locale:o().optional(),linked_to:o().optional(),profileData:o().optional(),user_id:o().optional(),app_metadata:j().default({}).optional(),user_metadata:j().default({}).optional(),middle_name:o().optional(),preferred_username:o().optional(),profile:o().optional(),website:o().optional(),gender:o().optional(),birthdate:o().optional(),zoneinfo:o().optional(),address:ol}),rl=pr.extend({email_verified:h().default(!1),verify_email:h().optional(),last_ip:o().optional(),last_login:o().optional(),user_id:o().optional(),provider:o().optional(),connection:o(),is_social:h().optional(),registration_completed_at:o().optional(),password:_({hash:o(),algorithm:o()}).optional()}),sl=_({...rl.omit({password:!0}).shape,...Ve.shape,user_id:o(),provider:o(),is_social:h(),email:o().optional(),login_count:I().default(0),identities:b(al).optional()});sl.omit({registration_completed_at:!0});pr.extend({login_count:I(),multifactor:b(o()).optional(),last_ip:o().optional(),last_login:o().optional(),user_id:o()}).catchall(j());let ll="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",dl=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=ll[t[n]&63];return e};const cl=_({client_id:o().openapi({description:"ID of this client."}),name:o().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:o().max(140).optional().openapi({description:"Free text description of this client (max length: 140 characters)."}),global:h().default(!1).openapi({description:"Whether this is your global 'All Applications' client representing legacy tenant settings (true) or a regular client (false)."}),client_secret:o().default(()=>dl()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:k(["native","spa","regular_web","non_interactive","resource_server","express_configuration","rms","box","cloudbees","concur","dropbox","mscrm","echosign","egnyte","newrelic","office365","salesforce","sentry","sharepoint","slack","springcm","zendesk","zoom","sso_integration","oag"]).default("regular_web").optional().openapi({description:"The type of application this client represents"}),logo_uri:o().url().optional().openapi({description:"URL of the logo to display for this client. Recommended size is 150x150 pixels."}),is_first_party:h().default(!1).openapi({description:"Whether this client a first party client (true) or not (false)."}),oidc_conformant:h().default(!0).openapi({description:"Whether this client conforms to strict OIDC specifications (true) or uses legacy features (false)."}),auth0_conformant:h().default(!0).openapi({description:"Whether this client follows Auth0-compatible behavior (true) or strict OIDC behavior (false). When true, profile/email claims are included in the ID token when scopes are requested. When false, these claims are only available from the userinfo endpoint (strict OIDC 5.4 compliance)."}),callbacks:b(o()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:b(o()).default([]).optional().openapi({description:"Comma-separated list of URLs allowed to make requests from JavaScript to Auth0 API (typically used with CORS). By default, all your callback URLs will be allowed. This field allows you to enter other origins if necessary. You can also use wildcards at the subdomain level (e.g., https://*.contoso.com). Query strings and hash information are not taken into account when validating these URLs."}),web_origins:b(o()).default([]).optional().openapi({description:"Comma-separated list of allowed origins for use with Cross-Origin Authentication, Device Flow, and web message response mode."}),client_aliases:b(o()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:b(o()).default([]).optional().openapi({description:"List of allow clients and API ids that are allowed to make delegation requests. Empty means all all your clients are allowed."}),connections:b(o()).default([]).optional().openapi({description:"List of connection IDs enabled for this client. The order determines the display order on the login page."}),allowed_logout_urls:b(o()).default([]).optional().openapi({description:"Comma-separated list of URLs that are valid to redirect to after logout from Auth0. Wildcards are allowed for subdomains."}),session_transfer:P(j()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:P(j()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:b(o()).default([]).optional().openapi({description:"List of grant types supported for this application. Can include authorization_code, implicit, refresh_token, client_credentials, password, http://auth0.com/oauth/grant-type/password-realm, http://auth0.com/oauth/grant-type/mfa-oob, http://auth0.com/oauth/grant-type/mfa-otp, http://auth0.com/oauth/grant-type/mfa-recovery-code, urn:openid:params:grant-type:ciba, and urn:ietf:params:oauth:grant-type:device_code."}),jwt_configuration:P(j()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:b(P(j())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:P(j()).default({}).optional().openapi({description:"Encryption used for WsFed responses with this client."}),sso:h().default(!1).openapi({description:"Applies only to SSO clients and determines whether Auth0 will handle Single Sign On (true) or whether the Identity Provider will (false)."}),sso_disabled:h().default(!1).openapi({description:"Whether Single Sign On is disabled for this client. When true, existing SSO sessions will not be reused and users must authenticate every time."}),cross_origin_authentication:h().default(!1).openapi({description:"Whether this client can be used to make cross-origin authentication requests (true) or it is not allowed to make such requests (false)."}),cross_origin_loc:o().url().optional().openapi({description:"URL of the location in your site where the cross origin verification takes place for the cross-origin auth flow when performing Auth in your own domain instead of Auth0 hosted login page."}),custom_login_page_on:h().default(!1).openapi({description:"Whether a custom login page is to be used (true) or the default provided login page (false)."}),custom_login_page:o().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:o().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:o().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:P(j()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:k(["none","client_secret_post","client_secret_basic"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. Can be none (public client without a client secret), client_secret_post (client uses HTTP POST parameters), or client_secret_basic (client uses HTTP Basic)."}),client_metadata:P(o().max(255)).default({}).optional().openapi({description:'Metadata associated with the client, in the form of an object with string values (max 255 chars). Maximum of 10 metadata properties allowed. Field names (max 255 chars) are alphanumeric and may only include the following special characters: :,-+=_*?"/()<>@ [Tab][Space]'}),mobile:P(j()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:o().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:P(j()).default({}).optional(),refresh_token:P(j()).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:P(j()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:k(["deny","allow","require"]).default("deny").optional().openapi({description:"Defines how to proceed during an authentication transaction with regards an organization. Can be deny (default), allow or require."}),organization_require_behavior:k(["no_prompt","pre_login_prompt","post_login_prompt"]).default("no_prompt").optional().openapi({description:"Defines how to proceed during an authentication transaction when client.organization_usage: 'require'. Can be no_prompt (default), pre_login_prompt or post_login_prompt. post_login_prompt requires oidc_conformant: true."}),client_authentication_methods:P(j()).default({}).optional().openapi({description:"Defines client authentication methods."}),require_pushed_authorization_requests:h().default(!1).openapi({description:"Makes the use of Pushed Authorization Requests mandatory for this client"}),require_proof_of_possession:h().default(!1).openapi({description:"Makes the use of Proof-of-Possession mandatory for this client"}),signed_request_object:P(j()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:k(["none","fapi1_adv_pkj_par","fapi1_adv_mtls_par","fapi2_sp_pkj_mtls","fapi2_sp_mtls_mtls"]).optional().openapi({description:"Defines the compliance level for this client, which may restrict it's capabilities"}),par_request_expiry:I().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:P(j()).default({}).optional(),owner_user_id:o().optional().openapi({description:"User ID of the consenting user when this client was created via IAT-gated Dynamic Client Registration. NULL for clients created via the Management API or open DCR."}),registration_type:k(["manual","open_dcr","iat_dcr"]).optional().openapi({description:"Provenance of this client. `manual` = Management API; `open_dcr` = RFC 7591 without IAT; `iat_dcr` = RFC 7591 with an Initial Access Token."}),registration_metadata:P(j()).default({}).optional().openapi({description:"Arbitrary metadata captured at Dynamic Client Registration time that isn't a first-class client field (e.g. integration_type, domain). Also stores `iat_constraints` for clients created via IAT so RFC 7592 PUT can enforce field immutability."})});_({created_at:o(),updated_at:o(),...cl.shape});const _l=_({client_id:o().min(1).openapi({description:"ID of the client."}),audience:o().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:b(o()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:k(["deny","allow","require"]).optional().openapi({description:"Defines whether organizations can be used with client credentials exchanges for this grant."}),allow_any_organization:h().optional().openapi({description:"If enabled, any organization can be used with this grant. If disabled (default), the grant must be explicitly assigned to the desired organizations."}),is_system:h().optional().openapi({description:"If enabled, this grant is a special grant created by Auth0. It cannot be modified or deleted directly."}),subject_type:k(["client","user"]).optional().openapi({description:"The type of application access the client grant allows. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."}),authorization_details_types:b(o()).optional().openapi({description:"Types of authorization_details allowed for this client grant. Use of this field is subject to the applicable Free Trial terms in Okta's Master Subscription Agreement."})}),ul=_({id:o().openapi({description:"ID of the client grant."}),..._l.shape,created_at:o().optional(),updated_at:o().optional()});b(ul);const fr=k(["iat","rat"]),pl=_({id:o(),token_hash:o(),type:fr,client_id:o().optional(),sub:o().optional(),constraints:P(at()).optional(),single_use:h().default(!1),expires_at:o().optional()});_({created_at:o(),used_at:o().optional(),revoked_at:o().optional(),...pl.shape});const Ot=_({x:I(),y:I()});var hr=(n=>(n.RICH_TEXT="RICH_TEXT",n.NEXT_BUTTON="NEXT_BUTTON",n.BACK_BUTTON="BACK_BUTTON",n.SUBMIT_BUTTON="SUBMIT_BUTTON",n.DIVIDER="DIVIDER",n.TEXT="TEXT",n.EMAIL="EMAIL",n.PASSWORD="PASSWORD",n.NUMBER="NUMBER",n.PHONE="PHONE",n.DATE="DATE",n.CHECKBOX="CHECKBOX",n.RADIO="RADIO",n.SELECT="SELECT",n.HIDDEN="HIDDEN",n.LEGAL="LEGAL",n))(hr||{}),gr=(n=>(n.BLOCK="BLOCK",n.FIELD="FIELD",n))(gr||{});const yn=_({id:o(),category:gt(gr),type:gt(hr)}),fl=yn.extend({category:O("BLOCK"),type:O("RICH_TEXT"),config:_({content:o()}).passthrough()}),hl=yn.extend({category:O("BLOCK"),type:Pe([O("NEXT_BUTTON"),O("BACK_BUTTON"),O("SUBMIT_BUTTON")]),config:_({text:o()}).passthrough()}),gl=yn.extend({category:O("FIELD"),type:O("LEGAL"),required:h().optional(),sensitive:h().optional(),config:_({text:o()}).passthrough()}),ml=yn.extend({category:O("FIELD"),type:Pe([O("TEXT"),O("EMAIL"),O("PASSWORD"),O("NUMBER"),O("PHONE"),O("DATE"),O("CHECKBOX"),O("RADIO"),O("SELECT"),O("HIDDEN")]),required:h().optional(),sensitive:h().optional(),config:_({label:o().optional(),placeholder:o().optional()}).passthrough()}),yl=_({id:o(),category:o(),type:o()}).passthrough(),vl=Pe([fl,hl,gl,ml,yl]),wl=_({id:o(),type:O("STEP"),coordinates:Ot,alias:o().optional(),config:_({components:b(vl),next_node:o()}).passthrough()}),Sl=_({id:o(),type:O("FLOW"),coordinates:Ot,alias:o().optional(),config:_({flow_id:o(),next_node:o()})}),Nl=_({id:o(),type:O("ACTION"),coordinates:Ot,alias:o().optional(),config:_({action_type:k(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:k(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:o().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:o().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),bl=_({id:o(),type:o(),coordinates:Ot}).passthrough(),El=Pe([wl,Sl,Nl,bl]),xl=_({next_node:o(),coordinates:Ot}).passthrough(),kl=_({resume_flow:h().optional(),coordinates:Ot}).passthrough(),Ol=_({id:o(),name:o(),languages:_({primary:o()}).passthrough(),nodes:b(El),start:xl,ending:kl,created_at:o(),updated_at:o(),links:_({sdkSrc:o().optional(),sdk_src:o().optional()}).passthrough()}).passthrough();Ol.omit({id:!0,created_at:!0,updated_at:!0});var mr=(n=>(n.TOKEN="token",n.ID_TOKEN="id_token",n.TOKEN_ID_TOKEN="token id_token",n.CODE="code",n))(mr||{}),yr=(n=>(n.QUERY="query",n.FRAGMENT="fragment",n.FORM_POST="form_post",n.WEB_MESSAGE="web_message",n.SAML_POST="saml_post",n))(yr||{}),vr=(n=>(n.S256="S256",n.Plain="plain",n))(vr||{});const Tl=_({client_id:o(),act_as:o().optional(),response_type:gt(mr).optional(),response_mode:gt(yr).optional(),redirect_uri:o().optional(),audience:o().optional(),organization:o().optional(),state:o().optional(),nonce:o().optional(),scope:o().optional(),prompt:o().optional(),code_challenge_method:gt(vr).optional(),code_challenge:o().optional(),username:o().optional(),ui_locales:o().optional(),max_age:I().optional(),acr_values:o().optional(),vendor_id:o().optional()});_({colors:_({primary:o(),page_background:_({type:o().optional(),start:o().optional(),end:o().optional(),angle_deg:I().optional()}).optional()}).optional(),logo_url:o().optional(),favicon_url:o().optional(),powered_by_logo_url:o().optional(),font:_({url:o()}).optional()});const Al=k(["password_reset","email_verification","otp","mfa_otp","authorization_code","oauth2_state","ticket"]),Il=_({code_id:o().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:o().openapi({description:"The id of the login session that the code is connected to"}),connection_id:o().optional().openapi({description:"The connection that the code is connected to"}),code_type:Al,code_verifier:o().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:o().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:k(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:o().optional().openapi({description:"The redirect URI associated with the code"}),otp:o().optional().openapi({description:"The one-time password value for OTP-based flows"}),nonce:o().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:o().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:o(),used_at:o().optional(),user_id:o().optional()});_({...Il.shape,created_at:o()});const Cl=_({kid:o().optional(),team_id:o().optional(),realms:o().optional(),authentication_method:o().optional(),client_id:o().optional(),client_secret:o().optional(),app_secret:o().optional(),scope:o().optional(),authorization_endpoint:o().optional(),token_endpoint:o().optional(),userinfo_endpoint:o().optional(),jwks_uri:o().optional(),discovery_url:o().optional(),issuer:o().optional(),provider:o().optional(),from:o().optional(),twilio_sid:o().optional(),twilio_token:o().optional(),icon_url:o().optional(),passwordPolicy:k(["none","low","fair","good","excellent"]).optional(),password_complexity_options:_({min_length:I().optional()}).optional(),password_history:_({enable:h().optional(),size:I().optional()}).optional(),password_no_personal_info:_({enable:h().optional()}).optional(),password_dictionary:_({enable:h().optional(),dictionary:b(o()).optional()}).optional(),disable_signup:h().optional(),brute_force_protection:h().optional(),import_mode:h().optional(),attributes:_({email:_({identifier:_({active:h().optional()}).optional(),signup:_({status:k(["required","optional","disabled"]).optional(),verification:_({active:h().optional()}).optional()}).optional(),validation:_({allowed:h().optional()}).optional(),unique:h().optional(),profile_required:h().optional(),verification_method:k(["link","code"]).optional()}).optional(),username:_({identifier:_({active:h().optional()}).optional(),signup:_({status:k(["required","optional","disabled"]).optional()}).optional(),validation:_({max_length:I().optional(),min_length:I().optional(),allowed_types:_({email:h().optional(),phone_number:h().optional()}).optional()}).optional(),profile_required:h().optional()}).optional(),phone_number:_({identifier:_({active:h().optional()}).optional(),signup:_({status:k(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:_({password:_({enabled:h().optional()}).optional(),passkey:_({enabled:h().optional()}).optional()}).optional(),passkey_options:_({challenge_ui:k(["both","autofill","button"]).optional(),local_enrollment_enabled:h().optional(),progressive_enrollment_enabled:h().optional()}).optional(),requires_username:h().optional(),validation:_({username:_({min:I().optional(),max:I().optional()}).optional()}).optional(),set_user_root_attributes:k(["on_each_login","on_first_login","never_on_login"]).optional()}),Dl=_({id:o().optional(),name:o(),display_name:o().optional(),strategy:o(),options:Cl.default({}),enabled_clients:b(o()).default([]).optional(),response_type:ri().optional(),response_mode:ri().optional(),is_domain_connection:h().optional(),show_as_button:h().optional(),metadata:P(j()).optional(),is_system:h().optional()});_({id:o(),created_at:o().transform(n=>n===null?"":n),updated_at:o().transform(n=>n===null?"":n)}).extend(Dl.shape);const Ll=_({domain:o(),custom_domain_id:o().optional(),type:k(["auth0_managed_certs","self_managed_certs"]),verification_method:k(["txt"]).optional(),tls_policy:k(["recommended"]).optional(),custom_client_ip_header:k(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:P(o().max(255)).optional()}),Rl=kt("name",[_({name:O("txt"),record:o(),domain:o()}),_({name:O("http"),http_body:o(),http_url:o()})]),Ul=_({...Ll.shape,custom_domain_id:o(),primary:h(),status:k(["disabled","pending","pending_verification","ready"]),origin_domain_name:o().optional(),verification:_({methods:b(Rl)}).optional(),tls_policy:o().optional()});Ul.extend({tenant_id:o()});const vi=_({id:o(),order:I().optional(),visible:h().optional().default(!0)}),ct=vi.extend({category:O("BLOCK").optional()}),zl=ct.extend({type:O("DIVIDER"),config:_({text:o().optional()}).optional()}),Fl=ct.extend({type:O("HTML"),config:_({content:o().optional()}).optional()}),Pl=ct.extend({type:O("IMAGE"),config:_({src:o().optional(),alt:o().optional(),width:I().optional(),height:I().optional()}).optional()}),Ml=ct.extend({type:O("JUMP_BUTTON"),config:_({text:o().optional(),target_step:o().optional()})}),ql=ct.extend({type:O("RESEND_BUTTON"),config:_({text:o().optional(),resend_action:o().optional()})}),Bl=ct.extend({type:O("NEXT_BUTTON"),config:_({text:o().optional()})}),$l=ct.extend({type:O("PREVIOUS_BUTTON"),config:_({text:o().optional()})}),jl=ct.extend({type:O("RICH_TEXT"),config:_({content:o().optional()}).optional()}),wi=vi.extend({category:O("WIDGET").optional(),label:o().min(1).optional(),hint:o().min(1).max(500).optional(),required:h().optional(),sensitive:h().optional()}),Vl=wi.extend({type:O("AUTH0_VERIFIABLE_CREDENTIALS"),config:_({credential_type:o().optional()})}),Zl=wi.extend({type:O("GMAPS_ADDRESS"),config:_({api_key:o().optional()})}),Hl=wi.extend({type:O("RECAPTCHA"),config:_({site_key:o().optional()})}),Ne=vi.extend({category:O("FIELD").optional(),label:o().min(1).optional(),hint:o().min(1).max(500).optional(),messages:b(_({id:I().optional(),text:o(),type:k(["info","error","success","warning"])})).optional(),required:h().optional(),sensitive:h().optional()}),Kl=Ne.extend({type:O("BOOLEAN"),config:_({default_value:h().optional()}).optional()}),Ql=Ne.extend({type:O("CARDS"),config:_({options:b(_({value:o(),label:o(),description:o().optional(),image:o().optional()})).optional(),multi_select:h().optional()}).optional()}),Gl=Ne.extend({type:O("CHOICE"),config:_({options:b(_({value:o(),label:o()})).optional(),display:k(["radio","checkbox"]).optional(),multiple:h().optional(),default_value:Pe([o(),b(o())]).optional()}).optional()}),Jl=Ne.extend({type:O("CUSTOM"),config:_({component:o().optional(),props:P(j()).optional(),schema:P(j()).optional(),code:o().optional()})}),Wl=Ne.extend({type:O("DATE"),config:_({format:o().optional(),min:o().optional(),max:o().optional(),default_value:o().optional()}).optional()}),Xl=Ne.extend({type:O("DROPDOWN"),config:_({options:b(_({value:o(),label:o()})).optional(),placeholder:o().optional(),searchable:h().optional(),multiple:h().optional(),default_value:Pe([o(),b(o())]).optional()}).optional()}),Yl=Ne.extend({type:O("EMAIL"),config:_({placeholder:o().optional(),default_value:o().optional()}).optional()}),ed=Ne.extend({type:O("FILE"),config:_({accept:o().optional(),max_size:I().optional(),multiple:h().optional()}).optional()}),td=Ne.extend({type:O("LEGAL"),config:_({text:o(),html:h().optional()}).optional()}),nd=Ne.extend({type:O("NUMBER"),config:_({placeholder:o().optional(),min:I().optional(),max:I().optional(),step:I().optional(),default_value:o().optional()}).optional()}),id=Ne.extend({type:O("PASSWORD"),config:_({placeholder:o().optional(),min_length:I().optional(),show_toggle:h().optional(),forgot_password_link:o().optional(),default_value:o().optional()}).optional()}),ad=Ne.extend({type:O("PAYMENT"),config:_({provider:o().optional(),currency:o().optional()}).optional()}),od=Ne.extend({type:O("SOCIAL"),config:_({providers:b(o()).optional(),provider_details:b(_({name:o(),strategy:o().optional(),display_name:o().optional(),icon_url:o().optional(),href:o().optional()})).optional()}).optional()}),rd=Ne.extend({type:O("TEL"),config:_({placeholder:o().optional(),default_country:o().optional(),default_value:o().optional(),allow_email:h().optional()}).optional()}),sd=Ne.extend({type:O("TEXT"),config:_({placeholder:o().optional(),multiline:h().optional(),max_length:I().optional(),default_value:o().optional()}).optional()}),ld=Ne.extend({type:O("COUNTRY"),config:_({placeholder:o().optional(),default_value:o().optional()}).optional()}),dd=Ne.extend({type:O("URL"),config:_({placeholder:o().optional(),default_value:o().optional()}).optional()}),cd=kt("type",[zl,Fl,Pl,Ml,ql,Bl,$l,jl]),_d=kt("type",[Vl,Zl,Hl]),ud=kt("type",[Kl,Ql,Gl,ld,Jl,Wl,Xl,Yl,ed,td,nd,id,ad,od,rd,sd,dd]),wr=Pe([cd,_d,ud]);_({id:o(),type:O("submit"),label:o(),className:o().optional(),disabled:h().optional().default(!1),order:I().optional(),visible:h().optional().default(!0),customizations:P(o(),j()).optional()});const Kt=_({x:I(),y:I()}),pd=_({id:o(),type:O("FLOW"),coordinates:Kt,alias:o().min(1).max(150).optional(),config:_({flow_id:o().max(30),next_node:o().optional()})}),fd=_({id:o(),type:O("ROUTER"),coordinates:Kt,alias:o().min(1).max(150),config:_({rules:b(_({id:o(),alias:o().min(1).max(150).optional(),condition:j(),next_node:o()})),fallback:o()})}),hd=_({id:o(),type:O("STEP"),coordinates:Kt,alias:o().min(1).max(150).optional(),config:_({components:b(wr),next_node:o().optional()})}),gd=kt("type",[pd,fd,hd]),md=_({name:o().openapi({description:"The name of the form"}),messages:_({errors:P(o(),j()).optional(),custom:P(o(),j()).optional()}).optional(),languages:_({primary:o().optional(),default:o().optional()}).optional(),translations:P(o(),j()).optional(),nodes:b(gd).optional(),start:_({hidden_fields:b(_({key:o(),value:o()})).optional(),next_node:o().optional(),coordinates:Kt.optional()}).optional(),ending:_({redirection:_({delay:I().optional(),target:o().optional()}).optional(),after_submit:_({flow_id:o().optional()}).optional(),coordinates:Kt.optional(),resume_flow:h().optional()}).optional(),style:_({css:o().optional()}).optional(),links:_({sdkSrc:o().optional(),sdk_src:o().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"});_({...Ve.shape,...md.shape,id:o()});const yd=_({id:I().optional(),text:o(),type:k(["info","error","success","warning"])}),vd=_({id:o().optional(),text:o(),href:o(),linkText:o().optional()});_({name:o().optional(),action:o(),method:k(["POST","GET"]),title:o().optional(),description:o().optional(),components:b(wr),messages:b(yd).optional(),links:b(vd).optional(),footer:o().optional()});const Sr=k(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Nr=k(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),br=k(["post-user-login","credentials-exchange"]),Er=k(["post-user-login","credentials-exchange","pre-user-registration","post-user-registration"]),xr=k(["ensure-username","set-preferred-username"]),_t={enabled:h().default(!1),synchronous:h().default(!1),priority:I().optional(),hook_id:o().optional()},wd=_({..._t,trigger_id:Sr,url:o()}),Sd=_({..._t,trigger_id:Nr,form_id:o()}),Nd=_({..._t,trigger_id:br,template_id:xr}),bd=_({..._t,trigger_id:Er,code_id:o()});Pe([wd,Sd,Nd,bd]);const Ed=_({..._t,trigger_id:Sr,...Ve.shape,hook_id:o(),url:o()}),xd=_({..._t,trigger_id:Nr,...Ve.shape,hook_id:o(),form_id:o()}),kd=_({..._t,trigger_id:br,...Ve.shape,hook_id:o(),template_id:xr}),Od=_({..._t,trigger_id:Er,...Ve.shape,hook_id:o(),code_id:o()});Pe([Ed,xd,kd,Od]);const Td=_({code:o().max(1e5),secrets:P(o()).optional()});Td.extend({id:o(),tenant_id:o(),...Ve.shape});const Ad=_({name:o().optional()}),Id=_({email:o().optional()}),Cd=_({organization_id:o().max(50),inviter:Ad,invitee:Id,invitation_url:o().url(),client_id:o(),connection_id:o().optional(),app_metadata:P(j()).default({}).optional(),user_metadata:P(j()).default({}).optional(),ttl_sec:I().int().max(2592e3).default(604800).optional(),roles:b(o()).default([]).optional(),send_invitation_email:h().default(!0).optional()});_({id:o(),organization_id:o().max(50),created_at:o().datetime(),expires_at:o().datetime(),ticket_id:o().optional()}).extend(Cd.shape);const Dd=_({alg:k(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),e:o(),kid:o(),kty:k(["RSA","EC","oct"]),n:o(),x5t:o().optional(),x5c:b(o()).optional(),use:k(["sig","enc"]).optional()});_({keys:b(Dd)});_({issuer:o(),authorization_endpoint:o(),token_endpoint:o(),device_authorization_endpoint:o(),userinfo_endpoint:o(),mfa_challenge_endpoint:o(),jwks_uri:o(),registration_endpoint:o().optional(),revocation_endpoint:o(),scopes_supported:b(o()),response_types_supported:b(o()),code_challenge_methods_supported:b(o()),response_modes_supported:b(o()),subject_types_supported:b(o()),id_token_signing_alg_values_supported:b(o()),token_endpoint_auth_methods_supported:b(o()),claims_supported:b(o()),request_uri_parameter_supported:h(),request_parameter_supported:h(),token_endpoint_auth_signing_alg_values_supported:b(o())});var kr=(n=>(n.PENDING="pending",n.AUTHENTICATED="authenticated",n.AWAITING_EMAIL_VERIFICATION="awaiting_email_verification",n.AWAITING_MFA="awaiting_mfa",n.AWAITING_HOOK="awaiting_hook",n.AWAITING_CONTINUATION="awaiting_continuation",n.COMPLETED="completed",n.FAILED="failed",n.EXPIRED="expired",n))(kr||{});const Ld=gt(kr),Rd=_({strategy:o(),strategy_type:o()}),Ud=_({csrf_token:o(),auth0Client:o().optional(),authParams:Tl,expires_at:o(),deleted_at:o().optional(),ip:o().optional(),useragent:o().optional(),session_id:o().optional(),authorization_url:o().optional(),state:Ld.optional().default("pending"),state_data:o().optional(),failure_reason:o().optional(),user_id:o().optional(),auth_connection:o().optional(),auth_strategy:Rd.optional(),authenticated_at:o().optional()}).openapi({description:"This represents a login sesion"});_({...Ud.shape,id:o().openapi({description:"This is is used as the state in the universal login"}),created_at:o(),updated_at:o()});const zd={ACLS_SUMMARY:"acls_summary",ACTIONS_EXECUTION_FAILED:"actions_execution_failed",API_LIMIT:"api_limit",API_LIMIT_WARNING:"api_limit_warning",APPI:"appi",CIBA_EXCHANGE_FAILED:"ciba_exchange_failed",CIBA_EXCHANGE_SUCCEEDED:"ciba_exchange_succeeded",CIBA_START_FAILED:"ciba_start_failed",CIBA_START_SUCCEEDED:"ciba_start_succeeded",CODE_LINK_SENT:"cls",CODE_SENT:"cs",DEPRECATION_NOTICE:"depnote",FAILED_LOGIN:"f",FAILED_BY_CONNECTOR:"fc",FAILED_CHANGE_EMAIL:"fce",FAILED_BY_CORS:"fco",FAILED_CROSS_ORIGIN_AUTHENTICATION:"fcoa",FAILED_CHANGE_PASSWORD:"fcp",FAILED_POST_CHANGE_PASSWORD_HOOK:"fcph",FAILED_CHANGE_PHONE_NUMBER:"fcpn",FAILED_CHANGE_PASSWORD_REQUEST:"fcpr",FAILED_CONNECTOR_PROVISIONING:"fcpro",FAILED_CHANGE_USERNAME:"fcu",FAILED_DELEGATION:"fd",FAILED_DEVICE_ACTIVATION:"fdeac",FAILED_DEVICE_AUTHORIZATION_REQUEST:"fdeaz",USER_CANCELED_DEVICE_CONFIRMATION:"fdecc",FAILED_USER_DELETION:"fdu",FAILED_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"feacft",FAILED_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"feccft",FAILED_EXCHANGE_CUSTOM_TOKEN:"fecte",FAILED_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"fede",FAILED_FEDERATED_LOGOUT:"federated_logout_failed",FAILED_EXCHANGE_NATIVE_SOCIAL_LOGIN:"fens",FAILED_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"feoobft",FAILED_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"feotpft",FAILED_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"fepft",FAILED_EXCHANGE_PASSWORDLESS_OTP_FOR_ACCESS_TOKEN:"fepotpft",FAILED_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"fercft",FAILED_EXCHANGE_ROTATING_REFRESH_TOKEN:"ferrt",FAILED_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"fertft",FAILED_HOOK:"fh",FAILED_IMPERSONATION:"fimp",FAILED_INVITE_ACCEPT:"fi",FAILED_LOGOUT:"flo",FLOWS_EXECUTION_COMPLETED:"flows_execution_completed",FLOWS_EXECUTION_FAILED:"flows_execution_failed",FAILED_SENDING_NOTIFICATION:"fn",FORMS_SUBMISSION_FAILED:"forms_submission_failed",FORMS_SUBMISSION_SUCCEEDED:"forms_submission_succeeded",FAILED_LOGIN_INCORRECT_PASSWORD:"fp",FAILED_PUSHED_AUTHORIZATION_REQUEST:"fpar",FAILED_POST_USER_REGISTRATION_HOOK:"fpurh",FAILED_SIGNUP:"fs",FAILED_SILENT_AUTH:"fsa",FAILED_LOGIN_INVALID_EMAIL_USERNAME:"fu",FAILED_USERS_IMPORT:"fui",FAILED_VERIFICATION_EMAIL:"fv",FAILED_VERIFICATION_EMAIL_REQUEST:"fvr",EMAIL_VERIFICATION_CONFIRMED:"gd_auth_email_verification",EMAIL_VERIFICATION_FAILED:"gd_auth_fail_email_verification",MFA_AUTH_FAILED:"gd_auth_failed",MFA_AUTH_REJECTED:"gd_auth_rejected",MFA_AUTH_SUCCESS:"gd_auth_succeed",MFA_ENROLLMENT_COMPLETE:"gd_enrollment_complete",TOO_MANY_MFA_FAILURES:"gd_otp_rate_limit_exceed",MFA_RECOVERY_FAILED:"gd_recovery_failed",MFA_RECOVERY_RATE_LIMIT_EXCEED:"gd_recovery_rate_limit_exceed",MFA_RECOVERY_SUCCESS:"gd_recovery_succeed",MFA_EMAIL_SENT:"gd_send_email",EMAIL_VERIFICATION_SENT:"gd_send_email_verification",EMAIL_VERIFICATION_SEND_FAILURE:"gd_send_email_verification_failure",PUSH_NOTIFICATION_SENT:"gd_send_pn",ERROR_SENDING_MFA_PUSH_NOTIFICATION:"gd_send_pn_failure",MFA_SMS_SENT:"gd_send_sms",ERROR_SENDING_MFA_SMS:"gd_send_sms_failure",MFA_VOICE_CALL_SUCCESS:"gd_send_voice",MFA_VOICE_CALL_FAILED:"gd_send_voice_failure",SECOND_FACTOR_STARTED:"gd_start_auth",MFA_ENROLL_STARTED:"gd_start_enroll",MFA_ENROLLMENT_FAILED:"gd_start_enroll_failed",GUARDIAN_TENANT_UPDATE:"gd_tenant_update",UNENROLL_DEVICE_ACCOUNT:"gd_unenroll",UPDATE_DEVICE_ACCOUNT:"gd_update_device_account",WEBAUTHN_CHALLENGE_FAILED:"gd_webauthn_challenge_failed",WEBAUTHN_ENROLLMENT_FAILED:"gd_webauthn_enrollment_failed",FAILED_KMS_API_OPERATION:"kms_key_management_failure",SUCCESS_KMS_API_OPERATION:"kms_key_management_success",KMS_KEY_STATE_CHANGED:"kms_key_state_changed",TOO_MANY_CALLS_TO_DELEGATION:"limit_delegation",BLOCKED_IP_ADDRESS:"limit_mu",BLOCKED_ACCOUNT_IP:"limit_sul",BLOCKED_ACCOUNT_EMAIL:"limit_wc",MFA_REQUIRED:"mfar",MANAGEMENT_API_READ_OPERATION:"mgmt_api_read",FAILED_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_failed",SUCCESSFUL_AUTHENTICATION_METHOD_OPERATION_MY_ACCOUNT:"my_account_authentication_method_succeeded",FAILED_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_failed",SUCCESSFUL_OIDC_BACKCHANNEL_LOGOUT:"oidc_backchannel_logout_succeeded",ORGANIZATION_MEMBER_ADDED:"organization_member_added",PASSKEY_CHALLENGE_FAILED:"passkey_challenge_failed",PASSKEY_CHALLENGE_STARTED:"passkey_challenge_started",PRE_LOGIN_ASSESSMENT:"pla",BREACHED_PASSWORD:"pwd_leak",BREACHED_PASSWORD_ON_RESET:"reset_pwd_leak",SUCCESS_RESOURCE_CLEANUP:"resource_cleanup",RICH_CONSENTS_ACCESS_ERROR:"rich_consents_access_error",SUCCESS_LOGIN:"s",SUCCESS_API_OPERATION:"sapi",FAILED_API_OPERATION:"fapi",SUCCESS_CHANGE_EMAIL:"sce",SUCCESS_CROSS_ORIGIN_AUTHENTICATION:"scoa",SUCCESS_CHANGE_PASSWORD:"scp",SUCCESS_CHANGE_PHONE_NUMBER:"scpn",SUCCESS_CHANGE_PASSWORD_REQUEST:"scpr",SUCCESS_CHANGE_USERNAME:"scu",SUCCESS_CREDENTIAL_VALIDATION:"scv",SUCCESS_DELEGATION:"sd",SUCCESS_USER_DELETION:"sdu",SUCCESS_EXCHANGE_AUTHORIZATION_CODE_FOR_ACCESS_TOKEN:"seacft",SUCCESS_EXCHANGE_ACCESS_TOKEN_FOR_CLIENT_CREDENTIALS:"seccft",SUCCESS_EXCHANGE_CUSTOM_TOKEN:"secte",SUCCESS_EXCHANGE_DEVICE_CODE_FOR_ACCESS_TOKEN:"sede",SUCCESS_EXCHANGE_NATIVE_SOCIAL_LOGIN:"sens",SUCCESS_EXCHANGE_PASSWORD_OOB_FOR_ACCESS_TOKEN:"seoobft",SUCCESS_EXCHANGE_PASSWORD_OTP_FOR_ACCESS_TOKEN:"seotpft",SUCCESS_EXCHANGE_PASSWORD_FOR_ACCESS_TOKEN:"sepft",SUCCESS_EXCHANGE_PASSKEY_OOB_FOR_ACCESS_TOKEN:"sepkoobft",SUCCESS_EXCHANGE_PASSKEY_OTP_FOR_ACCESS_TOKEN:"sepkotpft",SUCCESS_EXCHANGE_PASSKEY_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sepkrcft",SUCCESS_EXCHANGE_PASSWORD_MFA_RECOVERY_FOR_ACCESS_TOKEN:"sercft",SUCCESS_EXCHANGE_REFRESH_TOKEN_FOR_ACCESS_TOKEN:"sertft",SUCCESS_IMPERSONATION:"simp",SUCCESSFULLY_ACCEPTED_USER_INVITE:"si",BREACHED_PASSWORD_ON_SIGNUP:"signup_pwd_leak",SUCCESS_LOGOUT:"slo",SUCCESS_REVOCATION:"srrt",SUCCESS_SIGNUP:"ss",FAILED_SS_SSO_OPERATION:"ss_sso_failure",INFORMATION_FROM_SS_SSO_OPERATION:"ss_sso_info",SUCCESS_SS_SSO_OPERATION:"ss_sso_success",SUCCESS_SILENT_AUTH:"ssa",SUCCESSFUL_SCIM_OPERATION:"sscim",SUCCESSFULLY_IMPORTED_USERS:"sui",SUCCESS_VERIFICATION_EMAIL:"sv",SUCCESS_VERIFICATION_EMAIL_REQUEST:"svr",MAX_AMOUNT_OF_AUTHENTICATORS:"too_many_records",USER_LOGIN_BLOCK_RELEASED:"ublkdu",FAILED_UNIVERSAL_LOGOUT:"universal_logout_failed",SUCCESSFUL_UNIVERSAL_LOGOUT:"universal_logout_succeeded",WARNING_DURING_LOGIN:"w",WARNING_SENDING_NOTIFICATION:"wn",WARNING_USER_MANAGEMENT:"wum"},Fd=o().refine(n=>Object.values(zd).includes(n),{message:"Invalid log type"}),Pd=_({name:o(),version:o(),env:_({node:o().optional()}).optional()}),Md=_({country_code:o().length(2),city_name:o(),latitude:o(),longitude:o(),time_zone:o(),continent_code:o()}),qd=_({type:Fd,date:o(),description:o().optional(),ip:o().optional(),user_agent:o().optional(),details:j().optional(),isMobile:h(),user_id:o().optional(),user_name:o().optional(),connection:o().optional(),connection_id:o().optional(),client_id:o().optional(),client_name:o().optional(),audience:o().optional(),scope:o().optional(),strategy:o().optional(),strategy_type:o().optional(),hostname:o().optional(),auth0_client:Pd.optional(),log_id:o().optional(),location_info:Md.optional()});_({...qd.shape,log_id:o()});const Bd=_({id:o().optional(),user_id:o(),password:o(),algorithm:k(["bcrypt","argon2id"]).default("argon2id"),is_current:h().default(!0)});Bd.extend({id:o(),created_at:o(),updated_at:o()});const Or=_({initial_user_agent:o().describe("First user agent of the device from which this user logged in"),initial_ip:o().describe("First IP address associated with this session"),initial_asn:o().describe("First autonomous system number associated with this session"),last_user_agent:o().describe("Last user agent of the device from which this user logged in"),last_ip:o().describe("Last IP address from which this user logged in"),last_asn:o().describe("Last autonomous system number from which this user logged in")}),$d=_({id:o(),revoked_at:o().optional(),used_at:o().optional(),user_id:o().describe("The user ID associated with the session"),expires_at:o().optional(),login_session_id:o(),idle_expires_at:o().optional(),device:Or.describe("Metadata related to the device used in the session"),clients:b(o()).describe("List of client details for the session")});_({created_at:o(),updated_at:o(),authenticated_at:o(),last_interaction_at:o(),...$d.shape});_({kid:o().openapi({description:"The key id of the signing key"}),cert:o().openapi({description:"The public certificate of the signing key"}),fingerprint:o().openapi({description:"The cert fingerprint"}),thumbprint:o().openapi({description:"The cert thumbprint"}),pkcs7:o().optional().openapi({description:"The private key in pkcs7 format"}),current:h().optional().openapi({description:"True if the key is the current key"}),next:h().optional().openapi({description:"True if the key is the next key"}),previous:h().optional().openapi({description:"True if the key is the previous key"}),current_since:o().optional().openapi({description:"The date and time when the key became the current key"}),current_until:o().optional().openapi({description:"The date and time when the current key was rotated"}),revoked:h().optional().openapi({description:"True if the key is revoked"}),revoked_at:o().optional().openapi({description:"The date and time when the key was revoked"}),connection:o().optional().openapi({description:"The connection identifier associated with the key"}),type:k(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})});const jd=_({id:o().optional(),audience:o(),friendly_name:o(),picture_url:o().optional(),support_email:o().optional(),support_url:o().optional(),sender_email:o().email(),sender_name:o(),session_lifetime:I().optional(),idle_session_lifetime:I().optional(),ephemeral_session_lifetime:I().optional(),idle_ephemeral_session_lifetime:I().optional(),session_cookie:_({mode:k(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:b(o()).optional(),default_redirection_uri:o().optional(),enabled_locales:b(o()).optional(),default_directory:o().optional(),error_page:_({html:o().optional(),show_log_link:h().optional(),url:o().optional()}).optional(),flags:_({allow_changing_enable_sso:h().optional(),allow_legacy_delegation_grant_types:h().optional(),allow_legacy_ro_grant_types:h().optional(),allow_legacy_tokeninfo_endpoint:h().optional(),change_pwd_flow_v1:h().optional(),custom_domains_provisioning:h().optional(),dashboard_insights_view:h().optional(),dashboard_log_streams_next:h().optional(),disable_clickjack_protection_headers:h().optional(),disable_fields_map_fix:h().optional(),disable_impersonation:h().optional(),disable_management_api_sms_obfuscation:h().optional(),enable_adfs_waad_email_verification:h().optional(),enable_apis_section:h().optional(),enable_client_connections:h().optional(),enable_custom_domain_in_emails:h().optional(),enable_dynamic_client_registration:h().optional(),dcr_require_initial_access_token:h().optional(),dcr_allowed_grant_types:b(o()).optional(),dcr_allowed_integration_types:b(o()).optional(),enable_idtoken_api2:h().optional(),enable_legacy_logs_search_v2:h().optional(),enable_legacy_profile:h().optional(),enable_pipeline2:h().optional(),enable_public_signup_user_exists_error:h().optional(),enable_sso:h().optional(),enforce_client_authentication_on_passwordless_start:h().optional(),genai_trial:h().optional(),improved_signup_bot_detection_in_classic:h().optional(),mfa_show_factor_list_on_enrollment:h().optional(),no_disclose_enterprise_connections:h().optional(),remove_alg_from_jwks:h().optional(),revoke_refresh_token_grant:h().optional(),trust_azure_adfs_email_verified_connection_property:h().optional(),use_scope_descriptions_for_consent:h().optional(),inherit_global_permissions_in_organizations:h().optional()}).optional(),sandbox_version:o().optional(),legacy_sandbox_version:o().optional(),sandbox_versions_available:b(o()).optional(),change_password:_({enabled:h().optional(),html:o().optional()}).optional(),guardian_mfa_page:_({enabled:h().optional(),html:o().optional()}).optional(),device_flow:_({charset:k(["base20","digits"]).optional(),mask:o().max(20).optional()}).optional(),default_token_quota:_({clients:_({client_credentials:P(j()).optional()}).optional(),organizations:_({client_credentials:P(j()).optional()}).optional()}).optional(),default_audience:o().optional(),default_organization:o().optional(),sessions:_({oidc_logout_prompt_enabled:h().optional()}).optional(),oidc_logout:_({rp_logout_end_session_endpoint_discovery:h().optional()}).optional(),allow_organization_name_in_authentication_api:h().optional(),customize_mfa_in_postlogin_action:h().optional(),acr_values_supported:b(o()).optional(),mtls:_({enable_endpoint_aliases:h().optional()}).optional(),pushed_authorization_requests_supported:h().optional(),authorization_response_iss_parameter_supported:h().optional(),mfa:_({policy:k(["never","always"]).default("never").optional(),factors:_({sms:h().default(!1),otp:h().default(!1),email:h().default(!1),push_notification:h().default(!1),webauthn_roaming:h().default(!1),webauthn_platform:h().default(!1),recovery_code:h().default(!1),duo:h().default(!1)}).optional(),sms_provider:_({provider:k(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:_({sid:o().optional(),auth_token:o().optional(),from:o().optional(),messaging_service_sid:o().optional()}).optional(),phone_message:_({message:o().optional()}).optional()}).optional()});_({created_at:o().nullable().transform(n=>n??""),updated_at:o().nullable().transform(n=>n??""),...jd.shape,id:o()});_({access_token:o(),id_token:o().optional(),scope:o().optional(),state:o().optional(),refresh_token:o().optional(),token_type:o(),expires_in:I()});_({code:o(),state:o().optional()});const Vd=_({button_border_radius:I(),button_border_weight:I(),buttons_style:k(["pill","rounded","sharp"]),input_border_radius:I(),input_border_weight:I(),inputs_style:k(["pill","rounded","sharp"]),show_widget_shadow:h(),widget_border_weight:I(),widget_corner_radius:I()}),Zd=_({base_focus_color:o(),base_hover_color:o(),body_text:o(),captcha_widget_theme:k(["auto","dark","light"]),error:o(),header:o(),icons:o(),input_background:o(),input_border:o(),input_filled_text:o(),input_labels_placeholders:o(),links_focused_components:o(),primary_button:o(),primary_button_label:o(),secondary_button_border:o(),secondary_button_label:o(),success:o(),widget_background:o(),widget_border:o()}),vt=_({bold:h(),size:I()}),Hd=_({body_text:vt,buttons_text:vt,font_url:o(),input_labels:vt,links:vt,links_style:k(["normal","underlined"]),reference_text_size:I(),subtitle:vt,title:vt}),Kd=_({background_color:o(),background_image_url:o(),page_layout:k(["center","left","right"])}),Qd=_({header_text_alignment:k(["center","left","right"]),logo_height:I(),logo_position:k(["center","left","none","right"]),logo_url:o(),social_buttons_layout:k(["bottom","top"])}),Gd=_({borders:Vd,colors:Zd,displayName:o(),fonts:Hd,page_background:Kd,widget:Qd});Gd.extend({themeId:o()});_({universal_login_experience:k(["new","classic"]).default("new"),identifier_first:h().default(!0),password_first:h().default(!1),webauthn_platform_first_factor:h()});_({name:o(),enabled:h().optional().default(!0),default_from_address:o().optional(),credentials:Pe([_({accessKeyId:o(),secretAccessKey:o(),region:o()}),_({smtp_host:b(o()),smtp_port:I(),smtp_user:o(),smtp_pass:o()}),_({api_key:o(),domain:o().optional()}),_({connectionString:o()}),_({tenantId:o(),clientId:o(),clientSecret:o()})]),settings:_({}).optional()});const Jd=_({id:o(),login_id:o(),user_id:o(),client_id:o(),expires_at:o().optional(),idle_expires_at:o().optional(),last_exchanged_at:o().optional(),device:Or,resource_servers:b(_({audience:o(),scopes:o()})),rotating:h()});_({created_at:o(),revoked_at:o().optional(),...Jd.shape});_({to:o(),message:o()});_({name:o(),options:_({})});const Wd=_({value:o(),description:o().optional()}),Xd=_({token_dialect:k(["access_token","access_token_authz"]).optional(),enforce_policies:h().optional(),allow_skipping_userinfo:h().optional(),skip_userinfo:h().optional(),persist_client_authorization:h().optional(),enable_introspection_endpoint:h().optional(),mtls:_({bound_access_tokens:h().optional()}).optional()}),Yd=_({id:o().optional(),name:o(),identifier:o(),scopes:b(Wd).optional(),signing_alg:o().optional(),signing_secret:o().optional(),token_lifetime:I().default(86400),token_lifetime_for_web:I().default(7200),skip_consent_for_verifiable_first_party_clients:h().optional(),allow_offline_access:h().optional(),verificationKey:o().optional(),options:Xd.optional(),is_system:h().optional(),metadata:P(j()).optional()}),ec=_({...Yd.shape,created_at:o().optional(),updated_at:o().optional()});b(ec);const tc=_({role_id:o(),resource_server_identifier:o(),permission_name:o()}),nc=_({...tc.shape,created_at:o()});b(nc);const ic=_({user_id:o(),resource_server_identifier:o(),permission_name:o(),organization_id:o().optional()}),ac=_({...ic.shape,tenant_id:o(),created_at:o().optional()});b(ac);const oc=_({user_id:o(),resource_server_identifier:o(),resource_server_name:o(),permission_name:o(),description:o().nullable().optional(),created_at:o().optional(),organization_id:o().optional()});b(oc);const rc=_({user_id:o(),role_id:o(),organization_id:o().optional()}),sc=_({...rc.shape,tenant_id:o(),created_at:o().optional()});b(sc);const lc=_({id:o().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:o().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:o().max(255).optional().openapi({description:"The description of the role"}),is_system:h().optional(),metadata:P(j()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})}),dc=lc.extend({id:o().openapi({description:"The unique identifier of the role"}),created_at:o().optional(),updated_at:o().optional()});b(dc);const cc=_({logo_url:o().optional().openapi({description:"URL of the organization's logo"}),colors:_({primary:o().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:o().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),_c=_({connection_id:o().openapi({description:"ID of the connection"}),assign_membership_on_login:h().default(!1).openapi({description:"Whether to assign membership to the organization on login"}),show_as_button:h().default(!0).openapi({description:"Whether to show this connection as a button in the login screen"}),is_signup_enabled:h().default(!0).openapi({description:"Whether signup is enabled for this connection"})}),uc=_({client_credentials:_({enforce:h().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:I().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:I().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),pc=_({id:o().optional(),name:o().min(1).regex(/^[a-z0-9_-]+$/,{message:"Organization name must be lowercase and can only contain letters, numbers, hyphens, and underscores"}).openapi({description:"The name of the organization. Must be lowercase and can only contain letters, numbers, hyphens, and underscores."}),display_name:o().optional().openapi({description:"The display name of the organization"}),branding:cc,metadata:P(j()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:b(_c).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:uc});_({...pc.shape,...Ve.shape,id:o(),name:o().min(1).openapi({description:"The name of the organization"})});const fc=_({user_id:o().openapi({description:"ID of the user"}),organization_id:o().openapi({description:"ID of the organization"})});_({...fc.shape,...Ve.shape,id:o()});_({idle_session_lifetime:I().default(72),session_lifetime:I().default(168),session_cookie:_({mode:k(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:h().optional(),default_redirection_uri:o().optional(),enabled_locales:b(o()).optional(),default_directory:o().optional(),error_page:_({html:o().optional(),show_log_link:h().optional(),url:o().optional()}).optional(),flags:_({allow_legacy_delegation_grant_types:h().optional(),allow_legacy_ro_grant_types:h().optional(),allow_legacy_tokeninfo_endpoint:h().optional(),disable_clickjack_protection_headers:h().optional(),enable_apis_section:h().optional(),enable_client_connections:h().optional(),enable_custom_domain_in_emails:h().optional(),enable_dynamic_client_registration:h().optional(),enable_idtoken_api2:h().optional(),enable_legacy_logs_search_v2:h().optional(),enable_legacy_profile:h().optional(),enable_pipeline2:h().optional(),enable_public_signup_user_exists_error:h().optional(),use_scope_descriptions_for_consent:h().optional(),disable_management_api_sms_obfuscation:h().optional(),enable_adfs_waad_email_verification:h().optional(),revoke_refresh_token_grant:h().optional(),dashboard_log_streams_next:h().optional(),dashboard_insights_view:h().optional(),disable_fields_map_fix:h().optional(),mfa_show_factor_list_on_enrollment:h().optional()}).optional(),friendly_name:o().optional(),picture_url:o().optional(),support_email:o().optional(),support_url:o().optional(),sandbox_version:o().optional(),sandbox_versions_available:b(o()).optional(),change_password:_({enabled:h(),html:o()}).optional(),guardian_mfa_page:_({enabled:h(),html:o()}).optional(),default_audience:o().optional(),default_organization:o().optional(),sessions:_({oidc_logout_prompt_enabled:h().optional()}).optional(),mfa:_({policy:k(["never","always"]).default("never").optional(),factors:_({sms:h().default(!1),otp:h().default(!1),email:h().default(!1),push_notification:h().default(!1),webauthn_roaming:h().default(!1),webauthn_platform:h().default(!1),recovery_code:h().default(!1),duo:h().default(!1)}).optional(),sms_provider:_({provider:k(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:_({sid:o().optional(),auth_token:o().optional(),from:o().optional(),messaging_service_sid:o().optional()}).optional(),phone_message:_({message:o().optional()}).optional()}).optional()});_({date:o().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:I().openapi({description:"Number of logins on this date",example:150}),signups:I().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:I().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:o().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:o().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})});I().openapi({description:"Number of active users in the last 30 days",example:1234});const hc=k(["login","login-id","login-password","signup","signup-id","signup-password","reset-password","consent","mfa","mfa-push","mfa-otp","mfa-voice","mfa-phone","mfa-webauthn","mfa-email","mfa-recovery-code","status","device-flow","email-verification","email-otp-challenge","organizations","invitation","common","passkeys","captcha","custom-form","login-passwordless","mfa-login-options"]),gc=P(o(),P(o(),o())).openapi({type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}});_({prompt:hc,language:o(),custom_text:gc});const mc=k(["phone","totp","email","push","webauthn-roaming","webauthn-platform","passkey"]),Tr=_({user_id:o(),type:mc,phone_number:o().optional(),totp_secret:o().optional(),credential_id:o().optional(),public_key:o().optional(),sign_count:I().int().nonnegative().optional(),credential_backed_up:h().optional(),transports:b(o()).optional(),friendly_name:o().optional(),confirmed:h().default(!1)});function Ar(n,e){n.type==="phone"&&!n.phone_number&&e.addIssue({code:S.custom,message:"phone_number is required when type is 'phone'",path:["phone_number"]}),n.type==="totp"&&!n.totp_secret&&e.addIssue({code:S.custom,message:"totp_secret is required when type is 'totp'",path:["totp_secret"]}),["webauthn-roaming","webauthn-platform","passkey"].includes(n.type)&&(n.credential_id||e.addIssue({code:S.custom,message:`credential_id is required when type is '${n.type}'`,path:["credential_id"]}),n.public_key||e.addIssue({code:S.custom,message:`public_key is required when type is '${n.type}'`,path:["public_key"]}))}Tr.superRefine(Ar);_({...Tr.shape,id:o(),created_at:o(),updated_at:o()}).superRefine(Ar);function yc(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function vc(n){if(!n)return;const e=JSON.parse(n);return yc(e)?e:void 0}function Ln(n){return n==null?void 0:new Date(n).toISOString()}function Xt(n){if(!n)return null;const e=new Date(n);return isNaN(e.getTime())?null:e.getTime()}function Rn(n){const e=fr.parse(n.type);return{id:n.id,token_hash:n.token_hash,type:e,client_id:n.client_id??void 0,sub:n.sub??void 0,constraints:vc(n.constraints),single_use:!!n.single_use,expires_at:Ln(n.expires_at_ts),used_at:Ln(n.used_at_ts),revoked_at:Ln(n.revoked_at_ts),created_at:new Date(n.created_at_ts).toISOString()}}function wc(n){return{async create(e,t){const i=Date.now();return await n.insert(G).values({id:t.id,tenant_id:e,token_hash:t.token_hash,type:t.type,client_id:t.client_id??null,sub:t.sub??null,constraints:t.constraints?JSON.stringify(t.constraints):null,single_use:t.single_use?1:0,expires_at_ts:Xt(t.expires_at),created_at_ts:i}),{id:t.id,token_hash:t.token_hash,type:t.type,client_id:t.client_id,sub:t.sub,constraints:t.constraints,single_use:t.single_use,expires_at:t.expires_at,created_at:new Date(i).toISOString()}},async get(e,t){const i=await n.select().from(G).where(g(c(G.tenant_id,e),c(G.id,t))).get();return i?Rn(i):null},async getByHash(e,t){const i=await n.select().from(G).where(g(c(G.tenant_id,e),c(G.token_hash,t))).get();return i?Rn(i):null},async listByClient(e,t){return(await n.select().from(G).where(g(c(G.tenant_id,e),c(G.client_id,t))).orderBy(ce(G.created_at_ts))).map(Rn)},async markUsed(e,t,i){return(await n.update(G).set({used_at_ts:Xt(i)}).where(g(c(G.tenant_id,e),c(G.id,t),Ae(G.used_at_ts))).returning()).length>0},async revoke(e,t,i){return(await n.update(G).set({revoked_at_ts:Xt(i)}).where(g(c(G.tenant_id,e),c(G.id,t),Ae(G.revoked_at_ts))).returning()).length>0},async revokeByClient(e,t,i){return(await n.update(G).set({revoked_at_ts:Xt(i)}).where(g(c(G.tenant_id,e),c(G.client_id,t),Ae(G.revoked_at_ts))).returning()).length},async remove(e,t){return(await n.delete(G).where(g(c(G.tenant_id,e),c(G.id,t))).returning()).length>0}}}function Un(n){const{tenant_id:e,...t}=n;return K(t)}function Sc(n){return{async create(e,t){const i={...t,tenant_id:e,created_at:t.created_at||new Date().toISOString(),expires_at:t.expires_at};return await n.insert(re).values(i),Un(i)},async get(e,t,i){if(!e)throw new Error("tenant_id is required");const a=await n.select().from(re).where(g(c(re.tenant_id,e),c(re.code_id,t),c(re.code_type,i))).get();return a?Un(a):null},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l}=t||{};let d=n.select().from(re).where(c(re.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const v=re[l.sort_by];v&&(d=d.orderBy(l.sort_order==="desc"?ce(v):ge(v)))}const f=(await d.offset(i*a).limit(a)).map(Un);if(!r)return{codes:f};const[p]=await n.select({count:he()}).from(re).where(c(re.tenant_id,e));return{codes:f,start:i*a,limit:a,length:Number((p==null?void 0:p.count)??0)}},async used(e,t){return(await n.update(re).set({used_at:new Date().toISOString()}).where(g(c(re.tenant_id,e),c(re.code_id,t))).returning()).length>0},async consume(e,t){return(await n.update(re).set({used_at:new Date().toISOString()}).where(g(c(re.tenant_id,e),c(re.code_id,t),Ae(re.used_at))).returning()).length>0},async remove(e,t){return(await n.delete(re).where(g(c(re.tenant_id,e),c(re.code_id,t))).returning()).length>0}}}function Nc(){const{customAlphabet:n}=require("nanoid");return`con_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function zn(n){const{tenant_id:e,is_system:t,options:i,metadata:a,...r}=n;return K({...r,options:z(i,{}),metadata:z(a),is_system:t?!0:void 0})}function bc(n){return{async create(e,t){var r,l;const i=new Date().toISOString(),a={id:t.id||Nc(),...t,tenant_id:e,options:JSON.stringify(t.options||{}),metadata:t.metadata?JSON.stringify(t.metadata):void 0,is_system:t.is_system?1:0,created_at:i,updated_at:i};try{await n.insert(pe).values(a)}catch(d){throw(r=d==null?void 0:d.message)!=null&&r.includes("UNIQUE constraint failed")||(l=d==null?void 0:d.message)!=null&&l.includes("duplicate key")?new rt(409,{message:"Connection already exists"}):d}return zn(a)},async get(e,t){const i=await n.select().from(pe).where(g(c(pe.tenant_id,e),c(pe.id,t))).get();return i?zn(i):null},async update(e,t,i){const a={updated_at:new Date().toISOString()};return i.name!==void 0&&(a.name=i.name),i.strategy!==void 0&&(a.strategy=i.strategy),i.options!==void 0&&(a.options=JSON.stringify(i.options)),i.metadata!==void 0&&(a.metadata=JSON.stringify(i.metadata)),i.display_name!==void 0&&(a.display_name=i.display_name),i.response_type!==void 0&&(a.response_type=i.response_type),i.response_mode!==void 0&&(a.response_mode=i.response_mode),await n.update(pe).set(a).where(g(c(pe.tenant_id,e),c(pe.id,t))),!0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{};let u=c(pe.tenant_id,e);if(d){const N=je(pe,d,["name"]);N&&(u=g(u,N))}let f=n.select().from(pe).where(u).$dynamic();if(l!=null&&l.sort_by){const N=pe[l.sort_by];N&&(f=f.orderBy(l.sort_order==="desc"?ce(N):ge(N)))}const v=(await f.offset(i*a).limit(a)).map(zn);if(!r)return{connections:v};const[m]=await n.select({count:he()}).from(pe).where(u);return{connections:v,start:i*a,limit:a,length:Number((m==null?void 0:m.count)??0)}},async remove(e,t){return(await n.delete(pe).where(g(c(pe.tenant_id,e),c(pe.id,t))).returning()).length>0}}}function Yt(n){const{tenant_id:e,domain_metadata:t,...i}=n;return K({...i,primary:!!i.primary,domain_metadata:z(t)})}function Ec(n){return{async create(e,t){const i=new Date().toISOString(),r={custom_domain_id:t.custom_domain_id||Ie(),tenant_id:e,domain:t.domain,primary:t.primary??!1,status:t.status||"pending",type:t.type,origin_domain_name:t.origin_domain_name,verification:t.verification,custom_client_ip_header:t.custom_client_ip_header,tls_policy:t.tls_policy,domain_metadata:t.domain_metadata?JSON.stringify(t.domain_metadata):void 0,created_at:i,updated_at:i};return await n.insert(Oe).values(r),Yt({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(Oe).where(g(c(Oe.tenant_id,e),c(Oe.custom_domain_id,t))).get();return i?Yt(i):null},async getByDomain(e){const t=await n.select().from(Oe).where(c(Oe.domain,e)).get();return t?{...Yt(t),tenant_id:t.tenant_id}:null},async list(e){return(await n.select().from(Oe).where(c(Oe.tenant_id,e)).all()).map(Yt)},async update(e,t,i){const a={updated_at:new Date().toISOString()};return i.domain!==void 0&&(a.domain=i.domain),i.primary!==void 0&&(a.primary=i.primary),i.status!==void 0&&(a.status=i.status),i.type!==void 0&&(a.type=i.type),i.origin_domain_name!==void 0&&(a.origin_domain_name=i.origin_domain_name),i.verification!==void 0&&(a.verification=i.verification),i.custom_client_ip_header!==void 0&&(a.custom_client_ip_header=i.custom_client_ip_header),i.tls_policy!==void 0&&(a.tls_policy=i.tls_policy),i.domain_metadata!==void 0&&(a.domain_metadata=JSON.stringify(i.domain_metadata)),(await n.update(Oe).set(a).where(g(c(Oe.tenant_id,e),c(Oe.custom_domain_id,t))).returning()).length>0},async remove(e,t){return(await n.delete(Oe).where(g(c(Oe.tenant_id,e),c(Oe.custom_domain_id,t))).returning()).length>0}}}function xc(n){return{async get(e,t,i){const a=await n.select().from(Se).where(g(c(Se.tenant_id,e),c(Se.prompt,t),c(Se.language,i))).get();if(!a)return null;try{return JSON.parse(a.custom_text)}catch{return null}},async set(e,t,i,a){const r=Date.now(),l=JSON.stringify(a);await n.insert(Se).values({tenant_id:e,prompt:t,language:i,custom_text:l,created_at_ts:r,updated_at_ts:r}).onConflictDoUpdate({target:[Se.tenant_id,Se.prompt,Se.language],set:{custom_text:l,updated_at_ts:r}})},async delete(e,t,i){await n.delete(Se).where(g(c(Se.tenant_id,e),c(Se.prompt,t),c(Se.language,i)))},async list(e){return await n.select({prompt:Se.prompt,language:Se.language}).from(Se).where(c(Se.tenant_id,e)).all()}}}function kc(n){return{async create(e,t){const i=new Date().toISOString();await n.insert(it).values({tenant_id:e,name:t.name,enabled:t.enabled,default_from_address:t.default_from_address,credentials:JSON.stringify(t.credentials||{}),settings:JSON.stringify(t.settings||{}),created_at:i,updated_at:i})},async get(e){const t=await n.select().from(it).where(c(it.tenant_id,e)).get();if(!t)return null;const{tenant_id:i,...a}=t;return K({...a,enabled:!!a.enabled,credentials:z(a.credentials,{}),settings:z(a.settings,{})})},async update(e,t){const i={updated_at:new Date().toISOString()};t.name!==void 0&&(i.name=t.name),t.enabled!==void 0&&(i.enabled=t.enabled),t.default_from_address!==void 0&&(i.default_from_address=t.default_from_address),t.credentials!==void 0&&(i.credentials=JSON.stringify(t.credentials)),t.settings!==void 0&&(i.settings=JSON.stringify(t.settings)),await n.update(it).set(i).where(c(it.tenant_id,e))},async remove(e){await n.delete(it).where(c(it.tenant_id,e))}}}function Oc(n){return{async create(e,t){const i=new Date().toISOString(),a=`af_${Ie()}`;return await n.insert(xe).values({id:a,tenant_id:e,name:t.name,actions:JSON.stringify(t.actions||[]),created_at:i,updated_at:i}),{id:a,name:t.name,actions:t.actions||[],created_at:i,updated_at:i}},async get(e,t){const i=await n.select().from(xe).where(g(c(xe.tenant_id,e),c(xe.id,t))).get();if(!i)return null;const{tenant_id:a,actions:r,...l}=i;return K({...l,actions:z(r,[])})},async update(e,t,i){const a={updated_at:new Date().toISOString()};return i.name!==void 0&&(a.name=i.name),i.actions!==void 0&&(a.actions=JSON.stringify(i.actions)),(await n.update(xe).set(a).where(g(c(xe.tenant_id,e),c(xe.id,t))).returning()).length===0?null:this.get(e,t)},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l}=t||{};let d=n.select().from(xe).where(c(xe.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const v=xe[l.sort_by];v&&(d=d.orderBy(l.sort_order==="desc"?ce(v):ge(v)))}const f=(await d.offset(i*a).limit(a)).map(v=>{const{tenant_id:m,actions:N,...T}=v;return K({...T,actions:z(N,[])})});if(!r)return{flows:f};const[p]=await n.select({count:he()}).from(xe).where(c(xe.tenant_id,e));return{flows:f,start:i*a,limit:a,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(xe).where(g(c(xe.tenant_id,e),c(xe.id,t))).returning()).length>0}}}const en=["nodes","start","ending"];function Tc(n){return{async create(e,t){const i=new Date().toISOString(),a=Ie(),r={id:a,tenant_id:e,name:t.name,messages:t.messages,languages:t.languages,translations:t.translations,style:t.style,created_at:i,updated_at:i};for(const l of en)r[l]=JSON.stringify(t[l]||(l==="nodes"?[]:{}));return await n.insert(Ee).values(r),{id:a,...t,created_at:i,updated_at:i}},async get(e,t){const i=await n.select().from(Ee).where(g(c(Ee.tenant_id,e),c(Ee.id,t))).get();if(!i)return null;const{tenant_id:a,...r}=i,l={...r};for(const d of en)l[d]=z(r[d]);return K(l)},async update(e,t,i){const a={updated_at:new Date().toISOString()};for(const[l,d]of Object.entries(i))d!==void 0&&(en.includes(l)?a[l]=JSON.stringify(d):a[l]=d);return(await n.update(Ee).set(a).where(g(c(Ee.tenant_id,e),c(Ee.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l}=t||{};let d=n.select().from(Ee).where(c(Ee.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const v=Ee[l.sort_by];v&&(d=d.orderBy(l.sort_order==="desc"?ce(v):ge(v)))}const f=(await d.offset(i*a).limit(a)).map(v=>{const{tenant_id:m,...N}=v,T={...N};for(const ee of en)T[ee]=z(N[ee]);return K(T)});if(!r)return{forms:f};const[p]=await n.select({count:he()}).from(Ee).where(c(Ee.tenant_id,e));return{forms:f,start:i*a,limit:a,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(Ee).where(g(c(Ee.tenant_id,e),c(Ee.id,t))).returning()).length>0}}}function Ir(n){if(n!=null){if(typeof n=="number")return new Date(n).toISOString();if(typeof n=="string"){if(n==="")return;const e=parseFloat(n);return!isNaN(e)&&/^\d+(\.\d+)?$/.test(n)?new Date(e).toISOString():n}}}function si(n,e=new Date(0).toISOString()){return Ir(n)??e}function ne(n){if(!n||n==="")return null;const e=new Date(n);return isNaN(e.getTime())?null:e.getTime()}function Jt(n,e,t=[]){const i={};for(const a of e){const r=a.replace(/_ts$/,"");i[r]=si(n[a])}for(const a of t){const r=a.replace(/_ts$/,"");i[r]=Ir(n[a])}return i}const Ac=_s("0123456789abcdefghijklmnopqrstuvwxyz",17);function Ic(){return`hc_${Ac()}`}function Oi(n){const{created_at_ts:e,updated_at_ts:t,secrets:i,...a}=n,r=Jt({created_at_ts:e,updated_at_ts:t},["created_at_ts","updated_at_ts"]);return{...a,...r,secrets:i?JSON.parse(i):void 0}}function Cc(n){return{async create(e,t){const i=Date.now(),r={id:Ic(),tenant_id:e,code:t.code,secrets:t.secrets?JSON.stringify(t.secrets):null,created_at_ts:i,updated_at_ts:i};return await n.insert(qe).values(r),Oi({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(qe).where(g(c(qe.tenant_id,e),c(qe.id,t))).get();return i?Oi(i):null},async update(e,t,i){const a={updated_at_ts:Date.now()};return i.code!==void 0&&(a.code=i.code),i.secrets!==void 0&&(a.secrets=JSON.stringify(i.secrets)),(await n.update(qe).set(a).where(g(c(qe.tenant_id,e),c(qe.id,t))).returning()).length>0},async remove(e,t){return(await n.delete(qe).where(g(c(qe.tenant_id,e),c(qe.id,t))).returning()).length>0}}}function Dc(){const{customAlphabet:n}=require("nanoid");return`h_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Fn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,...a}=n,r=Jt({created_at_ts:t,updated_at_ts:i},["created_at_ts","updated_at_ts"]);return K({...a,enabled:!!a.enabled,synchronous:!!a.synchronous,...r})}function Lc(n){return{async create(e,t){const i=Date.now(),r={hook_id:t.hook_id||Dc(),tenant_id:e,trigger_id:t.trigger_id,url:t.url,enabled:t.enabled??!0,synchronous:t.synchronous??!1,priority:t.priority,form_id:t.form_id,template_id:t.template_id,code_id:t.code_id,created_at_ts:i,updated_at_ts:i};return await n.insert(we).values(r),Fn({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(we).where(g(c(we.tenant_id,e),c(we.hook_id,t))).get();return i?Fn(i):null},async update(e,t,i){const a={updated_at_ts:Date.now()};return i.trigger_id!==void 0&&(a.trigger_id=i.trigger_id),i.url!==void 0&&(a.url=i.url),i.enabled!==void 0&&(a.enabled=i.enabled),i.synchronous!==void 0&&(a.synchronous=i.synchronous),i.priority!==void 0&&(a.priority=i.priority),i.form_id!==void 0&&(a.form_id=i.form_id),i.template_id!==void 0&&(a.template_id=i.template_id),i.code_id!==void 0&&(a.code_id=i.code_id),(await n.update(we).set(a).where(g(c(we.tenant_id,e),c(we.hook_id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{},u=d?je(we,d,["url","form_id","template_id","code_id"]):void 0,f=u?g(c(we.tenant_id,e),u):c(we.tenant_id,e);let p=n.select().from(we).where(f).$dynamic();if(l!=null&&l.sort_by){const T=we[l.sort_by];T&&(p=p.orderBy(l.sort_order==="desc"?ce(T):ge(T)))}const m=(await p.offset(i*a).limit(a)).map(Fn);if(!r)return{hooks:m};const[N]=await n.select({count:he()}).from(we).where(f);return{hooks:m,start:i*a,limit:a,length:Number((N==null?void 0:N.count)??0)}},async remove(e,t){return(await n.delete(we).where(g(c(we.tenant_id,e),c(we.hook_id,t))).returning()).length>0}}}function Rc(){const{customAlphabet:n}=require("nanoid");return`inv_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const li=["inviter","invitee","app_metadata","user_metadata","roles"];function Pn(n){const{tenant_id:e,send_invitation_email:t,...i}=n,a={...i};for(const r of li)a[r]=z(i[r],r==="roles"?[]:{});return a.send_invitation_email=!!t,K(a)}function Uc(n){return{async create(e,t){var u,f;const i=t.id||Rc(),a=t.ttl_sec||604800,r=new Date,l=new Date(r.getTime()+a*1e3).toISOString(),d={id:i,tenant_id:e,organization_id:t.organization_id,client_id:t.client_id,connection_id:t.connection_id,invitation_url:t.invitation_url,ticket_id:t.ticket_id,ttl_sec:a,send_invitation_email:t.send_invitation_email!==!1?1:0,created_at:r.toISOString(),expires_at:l};for(const p of li)t[p]!==void 0&&(d[p]=JSON.stringify(t[p]));try{await n.insert(be).values(d)}catch(p){throw(u=p==null?void 0:p.message)!=null&&u.includes("UNIQUE constraint failed")||(f=p==null?void 0:p.message)!=null&&f.includes("duplicate key")?new rt(409,{message:"Invite already exists"}):p}return Pn({...d,tenant_id:e})},async get(e,t){const i=await n.select().from(be).where(g(c(be.tenant_id,e),c(be.id,t))).get();return i?Pn(i):null},async update(e,t,i){const a={};for(const l of li)i[l]!==void 0&&(a[l]=JSON.stringify(i[l]));return i.connection_id!==void 0&&(a.connection_id=i.connection_id),i.ttl_sec!==void 0&&(a.ttl_sec=i.ttl_sec,a.expires_at=new Date(Date.now()+i.ttl_sec*1e3).toISOString()),(await n.update(be).set(a).where(g(c(be.tenant_id,e),c(be.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l}=t||{};let d=n.select().from(be).where(c(be.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const v=be[l.sort_by];v&&(d=d.orderBy(l.sort_order==="desc"?ce(v):ge(v)))}const f=(await d.offset(i*a).limit(a)).map(Pn);if(!r)return{invites:f};const[p]=await n.select({count:he()}).from(be).where(c(be.tenant_id,e));return{invites:f,start:i*a,limit:a,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(be).where(g(c(be.tenant_id,e),c(be.id,t))).returning()).length>0}}}function zc(n){return{async create(e){await n.insert(Be).values({...e,created_at:new Date().toDateString()})},async list(e){const{page:t=0,per_page:i=50,include_totals:a=!1,sort:r}=e||{},l=new Date().toISOString();let d=n.select().from(Be).where(Ue(rn(Be.revoked_at,l),Ae(Be.revoked_at))).$dynamic();if(r!=null&&r.sort_by){const v=Be[r.sort_by];v&&(d=d.orderBy(r.sort_order==="desc"?ce(v):ge(v)))}const f=(await d.offset(t*i).limit(i)).map(v=>{const{created_at:m,...N}=v;return K(N)});if(!a)return{signingKeys:f};const[p]=await n.select({count:he()}).from(Be).where(Ue(rn(Be.revoked_at,l),Ae(Be.revoked_at)));return{signingKeys:f,start:t*i,limit:i,length:is((p==null?void 0:p.count)??0)}},async update(e,t){return(await n.update(Be).set(t).where(c(Be.kid,e)).returning()).length>0}}}const di="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Mn=di.length;function Fc(){let t=Date.now(),i="";for(let r=10;r>0;r--)i=di.charAt(t%Mn)+i,t=Math.floor(t/Mn);const a=new Uint8Array(16);crypto.getRandomValues(a);for(let r=0;r<16;r++)i+=di.charAt(a[r]%Mn);return i}function Ti(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,expires_at_ts:a,state_data:r,auth_params:l,...d}=n,u=Jt({created_at_ts:t,updated_at_ts:i,expires_at_ts:a},["created_at_ts","updated_at_ts","expires_at_ts"]),f={};for(const[v,m]of Object.entries(d))m!=null&&(f[v]=m);const p=or(f,["auth_strategy"]);return K({...p,authParams:typeof l=="string"&&l.length>0?JSON.parse(l):{},...u,state_data:z(r)})}function Pc(n){return{async create(e,t){var l,d;const i=Date.now(),r={id:Fc(),tenant_id:e,session_id:t.session_id,csrf_token:t.csrf_token,auth_params:JSON.stringify(t.authParams||{}),authorization_url:t.authorization_url?t.authorization_url.substring(0,1024):void 0,ip:t.ip,useragent:t.useragent,auth0Client:t.auth0Client,state:t.state||"pending",state_data:t.state_data?JSON.stringify(t.state_data):void 0,failure_reason:t.failure_reason,user_id:t.user_id,auth_connection:t.auth_connection,auth_strategy_strategy:(l=t.auth_strategy)==null?void 0:l.strategy,auth_strategy_strategy_type:(d=t.auth_strategy)==null?void 0:d.strategy_type,authenticated_at:t.authenticated_at,created_at_ts:i,updated_at_ts:i,expires_at_ts:t.expires_at?ne(t.expires_at):i+1e3*60*60*24};return await n.insert(J).values(r),Ti({...r,tenant_id:e})},async get(e,t){const i=e?g(c(J.tenant_id,e),c(J.id,t)):c(J.id,t),a=await n.select().from(J).where(i).get();return a?Ti(a):null},async update(e,t,i){var r,l,d;const a={updated_at_ts:Date.now()};if(i.session_id!==void 0&&(a.session_id=i.session_id),i.state!==void 0&&(a.state=i.state),i.state_data!==void 0&&(a.state_data=JSON.stringify(i.state_data)),i.failure_reason!==void 0&&(a.failure_reason=i.failure_reason),i.user_id!==void 0&&(a.user_id=i.user_id),i.auth_connection!==void 0&&(a.auth_connection=i.auth_connection),i.auth_strategy!==void 0&&(a.auth_strategy_strategy=(r=i.auth_strategy)==null?void 0:r.strategy,a.auth_strategy_strategy_type=(l=i.auth_strategy)==null?void 0:l.strategy_type),i.authenticated_at!==void 0&&(a.authenticated_at=i.authenticated_at),i.authorization_url!==void 0&&(a.authorization_url=(d=i.authorization_url)==null?void 0:d.substring(0,1024)),i.expires_at!==void 0&&(a.expires_at_ts=ne(i.expires_at)),i.authParams!==void 0){const u=await n.select({auth_params:J.auth_params}).from(J).where(g(c(J.tenant_id,e),c(J.id,t))).get(),f=u!=null&&u.auth_params&&typeof u.auth_params=="string"&&u.auth_params.length>0?JSON.parse(u.auth_params):{};a.auth_params=JSON.stringify({...f,...i.authParams})}return await n.update(J).set(a).where(g(c(J.tenant_id,e),c(J.id,t))),!0},async remove(e,t){return(await n.delete(J).where(g(c(J.tenant_id,e),c(J.id,t))).returning()).length>0}}}function qn(n){const{tenant_id:e,isMobile:t,auth0_client:i,details:a,country_code:r,city_name:l,latitude:d,longitude:u,time_zone:f,continent_code:p,scope:v,...m}=n,N={...m,isMobile:!!t,auth0_client:z(i),details:z(a),scope:v?v.split(","):void 0};return r&&(N.location_info=K({country_code:r,city_name:l,latitude:d,longitude:u,time_zone:f,continent_code:p})),K(N)}function Mc(n){return{async create(e,t){var r,l;const a={log_id:t.log_id||Ie(),tenant_id:e,type:t.type,date:t.date||new Date().toISOString(),category:t.category,user_id:t.user_id,ip:t.ip,client_id:t.client_id,client_name:t.client_name,user_agent:(r=t.user_agent)==null?void 0:r.substring(0,256),description:(l=t.description)==null?void 0:l.substring(0,256),isMobile:t.isMobile?1:0,user_name:t.user_name,connection:t.connection,connection_id:t.connection_id,audience:t.audience,scope:Array.isArray(t.scope)?t.scope.join(","):t.scope,strategy:t.strategy,strategy_type:t.strategy_type,hostname:t.hostname,session_connection:t.session_connection};return t.auth0_client&&(a.auth0_client=JSON.stringify(t.auth0_client)),t.details&&(a.details=JSON.stringify(t.details).substring(0,8192)),t.location_info&&(a.country_code=t.location_info.country_code,a.city_name=t.location_info.city_name,a.latitude=t.location_info.latitude,a.longitude=t.location_info.longitude,a.time_zone=t.location_info.time_zone,a.continent_code=t.location_info.continent_code),await n.insert(Q).values(a),qn({...a,tenant_id:e})},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{};let u=n.select().from(Q).where(c(Q.tenant_id,e)).$dynamic();if(d){const m=je(Q,d,["user_id","ip","type","client_id"]);m&&(u=u.where(g(c(Q.tenant_id,e),m)))}if(l!=null&&l.sort_by){const m=Q[l.sort_by];m&&(u=u.orderBy(l.sort_order==="desc"?ce(m):ge(m)))}else u=u.orderBy(ce(Q.date));const p=(await u.offset(i*a).limit(a)).map(qn);if(!r)return{logs:p};const[v]=await n.select({count:he()}).from(Q).where(c(Q.tenant_id,e));return{logs:p,start:i*a,limit:a,length:Number((v==null?void 0:v.count)??0)}},async get(e,t){const i=await n.select().from(Q).where(g(c(Q.tenant_id,e),c(Q.log_id,t))).get();return i?qn(i):null}}}const ci="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Bn=ci.length;function qc(){let t=Date.now(),i="";for(let r=10;r>0;r--)i=ci.charAt(t%Bn)+i,t=Math.floor(t/Bn);const a=new Uint8Array(16);crypto.getRandomValues(a);for(let r=0;r<16;r++)i+=ci.charAt(a[r]%Bn);return i}function tn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,credential_backed_up:a,confirmed:r,transports:l,...d}=n;return K({...d,confirmed:!!r,credential_backed_up:a!=null?!!a:void 0,transports:z(l),created_at:si(t),updated_at:si(i)})}function Bc(n){return{async create(e,t){const i=Date.now(),r={id:t.id||qc(),tenant_id:e,user_id:t.user_id,type:t.type,phone_number:t.phone_number,totp_secret:t.totp_secret,credential_id:t.credential_id,public_key:t.public_key,sign_count:t.sign_count,credential_backed_up:t.credential_backed_up!=null?t.credential_backed_up?1:0:null,transports:t.transports?JSON.stringify(t.transports):null,friendly_name:t.friendly_name,confirmed:t.confirmed?1:0,created_at_ts:i,updated_at_ts:i};return await n.insert(ue).values(r),tn({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(ue).where(g(c(ue.tenant_id,e),c(ue.id,t))).get();return i?tn(i):null},async getByCredentialId(e,t){const i=await n.select().from(ue).where(g(c(ue.tenant_id,e),c(ue.credential_id,t))).get();return i?tn(i):null},async list(e,t){return(await n.select().from(ue).where(g(c(ue.tenant_id,e),c(ue.user_id,t))).all()).map(tn)},async update(e,t,i){const a={updated_at_ts:Date.now()};i.type!==void 0&&(a.type=i.type),i.phone_number!==void 0&&(a.phone_number=i.phone_number),i.totp_secret!==void 0&&(a.totp_secret=i.totp_secret),i.credential_id!==void 0&&(a.credential_id=i.credential_id),i.public_key!==void 0&&(a.public_key=i.public_key),i.sign_count!==void 0&&(a.sign_count=i.sign_count),i.credential_backed_up!==void 0&&(a.credential_backed_up=i.credential_backed_up?1:0),i.transports!==void 0&&(a.transports=JSON.stringify(i.transports)),i.friendly_name!==void 0&&(a.friendly_name=i.friendly_name),i.confirmed!==void 0&&(a.confirmed=i.confirmed?1:0),await n.update(ue).set(a).where(g(c(ue.tenant_id,e),c(ue.id,t)));const r=await this.get(e,t);if(!r)throw new Error(`Authentication method ${t} not found after update`);return r},async remove(e,t){return(await n.delete(ue).where(g(c(ue.tenant_id,e),c(ue.id,t))).returning()).length>0}}}function $c(){const{customAlphabet:n}=require("nanoid");return`org_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function $n(n){const{tenant_id:e,branding:t,metadata:i,enabled_connections:a,token_quota:r,...l}=n;return K({...l,branding:z(t,{}),metadata:z(i,{}),enabled_connections:z(a,[]),token_quota:z(r,{})})}function jc(n){return{async create(e,t){var l,d;const i=new Date().toISOString(),r={id:t.id||$c(),tenant_id:e,name:t.name,display_name:t.display_name,branding:JSON.stringify(t.branding||{}),metadata:JSON.stringify(t.metadata||{}),enabled_connections:JSON.stringify(t.enabled_connections||[]),token_quota:JSON.stringify(t.token_quota||{}),created_at:i,updated_at:i};try{await n.insert(W).values(r)}catch(u){throw(l=u==null?void 0:u.message)!=null&&l.includes("UNIQUE constraint failed")||(d=u==null?void 0:u.message)!=null&&d.includes("AlreadyExists")?new rt(409,{message:"Organization already exists"}):u}return $n({...r,tenant_id:e})},async get(e,t){let i=await n.select().from(W).where(g(c(W.tenant_id,e),c(W.id,t))).get();return i||(i=await n.select().from(W).where(g(c(W.tenant_id,e),c(W.name,t))).get()),i?$n(i):null},async update(e,t,i){const a={updated_at:new Date().toISOString()};return i.name!==void 0&&(a.name=i.name),i.display_name!==void 0&&(a.display_name=i.display_name),i.branding!==void 0&&(a.branding=JSON.stringify(i.branding)),i.metadata!==void 0&&(a.metadata=JSON.stringify(i.metadata)),i.enabled_connections!==void 0&&(a.enabled_connections=JSON.stringify(i.enabled_connections)),i.token_quota!==void 0&&(a.token_quota=JSON.stringify(i.token_quota)),(await n.update(W).set(a).where(g(c(W.tenant_id,e),c(W.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{};let u=n.select().from(W).where(c(W.tenant_id,e)).$dynamic();if(d&&(u=u.where(Ue(St(W.name,`%${d}%`),St(W.display_name,`%${d}%`)))),l!=null&&l.sort_by){const N=W[l.sort_by];N&&(u=u.orderBy(l.sort_order==="desc"?ce(N):ge(N)))}const p=(await u.offset(i*a).limit(a)).map($n);if(!r)return{organizations:p};const v=[c(W.tenant_id,e)];d&&v.push(Ue(St(W.name,`%${d}%`),St(W.display_name,`%${d}%`)));const[m]=await n.select({count:he()}).from(W).where(g(...v));return{organizations:p,start:i*a,limit:a,length:Number((m==null?void 0:m.count)??0)}},async remove(e,t){return(await n.delete(W).where(g(c(W.tenant_id,e),c(W.id,t))).returning()).length>0}}}function jn(n){const{tenant_id:e,is_current:t,...i}=n;return{...i,is_current:!!t}}function Vc(n){return{async create(e,t){const i=new Date().toISOString(),a=t.id||Ie();t.is_current!==!1&&await n.update(te).set({is_current:0}).where(g(c(te.tenant_id,e),c(te.user_id,t.user_id)));const r={id:a,tenant_id:e,user_id:t.user_id,password:t.password,algorithm:t.algorithm||"bcrypt",is_current:t.is_current!==!1?1:0,created_at:i,updated_at:i};return await n.insert(te).values(r),jn({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(te).where(g(c(te.tenant_id,e),c(te.user_id,t),c(te.is_current,1))).get();return i?jn(i):null},async list(e,t,i){let a=n.select().from(te).where(g(c(te.tenant_id,e),c(te.user_id,t))).orderBy(ce(te.created_at)).$dynamic();return i&&(a=a.limit(i)),(await a).map(jn)},async update(e,t){const i={updated_at:new Date().toISOString()};return t.password!==void 0&&(i.password=t.password),t.algorithm!==void 0&&(i.algorithm=t.algorithm),t.is_current!==void 0&&(i.is_current=t.is_current?1:0),t.id?await n.update(te).set(i).where(g(c(te.tenant_id,e),c(te.id,t.id))):await n.update(te).set(i).where(g(c(te.tenant_id,e),c(te.user_id,t.user_id),c(te.is_current,1))),!0}}}function Zc(n){return{async get(e){const t=await n.select().from(It).where(c(It.tenant_id,e)).get();return t?{universal_login_experience:t.universal_login_experience,identifier_first:!!t.identifier_first,password_first:!!t.password_first,webauthn_platform_first_factor:!!t.webauthn_platform_first_factor}:{universal_login_experience:"new",identifier_first:!0,password_first:!1,webauthn_platform_first_factor:!1}},async set(e,t){await n.insert(It).values({tenant_id:e,universal_login_experience:t.universal_login_experience,identifier_first:t.identifier_first,password_first:t.password_first,webauthn_platform_first_factor:t.webauthn_platform_first_factor}).onConflictDoUpdate({target:It.tenant_id,set:{universal_login_experience:t.universal_login_experience,identifier_first:t.identifier_first,password_first:t.password_first,webauthn_platform_first_factor:t.webauthn_platform_first_factor}})}}}function Vn(n){const{tenant_id:e,created_at_ts:t,expires_at_ts:i,idle_expires_at_ts:a,last_exchanged_at_ts:r,revoked_at_ts:l,device:d,resource_servers:u,rotating:f,...p}=n,v=Jt({created_at_ts:t,expires_at_ts:i,idle_expires_at_ts:a,last_exchanged_at_ts:r,revoked_at_ts:l},["created_at_ts"],["expires_at_ts","idle_expires_at_ts","last_exchanged_at_ts","revoked_at_ts"]);return K({...p,...v,rotating:!!f,device:z(d,{}),resource_servers:z(u,[])})}function Hc(n,e){return Math.max(n??0,e??0)}function Kc(n){return{async create(e,t){const i=Date.now(),a={id:t.id||Ie(),tenant_id:e,client_id:t.client_id,login_id:t.login_id,user_id:t.user_id,device:JSON.stringify(t.device||{}),resource_servers:JSON.stringify(t.resource_servers||[]),rotating:t.rotating??!1,created_at_ts:i,expires_at_ts:ne(t.expires_at),idle_expires_at_ts:ne(t.idle_expires_at),last_exchanged_at_ts:ne(t.last_exchanged_at)};await n.run(A`BEGIN`);try{await n.insert(X).values(a);const r=Hc(a.expires_at_ts,a.idle_expires_at_ts);r>0&&a.login_id&&await n.update(J).set({expires_at_ts:r,updated_at_ts:i}).where(g(c(J.tenant_id,e),c(J.id,a.login_id),Xe(J.expires_at_ts,r))),await n.run(A`COMMIT`)}catch(r){throw await n.run(A`ROLLBACK`),r}return Vn({...a,tenant_id:e})},async get(e,t){const i=await n.select().from(X).where(g(c(X.tenant_id,e),c(X.id,t))).get();return i?Vn(i):null},async update(e,t,i,a){const r={};i.device!==void 0&&(r.device=JSON.stringify(i.device)),i.resource_servers!==void 0&&(r.resource_servers=JSON.stringify(i.resource_servers)),i.rotating!==void 0&&(r.rotating=i.rotating),i.expires_at!==void 0&&(r.expires_at_ts=ne(i.expires_at)),i.idle_expires_at!==void 0&&(r.idle_expires_at_ts=ne(i.idle_expires_at)),i.last_exchanged_at!==void 0&&(r.last_exchanged_at_ts=ne(i.last_exchanged_at)),i.revoked_at!==void 0&&(r.revoked_at_ts=ne(i.revoked_at));const l=a==null?void 0:a.loginSessionBump,d=l?ne(l.expires_at):null,u=await n.update(X).set(r).where(g(c(X.tenant_id,e),c(X.id,t))).returning();return l!=null&&l.login_id&&d&&d>0&&await n.update(J).set({expires_at_ts:d,updated_at_ts:Date.now()}).where(g(c(J.tenant_id,e),c(J.id,l.login_id),Xe(J.expires_at_ts,d))).catch(()=>{}),u.length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{};let u=n.select().from(X).where(c(X.tenant_id,e)).$dynamic();if(d){const m=je(X,d,["user_id"]);m&&(u=u.where(g(c(X.tenant_id,e),m)))}if(l!=null&&l.sort_by){const m=X[l.sort_by];m&&(u=u.orderBy(l.sort_order==="desc"?ce(m):ge(m)))}const p=(await u.offset(i*a).limit(a)).map(Vn);if(!r)return{refresh_tokens:p};const[v]=await n.select({count:he()}).from(X).where(c(X.tenant_id,e));return{refresh_tokens:p,start:i*a,limit:a,length:Number((v==null?void 0:v.count)??0)}},async remove(e,t){return(await n.delete(X).where(g(c(X.tenant_id,e),c(X.id,t))).returning()).length>0},async revokeByLoginSession(e,t,i){return(await n.update(X).set({revoked_at_ts:ne(i)}).where(g(c(X.tenant_id,e),c(X.login_id,t),Ae(X.revoked_at_ts))).returning()).length}}}function Qc(){const{customAlphabet:n}=require("nanoid");return`api_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const _i=["skip_consent_for_verifiable_first_party_clients","allow_offline_access","is_system"],Ai=new Set(["id","tenant_id","identifier","name","scopes","signing_alg","signing_secret","token_lifetime","token_lifetime_for_web","skip_consent_for_verifiable_first_party_clients","allow_offline_access","verification_key","options","is_system","metadata","created_at","updated_at"]);function Zn(n){const{tenant_id:e,verification_key:t,scopes:i,options:a,metadata:r,...l}=n,d={...l};d.scopes=z(i,[]),d.options=z(a,{}),d.metadata=z(r),t!==void 0&&(d.verificationKey=t);for(const u of _i)l[u]!==void 0&&l[u]!==null&&(d[u]=!!l[u]);return K(d)}function Gc(n){return{async create(e,t){const i=new Date().toISOString(),r={id:t.id||Qc(),tenant_id:e,identifier:t.identifier,name:t.name,signing_alg:t.signing_alg,signing_secret:t.signing_secret,token_lifetime:t.token_lifetime,token_lifetime_for_web:t.token_lifetime_for_web,scopes:JSON.stringify(t.scopes||[]),options:JSON.stringify(t.options||{}),metadata:t.metadata?JSON.stringify(t.metadata):void 0,verification_key:t.verificationKey||t.verification_key,created_at:i,updated_at:i};for(const l of _i)t[l]!==void 0&&(r[l]=t[l]?1:0);return r.is_system===void 0&&(r.is_system=0),await n.insert(Y).values(r),Zn({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(Y).where(g(c(Y.tenant_id,e),c(Y.id,t))).get();return i?Zn(i):null},async update(e,t,i){const a={updated_at:new Date().toISOString()};i.name!==void 0&&(a.name=i.name),i.identifier!==void 0&&(a.identifier=i.identifier),i.signing_alg!==void 0&&(a.signing_alg=i.signing_alg),i.signing_secret!==void 0&&(a.signing_secret=i.signing_secret),i.token_lifetime!==void 0&&(a.token_lifetime=i.token_lifetime),i.token_lifetime_for_web!==void 0&&(a.token_lifetime_for_web=i.token_lifetime_for_web),i.scopes!==void 0&&(a.scopes=JSON.stringify(i.scopes)),i.options!==void 0&&(a.options=A`json_patch(COALESCE(${Y.options}, '{}'), ${JSON.stringify(i.options)})`),i.metadata!==void 0&&(a.metadata=JSON.stringify(i.metadata)),i.verificationKey!==void 0&&(a.verification_key=i.verificationKey);for(const l of _i)i[l]!==void 0&&(a[l]=i[l]?1:0);return(await n.update(Y).set(a).where(g(c(Y.tenant_id,e),c(Y.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{},u=Math.max(0,Math.floor(Number(i)||0)),f=Math.min(Math.max(1,Math.floor(Number(a)||50)),500),p=[c(Y.tenant_id,e)];if(d){const ee=d.match(/^([^:]+):(.+)$/);if(ee){const[,ie,ae]=ee,Ge=ie==null?void 0:ie.startsWith("-"),ut=Ge?ie==null?void 0:ie.substring(1):ie;if(ut&&Ai.has(ut)&&!Ge){const vn=Y[ut];p.push(St(vn,`%${ae}%`))}}}let v=n.select().from(Y).where(g(...p)).$dynamic();if(l!=null&&l.sort_by&&Ai.has(l.sort_by)){const ee=Y[l.sort_by];v=v.orderBy(l.sort_order==="desc"?ce(ee):ge(ee))}const N=(await v.offset(u*f).limit(f)).map(Zn);if(!r)return{resource_servers:N};const[T]=await n.select({count:he()}).from(Y).where(g(...p));return{resource_servers:N,start:u*f,limit:f,length:Number((T==null?void 0:T.count)??0)}},async remove(e,t){return(await n.delete(Y).where(g(c(Y.tenant_id,e),c(Y.id,t))).returning()).length>0}}}function Jc(n){return{async assign(e,t,i){const a=new Date().toISOString();return await n.insert(Ce).values(i.map(r=>({tenant_id:e,role_id:t,resource_server_identifier:r.resource_server_identifier,permission_name:r.permission_name,created_at:a}))).onConflictDoNothing(),!0},async list(e,t,i){const a=await n.select({resource_server_identifier:Ce.resource_server_identifier,permission_name:Ce.permission_name,created_at:Ce.created_at}).from(Ce).where(g(c(Ce.tenant_id,e),c(Ce.role_id,t))).all(),r=[...new Set(a.map(d=>d.resource_server_identifier))],l=new Map;if(r.length>0){const d=await n.select({identifier:Y.identifier,name:Y.name}).from(Y).where(g(c(Y.tenant_id,e),Ye(Y.identifier,r))).all();for(const u of d)l.set(u.identifier,u.name)}return a.map(d=>({...d,resource_server_name:l.get(d.resource_server_identifier)||d.resource_server_identifier}))},async remove(e,t,i){const a=i.map(l=>g(c(Ce.resource_server_identifier,l.resource_server_identifier),c(Ce.permission_name,l.permission_name)));return(await n.delete(Ce).where(g(c(Ce.tenant_id,e),c(Ce.role_id,t),Ue(...a))).returning()).length>0}}}function Wc(n){return{async create(e,t,i,a){var r,l;try{await n.insert(Le).values({tenant_id:e,user_id:t,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name,organization_id:a||"",created_at:new Date().toISOString()})}catch(d){if((r=d==null?void 0:d.message)!=null&&r.includes("UNIQUE constraint")||(l=d==null?void 0:d.message)!=null&&l.includes("SQLITE_CONSTRAINT_PRIMARYKEY"))return!0;throw d}return!0},async list(e,t,i,a){let r=[c(Le.tenant_id,e),c(Le.user_id,t)];a&&r.push(c(Le.organization_id,a));const l=await n.select().from(Le).where(g(...r)).all();return await Promise.all(l.map(async u=>{const f=await n.select({name:Y.name}).from(Y).where(g(c(Y.tenant_id,e),c(Y.identifier,u.resource_server_identifier))).get();return{resource_server_identifier:u.resource_server_identifier,permission_name:u.permission_name,resource_server_name:(f==null?void 0:f.name)||u.resource_server_identifier,organization_id:u.organization_id===""?void 0:u.organization_id}}))},async remove(e,t,i,a){return(await n.delete(Le).where(g(c(Le.tenant_id,e),c(Le.user_id,t),c(Le.resource_server_identifier,i.resource_server_identifier),c(Le.permission_name,i.permission_name),c(Le.organization_id,a||""))).returning()).length>0}}}function Hn(n){const{tenant_id:e,is_system:t,metadata:i,...a}=n;return K({...a,is_system:t?!0:void 0,metadata:z(i)})}function Xc(n){return{async create(e,t){const i=new Date().toISOString(),r={id:t.id||Ie(),tenant_id:e,name:t.name,description:t.description,is_system:t.is_system?1:0,metadata:t.metadata?JSON.stringify(t.metadata):void 0,created_at:i,updated_at:i};return await n.insert(_e).values(r),Hn({...r,tenant_id:e})},async get(e,t){const i=await n.select().from(_e).where(g(c(_e.tenant_id,e),c(_e.id,t))).get();return i?Hn(i):null},async update(e,t,i){const a={updated_at:new Date().toISOString()};return i.name!==void 0&&(a.name=i.name),i.description!==void 0&&(a.description=i.description),i.is_system!==void 0&&(a.is_system=i.is_system?1:0),i.metadata!==void 0&&(a.metadata=JSON.stringify(i.metadata)),(await n.update(_e).set(a).where(g(c(_e.tenant_id,e),c(_e.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{},u=d?je(_e,d,["name"]):void 0,f=u?g(c(_e.tenant_id,e),u):c(_e.tenant_id,e);let p=n.select().from(_e).where(f).$dynamic();if(l!=null&&l.sort_by){const T=_e[l.sort_by];T&&(p=p.orderBy(l.sort_order==="desc"?ce(T):ge(T)))}const m=(await p.offset(i*a).limit(a)).map(Hn);if(!r)return{roles:m};const[N]=await n.select({count:he()}).from(_e).where(f);return{roles:m,start:i*a,limit:a,length:Number((N==null?void 0:N.count)??0)}},async remove(e,t){return(await n.delete(_e).where(g(c(_e.tenant_id,e),c(_e.id,t))).returning()).length>0}}}const Yc=["created_at_ts","updated_at_ts"],e_=["expires_at_ts","idle_expires_at_ts","authenticated_at_ts","last_interaction_at_ts","used_at_ts","revoked_at_ts"];function Kn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,expires_at_ts:a,idle_expires_at_ts:r,authenticated_at_ts:l,last_interaction_at_ts:d,used_at_ts:u,revoked_at_ts:f,device:p,clients:v,...m}=n,N=Jt({created_at_ts:t,updated_at_ts:i,expires_at_ts:a,idle_expires_at_ts:r,authenticated_at_ts:l,last_interaction_at_ts:d,used_at_ts:u,revoked_at_ts:f},[...Yc],[...e_]);return K({...m,...N,device:z(p,{}),clients:z(v,[])})}function t_(n){return{async create(e,t){const i=Date.now(),a={id:t.id||Ie(),tenant_id:e,user_id:t.user_id,login_session_id:t.login_session_id,device:JSON.stringify(t.device||{}),clients:JSON.stringify(t.clients||[]),created_at_ts:i,updated_at_ts:i,expires_at_ts:ne(t.expires_at),idle_expires_at_ts:ne(t.idle_expires_at),authenticated_at_ts:t.authenticated_at?ne(t.authenticated_at):i,last_interaction_at_ts:t.last_interaction_at?ne(t.last_interaction_at):i,used_at_ts:ne(t.used_at),revoked_at_ts:ne(t.revoked_at)};return await n.insert(oe).values(a),Kn({...a,tenant_id:e})},async get(e,t){const i=await n.select().from(oe).where(g(c(oe.tenant_id,e),c(oe.id,t))).get();return i?Kn(i):null},async update(e,t,i){const a={updated_at_ts:Date.now()};return i.user_id!==void 0&&(a.user_id=i.user_id),i.login_session_id!==void 0&&(a.login_session_id=i.login_session_id),i.device!==void 0&&(a.device=JSON.stringify(i.device)),i.clients!==void 0&&(a.clients=JSON.stringify(i.clients)),i.expires_at!==void 0&&(a.expires_at_ts=ne(i.expires_at)),i.idle_expires_at!==void 0&&(a.idle_expires_at_ts=ne(i.idle_expires_at)),i.authenticated_at!==void 0&&(a.authenticated_at_ts=ne(i.authenticated_at)),i.last_interaction_at!==void 0&&(a.last_interaction_at_ts=ne(i.last_interaction_at)),i.used_at!==void 0&&(a.used_at_ts=ne(i.used_at)),i.revoked_at!==void 0&&(a.revoked_at_ts=ne(i.revoked_at)),(await n.update(oe).set(a).where(g(c(oe.tenant_id,e),c(oe.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,sort:l,q:d}=t||{},u=d?je(oe,d,["user_id"]):void 0,f=u?g(c(oe.tenant_id,e),u):c(oe.tenant_id,e);let p=n.select().from(oe).where(f).$dynamic();if(l!=null&&l.sort_by){const T=oe[l.sort_by];T&&(p=p.orderBy(l.sort_order==="desc"?ce(T):ge(T)))}const m=(await p.offset(i*a).limit(a)).map(Kn);if(!r)return{sessions:m};const[N]=await n.select({count:he()}).from(oe).where(f);return{sessions:m,start:i*a,limit:a,length:Number((N==null?void 0:N.count)??0)}},async remove(e,t){return(await n.delete(oe).where(g(c(oe.tenant_id,e),c(oe.id,t))).returning()).length>0}}}const Cr=["session_cookie","enabled_locales","error_page","flags","sandbox_versions_available","change_password","guardian_mfa_page","sessions","oidc_logout","device_flow","default_token_quota","allowed_logout_urls","acr_values_supported","mtls","mfa"],Dr=["allow_organization_name_in_authentication_api","customize_mfa_in_postlogin_action","pushed_authorization_requests_supported","authorization_response_iss_parameter_supported"];function Ii(n){const e={...n};for(const t of Cr)typeof e[t]=="string"&&(e[t]=z(e[t]));for(const t of Dr)e[t]!==void 0&&e[t]!==null&&(e[t]=e[t]===1);return K(e)}function Ci(n){const e={...n};ts(n,Cr,e);for(const t of Dr)n[t]!==void 0&&(e[t]=n[t]?1:0);return ar(e)}function n_(n){return{async create(e){var a,r;const t={id:e.id||Ie(),created_at:new Date().toISOString(),updated_at:new Date().toISOString(),...e},i=Ci(t);try{await n.insert(B).values(i)}catch(l){throw(a=l==null?void 0:l.message)!=null&&a.includes("UNIQUE constraint failed")||(r=l==null?void 0:l.message)!=null&&r.includes("duplicate key")||(l==null?void 0:l.code)==="SQLITE_CONSTRAINT"?new rt(409,{message:`Tenant with ID '${t.id}' already exists`}):l}return t},async get(e){const t=await n.select().from(B).where(c(B.id,e)).get();return t?Ii(t):null},async list(e){const{page:t=0,per_page:i=50,include_totals:a=!1,sort:r,q:l}=e||{};let d=n.select().from(B).$dynamic();if(l){const v=je(B,l,["friendly_name"]);v&&(d=d.where(v))}if(r!=null&&r.sort_by){const v=B[r.sort_by];v&&(d=d.orderBy(r.sort_order==="desc"?ce(v):ge(v)))}const f=(await d.offset(t*i).limit(i)).map(Ii);if(!a)return{tenants:f};const[p]=await n.select({count:he()}).from(B);return{tenants:f,start:t*i,limit:i,length:Number((p==null?void 0:p.count)??0)}},async update(e,t){const i=Ci({...t,id:e,updated_at:new Date().toISOString()});await n.update(B).set(i).where(c(B.id,e))},async remove(e){return(await n.delete(B).where(c(B.id,e)).returning()).length>0}}}const i_=["colors","borders","fonts","page_background","widget"];function Di(n){const{tenant_id:e,...t}=n,i=or(t,i_);return i.borders&&(i.borders.show_widget_shadow=!!i.borders.show_widget_shadow),i.fonts&&(i.fonts.links_bold=!!i.fonts.links_bold,i.fonts.subtitle_bold=!!i.fonts.subtitle_bold,i.fonts.title_bold=!!i.fonts.title_bold),K(i)}function a_(n){return{async create(e,t,i){const a=new Date().toISOString(),r=i||Ie(),d={...Wn(t),tenant_id:e,themeId:r,created_at:a,updated_at:a};return await n.insert(Me).values(d),Di({...d,tenant_id:e})},async get(e,t){const i=await n.select().from(Me).where(g(c(Me.tenant_id,e),c(Me.themeId,t))).get();return i?Di(i):null},async update(e,t,i){const a=Wn(i);return a.updated_at=new Date().toISOString(),await n.update(Me).set(a).where(g(c(Me.tenant_id,e),c(Me.themeId,t))),!0},async remove(e,t){return(await n.delete(Me).where(g(c(Me.tenant_id,e),c(Me.themeId,t))).returning()).length>0}}}function o_(n){return{async get(e){const t=await n.select({body:nt.body}).from(nt).where(c(nt.tenant_id,e)).get();return t?{body:t.body}:null},async set(e,t){const i=Date.now();await n.insert(nt).values({tenant_id:e,body:t.body,created_at_ts:i,updated_at_ts:i}).onConflictDoUpdate({target:nt.tenant_id,set:{body:t.body,updated_at_ts:i}})},async delete(e){await n.delete(nt).where(c(nt.tenant_id,e))}}}function Li(n,e){const t={connection:n.connection,provider:n.provider,user_id:n.user_id,isSocial:!!n.is_social};return e?t.isPrimary=!0:t.profileData={email:n.email,email_verified:!!n.email_verified,...typeof n.profileData=="string"?z(n.profileData,{}):{}},t}function Qn(n,e=[]){const{tenant_id:t,app_metadata:i,user_metadata:a,address:r,email_verified:l,phone_verified:d,is_social:u,linked_to:f,profileData:p,...v}=n,m=Li(n,!0),N=e.map(T=>Li(T,!1));return K({...v,email:n.email||"",email_verified:!!l,phone_verified:d!=null?!!d:void 0,is_social:!!u,app_metadata:z(i,{}),user_metadata:z(a,{}),address:z(r),identities:[m,...N]})}function r_(n){const e=async(t,i)=>{var d,u;const a=new Date().toISOString(),r={user_id:i.user_id,tenant_id:t,email:i.email,given_name:i.given_name,family_name:i.family_name,nickname:i.nickname,name:i.name,picture:i.picture,tags:i.tags,phone_number:i.phone_number,phone_verified:i.phone_verified??!1,username:i.username,linked_to:i.linked_to,last_ip:i.last_ip,login_count:i.login_count??0,last_login:i.last_login,provider:i.provider,connection:i.connection,email_verified:i.email_verified??!1,is_social:i.is_social??!1,app_metadata:JSON.stringify(i.app_metadata||{}),user_metadata:JSON.stringify(i.user_metadata||{}),address:i.address?JSON.stringify(i.address):void 0,profileData:i.profileData?JSON.stringify(i.profileData):void 0,locale:i.locale,middle_name:i.middle_name,preferred_username:i.preferred_username,profile:i.profile,website:i.website,gender:i.gender,birthdate:i.birthdate,zoneinfo:i.zoneinfo,created_at:i.created_at||a,updated_at:i.updated_at||a},l=i.password?Ie():void 0;try{if(i.password&&l){await n.run(A`BEGIN`);try{await n.insert(V).values(r),await n.insert(te).values({id:l,tenant_id:t,user_id:i.user_id,password:i.password.hash||i.password,algorithm:i.password.algorithm||"bcrypt",is_current:1,created_at:a,updated_at:a}),await n.run(A`COMMIT`)}catch(f){throw await n.run(A`ROLLBACK`),f}}else await n.insert(V).values(r)}catch(f){throw(d=f==null?void 0:f.message)!=null&&d.includes("UNIQUE constraint")||(u=f==null?void 0:f.message)!=null&&u.includes("AlreadyExists")?new rt(409,{message:"User already exists"}):(console.error("User upsert failed:",f==null?void 0:f.code,f==null?void 0:f.message),new rt(500,{message:"Internal server error"}))}return Qn(r)};return{create:e,rawCreate:e,async get(t,i){const a=await n.select().from(V).where(g(c(V.tenant_id,t),c(V.user_id,i))).get();if(!a)return null;const r=await n.select().from(V).where(g(c(V.tenant_id,t),c(V.linked_to,i))).all();return Qn(a,r)},async update(t,i,a){const r={updated_at:new Date().toISOString()},l=["email","given_name","family_name","nickname","name","picture","tags","phone_number","username","linked_to","last_ip","login_count","last_login","provider","connection","locale","middle_name","preferred_username","profile","website","gender","birthdate","zoneinfo"];for(const u of l)a[u]!==void 0&&(r[u]=a[u]);return a.email_verified!==void 0&&(r.email_verified=a.email_verified),a.phone_verified!==void 0&&(r.phone_verified=a.phone_verified),a.is_social!==void 0&&(r.is_social=a.is_social),a.app_metadata!==void 0&&(r.app_metadata=JSON.stringify(a.app_metadata)),a.user_metadata!==void 0&&(r.user_metadata=JSON.stringify(a.user_metadata)),a.address!==void 0&&(r.address=JSON.stringify(a.address)),a.profileData!==void 0&&(r.profileData=JSON.stringify(a.profileData)),(await n.update(V).set(r).where(g(c(V.tenant_id,t),c(V.user_id,i))).returning()).length>0},async list(t,i){const{page:a=0,per_page:r=50,include_totals:l=!1,sort:d,q:u}=i||{},f=[c(V.tenant_id,t),Ae(V.linked_to)];if(u){const ae=je(V,u,["email","name","nickname","username"]);ae&&f.push(ae)}const p=g(...f);let v=n.select().from(V).where(p).$dynamic();if(d!=null&&d.sort_by){const ae=V[d.sort_by];ae&&(v=v.orderBy(d.sort_order==="desc"?ce(ae):ge(ae)))}const m=await v.offset(a*r).limit(r),N=m.map(ae=>ae.user_id);let T=[];N.length>0&&(T=await n.select().from(V).where(g(c(V.tenant_id,t),Ye(V.linked_to,N))));const ee=m.map(ae=>{const Ge=T.filter(ut=>ut.linked_to===ae.user_id);return Qn(ae,Ge)});if(!l)return{users:ee};const[ie]=await n.select({count:he()}).from(V).where(p);return{users:ee,start:a*r,limit:r,length:Number((ie==null?void 0:ie.count)??0)}},async remove(t,i){await n.run(A`BEGIN`);try{const a=await n.select({user_id:V.user_id}).from(V).where(g(c(V.tenant_id,t),c(V.linked_to,i))),r=[i,...a.map(d=>d.user_id)];await n.delete(ue).where(g(c(ue.tenant_id,t),Ye(ue.user_id,r))),await n.delete(te).where(g(c(te.tenant_id,t),Ye(te.user_id,r))),await n.delete(V).where(g(c(V.tenant_id,t),c(V.linked_to,i)));const l=await n.delete(V).where(g(c(V.tenant_id,t),c(V.user_id,i))).returning();return await n.run(A`COMMIT`),l.length>0}catch(a){throw await n.run(A`ROLLBACK`),a}},async unlink(t,i,a,r){const l=`${a}|${r}`;return(await n.update(V).set({linked_to:null}).where(g(c(V.tenant_id,t),c(V.user_id,l),c(V.linked_to,i))).returning()).length>0}}}function s_(n){return{async create(e,t,i,a){var r,l;try{await n.insert(Re).values({tenant_id:e,user_id:t,role_id:i,organization_id:a||"",created_at:new Date().toISOString()})}catch(d){if((r=d==null?void 0:d.message)!=null&&r.includes("UNIQUE constraint")||(l=d==null?void 0:d.message)!=null&&l.includes("SQLITE_CONSTRAINT_PRIMARYKEY"))return!0;throw d}return!0},async list(e,t,i,a){let r=[c(Re.tenant_id,e),c(Re.user_id,t)];a&&r.push(c(Re.organization_id,a));const l=await n.select({role_id:Re.role_id}).from(Re).where(g(...r)).all();return l.length===0?[]:(await Promise.all(l.map(async u=>{const f=await n.select().from(_e).where(g(c(_e.tenant_id,e),c(_e.id,u.role_id))).get();if(!f)return null;const{tenant_id:p,is_system:v,metadata:m,...N}=f;return K({...N,is_system:v?!0:void 0,metadata:z(m)})}))).filter(Boolean)},async remove(e,t,i,a){return(await n.delete(Re).where(g(c(Re.tenant_id,e),c(Re.user_id,t),c(Re.role_id,i),c(Re.organization_id,a||""))).returning()).length>0}}}function l_(n){return{async create(e,t){var u,f;const i=new Date().toISOString(),r={id:t.id||Ie(),tenant_id:e,user_id:t.user_id,organization_id:t.organization_id,created_at:i,updated_at:i};try{await n.insert(se).values(r)}catch(p){throw(u=p==null?void 0:p.message)!=null&&u.includes("UNIQUE constraint")||(f=p==null?void 0:p.message)!=null&&f.includes("duplicate key")?new rt(409,{message:"User organization already exists"}):p}const{tenant_id:l,...d}=r;return d},async get(e,t){const i=await n.select().from(se).where(g(c(se.tenant_id,e),c(se.id,t))).get();if(!i)return null;const{tenant_id:a,...r}=i;return r},async update(e,t,i){const a={updated_at:new Date().toISOString()};return i.user_id!==void 0&&(a.user_id=i.user_id),i.organization_id!==void 0&&(a.organization_id=i.organization_id),(await n.update(se).set(a).where(g(c(se.tenant_id,e),c(se.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:a=50,include_totals:r=!1,q:l}=t||{},d=c(se.tenant_id,e);let u=d;if(l){const m=je(se,l,["user_id","organization_id"]);m&&(u=g(d,m))}const p=(await n.select().from(se).where(u).offset(i*a).limit(a)).map(m=>{const{tenant_id:N,...T}=m;return T});if(!r)return{userOrganizations:p};const[v]=await n.select({count:he()}).from(se).where(u);return{userOrganizations:p,start:i*a,limit:a,length:Number((v==null?void 0:v.count)??0)}},async listUserOrganizations(e,t,i){const{page:a=0,per_page:r=50,include_totals:l=!1}=i||{},d=await n.select().from(se).where(g(c(se.tenant_id,e),c(se.user_id,t))).offset(a*r).limit(r).all(),f=(await Promise.all(d.map(async v=>{const m=await n.select().from(W).where(g(c(W.tenant_id,e),c(W.id,v.organization_id))).get();if(!m)return null;const{tenant_id:N,branding:T,metadata:ee,enabled_connections:ie,token_quota:ae,...Ge}=m;return K({...Ge,branding:z(T,{}),metadata:z(ee,{}),enabled_connections:z(ie,[]),token_quota:z(ae,{})})}))).filter(Boolean);if(!l)return{organizations:f};const[p]=await n.select({count:he()}).from(se).where(g(c(se.tenant_id,e),c(se.user_id,t)));return{organizations:f,start:a*r,limit:r,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(se).where(g(c(se.tenant_id,e),c(se.id,t))).returning()).length>0}}}const Ri=["s","seacft","seccft","sepft","sertft","ssa"],d_=["pwd_leak","signup_pwd_leak","reset_pwd_leak"];function c_(n){return{async getDaily(e,t){const i=new Date,a=(t==null?void 0:t.from)||new Date(i.getTime()-30*24*60*60*1e3).toISOString().split("T")[0],r=(t==null?void 0:t.to)||i.toISOString().split("T")[0];return(await n.select({date:A`substr(${Q.date}, 1, 10)`.as("date"),logins:A`SUM(CASE WHEN ${Q.type} IN (${A.join(Ri.map(d=>A`${d}`),A`, `)}) THEN 1 ELSE 0 END)`.as("logins"),signups:A`SUM(CASE WHEN ${Q.type} = 'ss' THEN 1 ELSE 0 END)`.as("signups"),leaked_passwords:A`SUM(CASE WHEN ${Q.type} IN (${A.join(d_.map(d=>A`${d}`),A`, `)}) THEN 1 ELSE 0 END)`.as("leaked_passwords")}).from(Q).where(g(c(Q.tenant_id,e),sn(Q.date,a),ft(Q.date,`${r}T23:59:59.999Z`))).groupBy(A`substr(${Q.date}, 1, 10)`).orderBy(A`substr(${Q.date}, 1, 10)`).all()).map(d=>({date:d.date,logins:Number(d.logins)||0,signups:Number(d.signups)||0,leaked_passwords:Number(d.leaked_passwords)||0,created_at:new Date().toISOString(),updated_at:new Date().toISOString()}))},async getActiveUsers(e){const t=new Date(Date.now()-2592e6).toISOString(),[i]=await n.select({count:A`COUNT(DISTINCT ${Q.user_id})`.as("count")}).from(Q).where(g(c(Q.tenant_id,e),sn(Q.date,t),A`${Q.type} IN (${A.join(Ri.map(a=>A`${a}`),A`, `)})`));return Number(i==null?void 0:i.count)||0}}}function Ui(n){return{...n,payload:z(n.payload,{})}}function __(n){return{async create(e,t){const i=Ie(),a=new Date().toISOString();return await n.insert(F).values({id:i,tenant_id:e,event_type:t.event_type,log_type:t.log_type,aggregate_type:t.aggregate_type,aggregate_id:t.aggregate_id,payload:JSON.stringify({...t,id:i}),created_at:a,processed_at:null,retry_count:0,next_retry_at:null,error:null,claimed_by:null,claim_expires_at:null}),i},async getByIds(e){return e.length===0?[]:(await n.select().from(F).where(Ye(F.id,e)).all()).map(Ui)},async getUnprocessed(e){const t=new Date().toISOString();return(await n.select().from(F).where(g(Ae(F.processed_at),Ue(Ae(F.next_retry_at),ft(F.next_retry_at,t)),Ue(Ae(F.claimed_by),ft(F.claim_expires_at,t)))).orderBy(F.created_at,F.id).limit(e).all()).map(Ui)},async claimEvents(e,t,i){if(e.length===0)return[];const a=new Date().toISOString(),r=new Date(Date.now()+i).toISOString();return await n.update(F).set({claimed_by:t,claim_expires_at:r}).where(g(Ye(F.id,e),Ae(F.processed_at),Ue(Ae(F.claimed_by),ft(F.claim_expires_at,a)))),(await n.select({id:F.id}).from(F).where(g(Ye(F.id,e),c(F.claimed_by,t))).all()).map(d=>d.id)},async markProcessed(e){e.length!==0&&await n.update(F).set({processed_at:new Date().toISOString()}).where(Ye(F.id,e))},async markRetry(e,t,i){await n.update(F).set({error:t,next_retry_at:i,retry_count:A`${F.retry_count} + 1`,claimed_by:null,claim_expires_at:null}).where(c(F.id,e))},async cleanup(e){return(await n.delete(F).where(g(A`${F.processed_at} IS NOT NULL`,ft(F.processed_at,e))).returning()).length},async deadLetter(e,t){const i=new Date().toISOString();await n.update(F).set({processed_at:i,dead_lettered_at:i,final_error:t}).where(c(F.id,e))},async listFailed(e,t={}){const{page:i=0,per_page:a=50,include_totals:r=!1}=t,d=(await n.select().from(F).where(g(c(F.tenant_id,e),nn(F.dead_lettered_at))).orderBy(ce(F.dead_lettered_at),ge(F.id)).offset(i*a).limit(a).all()).map(f=>({...z(f.payload,{}),id:f.id,created_at:f.created_at,processed_at:f.processed_at,retry_count:f.retry_count,next_retry_at:f.next_retry_at,error:f.error,dead_lettered_at:f.dead_lettered_at,final_error:f.final_error}));let u=d.length;if(r){const[f]=await n.select({total:he()}).from(F).where(g(c(F.tenant_id,e),nn(F.dead_lettered_at)));u=Number((f==null?void 0:f.total)??d.length)}return{events:d,start:i*a,limit:a,length:u}},async replay(e,t){return(await n.update(F).set({processed_at:null,dead_lettered_at:null,final_error:null,retry_count:0,next_retry_at:null,error:null}).where(g(c(F.id,e),c(F.tenant_id,t),nn(F.dead_lettered_at))).returning()).length>0}}}const u_=7*24*60*60*1e3;function p_(n){return async e=>{const t=Date.now()-u_;try{let i=[Ue(Xe(X.expires_at_ts,t),Xe(X.idle_expires_at_ts,t))];e!=null&&e.tenant_id&&i.push(c(X.tenant_id,e.tenant_id)),await n.delete(X).where(g(...i)),i=[Ue(Xe(oe.expires_at_ts,t),Xe(oe.idle_expires_at_ts,t))],e!=null&&e.tenant_id&&i.push(c(oe.tenant_id,e.tenant_id)),e!=null&&e.user_id&&i.push(c(oe.user_id,e.user_id)),await n.delete(oe).where(g(...i)),i=[Xe(J.expires_at_ts,t)],e!=null&&e.tenant_id&&i.push(c(J.tenant_id,e.tenant_id)),await n.delete(J).where(g(...i))}catch(i){console.error("Session cleanup error:",i)}}}function f_(n,e={useTransactions:!0}){const t={actions:$r(),branding:as(n),clients:os(n),clientConnections:ss(n),clientGrants:us(n),clientRegistrationTokens:wc(n),codes:Sc(n),connections:bc(n),customDomains:Ec(n),customText:xc(n),emailProviders:kc(n),flows:Oc(n),forms:Tc(n),hookCode:Cc(n),hooks:Lc(n),invites:Uc(n),keys:zc(n),loginSessions:Pc(n),logs:Mc(n),authenticationMethods:Bc(n),organizations:jc(n),passwords:Vc(n),promptSettings:Zc(n),refreshTokens:Kc(n),resourceServers:Gc(n),rolePermissions:Jc(n),userPermissions:Wc(n),roles:Xc(n),sessions:t_(n),sessionCleanup:p_(n),tenants:n_(n),themes:a_(n),universalLoginTemplates:o_(n),users:r_(n),userRoles:s_(n),userOrganizations:l_(n),stats:c_(n),outbox:__(n),async transaction(i){if(e.useTransactions===!1)return i(t);await n.run(A`BEGIN`);try{const a=await i(t);return await n.run(A`COMMIT`),a}catch(a){throw await n.run(A`ROLLBACK`),a}}};return t}exports.default=f_;exports.sqlite=es;