@authhero/drizzle 0.50.0 → 0.50.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var Zs=Object.defineProperty;var Hs=(n,e,t)=>e in n?Zs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var v=(n,e,t)=>Hs(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const L=Symbol.for("drizzle:entityKind");function ve(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 $i;$i=L;class en{constructor(e,t){v(this,"name");v(this,"keyAsName");v(this,"primary");v(this,"notNull");v(this,"default");v(this,"defaultFn");v(this,"onUpdateFn");v(this,"hasDefault");v(this,"isUnique");v(this,"uniqueName");v(this,"uniqueType");v(this,"dataType");v(this,"columnType");v(this,"enumValues");v(this,"generated");v(this,"generatedIdentity");v(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"}}v(en,$i,"Column");var ji;ji=L;class Ta{constructor(e,t,i){v(this,"config");v(this,"$default",this.$defaultFn);v(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)}}v(Ta,ji,"ColumnBuilder");const Ot=Symbol.for("drizzle:Name"),Ei=Symbol.for("drizzle:isPgEnum");function Ks(n){return!!n&&typeof n=="function"&&Ei in n&&n[Ei]===!0}var Vi;Vi=L;class hi{constructor(e,t,i,o=!1,s=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:i,isWith:o,usedTables:s}}}v(hi,Vi,"Subquery");const Js={startActiveSpan(n,e){return e()}},zt=Symbol.for("drizzle:ViewBaseConfig"),In=Symbol.for("drizzle:Schema"),xi=Symbol.for("drizzle:Columns"),ki=Symbol.for("drizzle:ExtraConfigColumns"),Cn=Symbol.for("drizzle:OriginalName"),Dn=Symbol.for("drizzle:BaseName"),_n=Symbol.for("drizzle:IsAlias"),Oi=Symbol.for("drizzle:ExtraConfigBuilder"),Qs=Symbol.for("drizzle:IsDrizzleTable");var Zi,Hi,Ki,Ji,Qi,Gi,Wi,Xi,Yi,eo;eo=L,Yi=Ot,Xi=Cn,Wi=In,Gi=xi,Qi=ki,Ji=Dn,Ki=_n,Hi=Qs,Zi=Oi;class fe{constructor(e,t,i){v(this,Yi);v(this,Xi);v(this,Wi);v(this,Gi);v(this,Qi);v(this,Ji);v(this,Ki,!1);v(this,Hi,!0);v(this,Zi);this[Ot]=this[Cn]=e,this[In]=t,this[Dn]=i}}v(fe,eo,"Table"),v(fe,"Symbol",{Name:Ot,Schema:In,OriginalName:Cn,Columns:xi,ExtraConfigColumns:ki,BaseName:Dn,IsAlias:_n,ExtraConfigBuilder:Oi});function Aa(n){return n!=null&&typeof n.getSQL=="function"}function Gs(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 to;to=L;class we{constructor(e){v(this,"value");this.value=Array.isArray(e)?e:[e]}getSQL(){return new ce([this])}}v(we,to,"StringChunk");var no;no=L;const mt=class mt{constructor(e){v(this,"decoder",Ia);v(this,"shouldInlineParams",!1);v(this,"usedTables",[]);this.queryChunks=e;for(const t of e)if(ve(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 Js.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:o,escapeName:s,escapeParam:l,prepareTyping:d,inlineParams:u,paramStartIndex:f}=i;return Gs(e.map(p=>{var m;if(ve(p,we))return{sql:p.value.join(""),params:[]};if(ve(p,un))return{sql:s(p.value),params:[]};if(p===void 0)return{sql:"",params:[]};if(Array.isArray(p)){const y=[new we("(")];for(const[E,T]of p.entries())y.push(T),E<p.length-1&&y.push(new we(", "));return y.push(new we(")")),this.buildQueryFromSourceParams(y,i)}if(ve(p,mt))return this.buildQueryFromSourceParams(p.queryChunks,{...i,inlineParams:u||p.shouldInlineParams});if(ve(p,fe)){const y=p[fe.Symbol.Schema],E=p[fe.Symbol.Name];return{sql:y===void 0||p[_n]?s(E):s(y)+"."+s(E),params:[]}}if(ve(p,en)){const y=o.getColumnCasing(p);if(t.invokeSource==="indexes")return{sql:s(y),params:[]};const E=p.table[fe.Symbol.Schema];return{sql:p.table[_n]||E===void 0?s(p.table[fe.Symbol.Name])+"."+s(y):s(E)+"."+s(p.table[fe.Symbol.Name])+"."+s(y),params:[]}}if(ve(p,gi)){const y=p[zt].schema,E=p[zt].name;return{sql:y===void 0||p[zt].isAlias?s(E):s(y)+"."+s(E),params:[]}}if(ve(p,Ft)){if(ve(p.value,Pt))return{sql:l(f.value++,p),params:[p],typings:["none"]};const y=p.value===null?null:p.encoder.mapToDriverValue(p.value);if(ve(y,mt))return this.buildQueryFromSourceParams([y],i);if(u)return{sql:this.mapInlineParam(y,i),params:[]};let E=["none"];return d&&(E=[d(p.encoder)]),{sql:l(f.value++,y),params:[y],typings:E}}return ve(p,Pt)?{sql:l(f.value++,p),params:[p],typings:["none"]}:ve(p,mt.Aliased)&&p.fieldAlias!==void 0?{sql:s(p.fieldAlias),params:[]}:ve(p,hi)?p._.isWith?{sql:s(p._.alias),params:[]}:this.buildQueryFromSourceParams([new we("("),p._.sql,new we(") "),new un(p._.alias)],i):Ks(p)?p.schema?{sql:s(p.schema)+"."+s(p.enumName),params:[]}:{sql:s(p.enumName),params:[]}:Aa(p)?(m=p.shouldOmitSQLParens)!=null&&m.call(p)?this.buildQueryFromSourceParams([p.getSQL()],i):this.buildQueryFromSourceParams([new we("("),p.getSQL(),new we(")")],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 mt.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}};v(mt,no,"SQL");let ce=mt;var io;io=L;class un{constructor(e){v(this,"brand");this.value=e}getSQL(){return new ce([this])}}v(un,io,"Name");function Ws(n){return typeof n=="object"&&n!==null&&"mapToDriverValue"in n&&typeof n.mapToDriverValue=="function"}const Ia={mapFromDriverValue:n=>n},Ca={mapToDriverValue:n=>n};({...Ia,...Ca});var oo;oo=L;class Ft{constructor(e,t=Ca){v(this,"brand");this.value=e,this.encoder=t}getSQL(){return new ce([this])}}v(Ft,oo,"Param");function O(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new we(n[0]));for(const[i,o]of e.entries())t.push(o,new we(n[i+1]));return new ce(t)}(n=>{function e(){return new ce([])}n.empty=e;function t(u){return new ce(u)}n.fromList=t;function i(u){return new ce([new we(u)])}n.raw=i;function o(u,f){const p=[];for(const[m,y]of u.entries())m>0&&f!==void 0&&p.push(f),p.push(y);return new ce(p)}n.join=o;function s(u){return new un(u)}n.identifier=s;function l(u){return new Pt(u)}n.placeholder=l;function d(u,f){return new Ft(u,f)}n.param=d})(O||(O={}));(n=>{var t;t=L;const i=class i{constructor(s,l){v(this,"isSelectionField",!1);this.sql=s,this.fieldAlias=l}getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}};v(i,t,"SQL.Aliased");let e=i;n.Aliased=e})(ce||(ce={}));var ao;ao=L;class Pt{constructor(e){this.name=e}getSQL(){return new ce([this])}}v(Pt,ao,"Placeholder");const Xs=Symbol.for("drizzle:IsDrizzleView");var so,ro,lo;lo=L,ro=zt,so=Xs;class gi{constructor({name:e,schema:t,selectedFields:i,query:o}){v(this,ro);v(this,so,!0);this[zt]={name:e,originalName:e,schema:t,selectedFields:i,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new ce([this])}}v(gi,lo,"View");en.prototype.getSQL=function(){return new ce([this])};fe.prototype.getSQL=function(){return new ce([this])};hi.prototype.getSQL=function(){return new ce([this])};function tn(n,e){return{name:typeof n=="string"&&n.length>0?n:"",config:typeof n=="object"?n:e}}const Da=typeof TextDecoder>"u"?null:new TextDecoder;function ct(n,e){return Ws(e)&&!Aa(n)&&!ve(n,Ft)&&!ve(n,Pt)&&!ve(n,en)&&!ve(n,fe)&&!ve(n,gi)?new Ft(n,e):n}const c=(n,e)=>O`${n} = ${ct(e,n)}`,Ys=(n,e)=>O`${n} <> ${ct(e,n)}`;function g(...n){const e=n.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new ce(e):new ce([new we("("),O.join(e,new we(" and ")),new we(")")])}function $e(...n){const e=n.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new ce(e):new ce([new we("("),O.join(e,new we(" or ")),new we(")")])}const pn=(n,e)=>O`${n} > ${ct(e,n)}`,Tt=(n,e)=>O`${n} >= ${ct(e,n)}`,Qe=(n,e)=>O`${n} < ${ct(e,n)}`,yt=(n,e)=>O`${n} <= ${ct(e,n)}`;function De(n,e){return Array.isArray(e)?e.length===0?O`false`:O`${n} in ${e.map(t=>ct(t,n))}`:O`${n} in ${ct(e,n)}`}function Ce(n){return O`${n} is null`}function cn(n){return O`${n} is not null`}function xt(n,e){return O`${n} like ${e}`}function he(n){return O`${n} asc`}function se(n){return O`${n} desc`}function ge(n){return O`count(${O.raw("*")})`.mapWith(Number)}function er(){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")}}function tr(){const n=e=>{throw new Error(`Action executions 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")}}function nr(){const n=e=>{throw new Error(`Action versions 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"),removeForAction:()=>n("removeForAction")}}var co;co=L;class La{constructor(e,t){v(this,"reference");v(this,"_onUpdate");v(this,"_onDelete");this.reference=()=>{const{name:i,columns:o,foreignColumns:s}=e();return{name:i,columns:o,foreignTable:s[0].table,foreignColumns:s}},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 Ra(e,this)}}v(La,co,"SQLiteForeignKeyBuilder");var _o;_o=L;class Ra{constructor(e,t){v(this,"reference");v(this,"onUpdate");v(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(),o=t.map(d=>d.name),s=i.map(d=>d.name),l=[this.table[Ot],...o,i[0].table[Ot],...s];return e??`${l.join("_")}_fk`}}v(Ra,_o,"SQLiteForeignKey");function ir(n,e){return`${n[Ot]}_${e.join("_")}_unique`}var uo,po;class je extends(po=Ta,uo=L,po){constructor(){super(...arguments);v(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:o,actions:s})=>((l,d)=>{const u=new La(()=>{const f=l();return{columns:[t],foreignColumns:[f]}});return d.onUpdate&&u.onUpdate(d.onUpdate),d.onDelete&&u.onDelete(d.onDelete),u.build(i)})(o,s))}}v(je,uo,"SQLiteColumnBuilder");var fo,ho;class Ve extends(ho=en,fo=L,ho){constructor(e,t){t.uniqueName||(t.uniqueName=ir(e,[t.name])),super(e,t),this.table=e}}v(Ve,fo,"SQLiteColumn");var go,mo;class Ua extends(mo=je,go=L,mo){constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new za(e,this.config)}}v(Ua,go,"SQLiteBigIntBuilder");var yo,vo;class za extends(vo=Ve,yo=L,vo){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(Da.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}}v(za,yo,"SQLiteBigInt");var wo,So;class Fa extends(So=je,wo=L,So){constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new Pa(e,this.config)}}v(Fa,wo,"SQLiteBlobJsonBuilder");var No,bo;class Pa extends(bo=Ve,No=L,bo){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(Da.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}}v(Pa,No,"SQLiteBlobJson");var Eo,xo;class Ma extends(xo=je,Eo=L,xo){constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new qa(e,this.config)}}v(Ma,Eo,"SQLiteBlobBufferBuilder");var ko,Oo;class qa extends(Oo=Ve,ko=L,Oo){mapFromDriverValue(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}getSQLType(){return"blob"}}v(qa,ko,"SQLiteBlobBuffer");function or(n,e){const{name:t,config:i}=tn(n,e);return(i==null?void 0:i.mode)==="json"?new Fa(t):(i==null?void 0:i.mode)==="bigint"?new Ua(t):new Ma(t)}var To,Ao;class Ba extends(Ao=je,To=L,Ao){constructor(e,t,i){super(e,"custom","SQLiteCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=i}build(e){return new $a(e,this.config)}}v(Ba,To,"SQLiteCustomColumnBuilder");var Io,Co;class $a extends(Co=Ve,Io=L,Co){constructor(t,i){super(t,i);v(this,"sqlName");v(this,"mapTo");v(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}}v($a,Io,"SQLiteCustomColumn");function ar(n){return(e,t)=>{const{name:i,config:o}=tn(e,t);return new Ba(i,o,n)}}var Do,Lo;class vn extends(Lo=je,Do=L,Lo){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()}}v(vn,Do,"SQLiteBaseIntegerBuilder");var Ro,Uo;class wn extends(Uo=Ve,Ro=L,Uo){constructor(){super(...arguments);v(this,"autoIncrement",this.config.autoIncrement)}getSQLType(){return"integer"}}v(wn,Ro,"SQLiteBaseInteger");var zo,Fo;class ja extends(Fo=vn,zo=L,Fo){constructor(e){super(e,"number","SQLiteInteger")}build(e){return new Va(e,this.config)}}v(ja,zo,"SQLiteIntegerBuilder");var Po,Mo;class Va extends(Mo=wn,Po=L,Mo){}v(Va,Po,"SQLiteInteger");var qo,Bo;class Za extends(Bo=vn,qo=L,Bo){constructor(e,t){super(e,"date","SQLiteTimestamp"),this.config.mode=t}defaultNow(){return this.default(O`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new Ha(e,this.config)}}v(Za,qo,"SQLiteTimestampBuilder");var $o,jo;class Ha extends(jo=wn,$o=L,jo){constructor(){super(...arguments);v(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}}v(Ha,$o,"SQLiteTimestamp");var Vo,Zo;class Ka extends(Zo=vn,Vo=L,Zo){constructor(e,t){super(e,"boolean","SQLiteBoolean"),this.config.mode=t}build(e){return new Ja(e,this.config)}}v(Ka,Vo,"SQLiteBooleanBuilder");var Ho,Ko;class Ja extends(Ko=wn,Ho=L,Ko){constructor(){super(...arguments);v(this,"mode",this.config.mode)}mapFromDriverValue(t){return Number(t)===1}mapToDriverValue(t){return t?1:0}}v(Ja,Ho,"SQLiteBoolean");function w(n,e){const{name:t,config:i}=tn(n,e);return(i==null?void 0:i.mode)==="timestamp"||(i==null?void 0:i.mode)==="timestamp_ms"?new Za(t,i.mode):(i==null?void 0:i.mode)==="boolean"?new Ka(t,i.mode):new ja(t)}var Jo,Qo;class Qa extends(Qo=je,Jo=L,Qo){constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new Ga(e,this.config)}}v(Qa,Jo,"SQLiteNumericBuilder");var Go,Wo;class Ga extends(Wo=Ve,Go=L,Wo){mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return"numeric"}}v(Ga,Go,"SQLiteNumeric");var Xo,Yo;class Wa extends(Yo=je,Xo=L,Yo){constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new Xa(e,this.config)}}v(Wa,Xo,"SQLiteNumericNumberBuilder");var ea,ta;class Xa extends(ta=Ve,ea=L,ta){constructor(){super(...arguments);v(this,"mapToDriverValue",String)}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}getSQLType(){return"numeric"}}v(Xa,ea,"SQLiteNumericNumber");var na,ia;class Ya extends(ia=je,na=L,ia){constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new es(e,this.config)}}v(Ya,na,"SQLiteNumericBigIntBuilder");var oa,aa;class es extends(aa=Ve,oa=L,aa){constructor(){super(...arguments);v(this,"mapFromDriverValue",BigInt);v(this,"mapToDriverValue",String)}getSQLType(){return"numeric"}}v(es,oa,"SQLiteNumericBigInt");function sr(n,e){const{name:t,config:i}=tn(n,e),o=i==null?void 0:i.mode;return o==="number"?new Wa(t):o==="bigint"?new Ya(t):new Qa(t)}var sa,ra;class ts extends(ra=je,sa=L,ra){constructor(e){super(e,"number","SQLiteReal")}build(e){return new ns(e,this.config)}}v(ts,sa,"SQLiteRealBuilder");var la,da;class ns extends(da=Ve,la=L,da){getSQLType(){return"real"}}v(ns,la,"SQLiteReal");function rr(n){return new ts(n??"")}var ca,_a;class is extends(_a=je,ca=L,_a){constructor(e,t){super(e,"string","SQLiteText"),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new os(e,this.config)}}v(is,ca,"SQLiteTextBuilder");var ua,pa;class os extends(pa=Ve,ua=L,pa){constructor(t,i){super(t,i);v(this,"enumValues",this.config.enumValues);v(this,"length",this.config.length)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}v(os,ua,"SQLiteText");var fa,ha;class as extends(ha=je,fa=L,ha){constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new ss(e,this.config)}}v(as,fa,"SQLiteTextJsonBuilder");var ga,ma;class ss extends(ma=Ve,ga=L,ma){getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}v(ss,ga,"SQLiteTextJson");function r(n,e={}){const{name:t,config:i}=tn(n,e);return i.mode==="json"?new as(t):new is(t,i)}function lr(){return{blob:or,customType:ar,integer:w,numeric:sr,real:rr,text:r}}const Wn=Symbol.for("drizzle:SQLiteInlineForeignKeys");var ya,va,wa,Sa,Na;class Mt extends(Na=fe,Sa=L,wa=fe.Symbol.Columns,va=Wn,ya=fe.Symbol.ExtraConfigBuilder,Na){constructor(){super(...arguments);v(this,wa);v(this,va,[]);v(this,ya)}}v(Mt,Sa,"SQLiteTable"),v(Mt,"Symbol",Object.assign({},fe.Symbol,{InlineForeignKeys:Wn}));function dr(n,e,t,i,o=n){const s=new Mt(n,i,o),l=typeof e=="function"?e(lr()):e,d=Object.fromEntries(Object.entries(l).map(([f,p])=>{const m=p;m.setName(f);const y=m.build(s);return s[Wn].push(...m.buildForeignKeys(y,s)),[f,y]})),u=Object.assign(s,d);return u[fe.Symbol.Columns]=d,u[fe.Symbol.ExtraConfigColumns]=d,t&&(u[Mt.Symbol.ExtraConfigBuilder]=t),u}const j=(n,e,t)=>dr(n,e,t);var ba;ba=L;class mi{constructor(e,t){this.name=e,this.unique=t}on(...e){return new rs(this.name,e,this.unique)}}v(mi,ba,"SQLiteIndexBuilderOn");var Ea;Ea=L;class rs{constructor(e,t,i){v(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 ls(this.config,e)}}v(rs,Ea,"SQLiteIndexBuilder");var xa;xa=L;class ls{constructor(e,t){v(this,"config");this.config={...e,table:t}}}v(ls,xa,"SQLiteIndex");function D(n){return new mi(n,!1)}function vt(n){return new mi(n,!0)}function Ae(...n){return n[0].columns?new Xn(n[0].columns,n[0].name):new Xn(n)}var ka;ka=L;class Xn{constructor(e,t){v(this,"columns");v(this,"name");this.columns=e,this.name=t}build(e){return new ds(e,this.columns,this.name)}}v(Xn,ka,"SQLitePrimaryKeyBuilder");var Oa;Oa=L;class ds{constructor(e,t,i){v(this,"columns");v(this,"name");this.table=e,this.columns=t,this.name=i}getName(){return this.name??`${this.table[Mt.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}v(ds,Oa,"SQLitePrimaryKey");const B=j("tenants",{id:r("id",{length:191}).primaryKey(),name:r("name",{length:255}),audience:r("audience",{length:255}),sender_email:r("sender_email",{length:255}),sender_name:r("sender_name",{length:255}),language:r("language",{length:255}),logo:r("logo",{length:255}),primary_color:r("primary_color",{length:255}),secondary_color:r("secondary_color",{length:255}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),support_url:r("support_url",{length:255}),idle_session_lifetime:w("idle_session_lifetime"),session_lifetime:w("session_lifetime"),session_cookie:r("session_cookie"),allowed_logout_urls:r("allowed_logout_urls"),ephemeral_session_lifetime:w("ephemeral_session_lifetime"),idle_ephemeral_session_lifetime:w("idle_ephemeral_session_lifetime"),default_redirection_uri:r("default_redirection_uri"),default_client_id:r("default_client_id",{length:255}),enabled_locales:r("enabled_locales"),default_directory:r("default_directory",{length:255}),error_page:r("error_page"),flags:r("flags"),friendly_name:r("friendly_name",{length:255}),picture_url:r("picture_url"),support_email:r("support_email",{length:255}),sandbox_version:r("sandbox_version",{length:50}),sandbox_versions_available:r("sandbox_versions_available"),legacy_sandbox_version:r("legacy_sandbox_version",{length:50}),change_password:r("change_password"),guardian_mfa_page:r("guardian_mfa_page"),device_flow:r("device_flow"),default_token_quota:r("default_token_quota"),default_audience:r("default_audience",{length:255}),default_organization:r("default_organization",{length:255}),sessions:r("sessions"),oidc_logout:r("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:r("acr_values_supported"),mtls:r("mtls"),pushed_authorization_requests_supported:w("pushed_authorization_requests_supported"),authorization_response_iss_parameter_supported:w("authorization_response_iss_parameter_supported")}),Z=j("users",{user_id:r("user_id",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),email:r("email",{length:255}),given_name:r("given_name",{length:255}),family_name:r("family_name",{length:255}),nickname:r("nickname",{length:255}),name:r("name",{length:255}),picture:r("picture",{length:2083}),tags:r("tags",{length:255}),phone_number:r("phone_number",{length:17}),phone_verified:w("phone_verified",{mode:"boolean"}),username:r("username",{length:128}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),linked_to:r("linked_to",{length:255}),last_ip:r("last_ip",{length:255}),login_count:w("login_count").notNull(),last_login:r("last_login",{length:255}),registration_completed_at:r("registration_completed_at",{length:35}),provider:r("provider",{length:255}).notNull(),connection:r("connection",{length:255}),email_verified:w("email_verified",{mode:"boolean"}).notNull(),is_social:w("is_social",{mode:"boolean"}).notNull(),app_metadata:r("app_metadata",{length:4096}).notNull().default("{}"),user_metadata:r("user_metadata").notNull().default("{}"),profileData:r("profileData",{length:2048}),locale:r("locale",{length:255}),middle_name:r("middle_name",{length:100}),preferred_username:r("preferred_username",{length:255}),profile:r("profile"),website:r("website"),gender:r("gender",{length:50}),birthdate:r("birthdate",{length:10}),zoneinfo:r("zoneinfo",{length:100}),address:r("address")},n=>[Ae({columns:[n.user_id,n.tenant_id],name:"users_tenants"}),vt("unique_email_provider").on(n.email,n.provider,n.tenant_id),vt("unique_phone_provider").on(n.phone_number,n.provider,n.tenant_id),vt("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)]),oe=j("passwords",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),password:r("password",{length:255}).notNull(),algorithm:r("algorithm",{length:16}).notNull().default("bcrypt"),is_current:w("is_current").notNull().default(1)}),ae=j("sessions",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("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:r("device").notNull(),clients:r("clients").notNull(),login_session_id:r("login_session_id",{length:21})},n=>[Ae({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)]),J=j("refresh_tokens",{id:r("id",{length:26}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),client_id:r("client_id",{length:191}).notNull(),login_id:r("login_id",{length:26}).notNull(),user_id:r("user_id",{length:255}),resource_servers:r("resource_servers").notNull(),device:r("device").notNull(),rotating:w("rotating",{mode:"boolean"}).notNull(),token_lookup:r("token_lookup",{length:16}),token_hash:r("token_hash",{length:64}),family_id:r("family_id",{length:26}),rotated_to:r("rotated_to",{length:26}),rotated_at_ts:w("rotated_at_ts"),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=>[Ae({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),D("idx_refresh_tokens_token_lookup").on(n.tenant_id,n.token_lookup),D("idx_refresh_tokens_family_id").on(n.tenant_id,n.family_id)]),Y=j("login_sessions",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),session_id:r("session_id",{length:21}),csrf_token:r("csrf_token",{length:21}).notNull(),auth_params:r("auth_params"),authorization_url:r("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:r("ip",{length:39}),useragent:r("useragent"),auth0Client:r("auth0Client",{length:255}),state:r("state",{length:50}).notNull().default("pending"),state_data:r("state_data"),failure_reason:r("failure_reason"),user_id:r("user_id",{length:255}),auth_connection:r("auth_connection",{length:255}),auth_strategy_strategy:r("auth_strategy_strategy",{length:64}),auth_strategy_strategy_type:r("auth_strategy_strategy_type",{length:64}),authenticated_at:r("authenticated_at",{length:35})},n=>[Ae({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=j("codes",{code_id:r("code_id",{length:191}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}),login_id:r("login_id",{length:255}),connection_id:r("connection_id",{length:255}),code_type:r("code_type",{length:255}).notNull(),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35}),code_verifier:r("code_verifier",{length:128}),code_challenge:r("code_challenge",{length:128}),code_challenge_method:r("code_challenge_method",{length:5}),redirect_uri:r("redirect_uri",{length:1024}),nonce:r("nonce",{length:1024}),state:r("state",{length:2048})},n=>[Ae({columns:[n.code_id,n.code_type],name:"PK_codes_code_id_code_type"}),D("codes_expires_at_index").on(n.expires_at)]),cr=j("authentication_codes",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),code:r("code",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),user_id:r("user_id",{length:255}).notNull(),nonce:r("nonce",{length:255}),state:r("state",{length:8192}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35})}),_r=j("otps",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),id:r("id",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),code:r("code",{length:255}).notNull(),email:r("email",{length:255}).notNull(),user_id:r("user_id",{length:255}),send:r("send",{length:255}),nonce:r("nonce",{length:255}),state:r("state",{length:1024}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35}),audience:r("audience",{length:255}),ip:r("ip",{length:64})},n=>[D("otps_email_index").on(n.email),D("otps_expires_at_index").on(n.expires_at)]),ur=j("tickets",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),id:r("id",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),email:r("email",{length:255}).notNull(),nonce:r("nonce",{length:255}),state:r("state",{length:1024}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35})}),H=j("clients",{client_id:r("client_id",{length:191}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:255}).notNull(),description:r("description",{length:140}),global:w("global").notNull().default(0),client_secret:r("client_secret",{length:255}),app_type:r("app_type",{length:64}).default("regular_web"),logo_uri:r("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:r("callbacks").notNull(),allowed_origins:r("allowed_origins").notNull(),web_origins:r("web_origins").notNull(),client_aliases:r("client_aliases").notNull(),allowed_clients:r("allowed_clients").notNull(),allowed_logout_urls:r("allowed_logout_urls").notNull(),session_transfer:r("session_transfer").notNull(),oidc_logout:r("oidc_logout").notNull(),grant_types:r("grant_types").notNull(),jwt_configuration:r("jwt_configuration").notNull(),signing_keys:r("signing_keys").notNull(),encryption_key:r("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:r("cross_origin_loc",{length:2083}),custom_login_page_on:w("custom_login_page_on").notNull().default(0),custom_login_page:r("custom_login_page"),custom_login_page_preview:r("custom_login_page_preview"),form_template:r("form_template"),addons:r("addons").notNull(),token_endpoint_auth_method:r("token_endpoint_auth_method",{length:64}).default("client_secret_basic"),client_metadata:r("client_metadata").notNull(),mobile:r("mobile").notNull(),initiate_login_uri:r("initiate_login_uri",{length:2083}),native_social_login:r("native_social_login").notNull(),refresh_token:r("refresh_token").notNull(),default_organization:r("default_organization").notNull(),organization_usage:r("organization_usage",{length:32}).default("deny"),organization_require_behavior:r("organization_require_behavior",{length:32}).default("no_prompt"),client_authentication_methods:r("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),hide_sign_up_disabled_error:w("hide_sign_up_disabled_error").notNull().default(0),signed_request_object:r("signed_request_object").notNull(),compliance_level:r("compliance_level",{length:64}),par_request_expiry:w("par_request_expiry"),token_quota:r("token_quota").notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),connections:r("connections").notNull().default("[]"),owner_user_id:r("owner_user_id",{length:255}),registration_type:r("registration_type",{length:32}),registration_metadata:r("registration_metadata"),user_linking_mode:r("user_linking_mode",{length:16})},n=>[Ae({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)]),X=j("client_registration_tokens",{id:r("id",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),token_hash:r("token_hash",{length:64}).notNull(),type:r("type",{length:8}).notNull(),client_id:r("client_id",{length:191}),sub:r("sub",{length:255}),constraints:r("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=>[vt("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)]),ye=j("client_grants",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),client_id:r("client_id",{length:191}).notNull(),audience:r("audience",{length:191}).notNull(),scope:r("scope").default("[]"),organization_usage:r("organization_usage",{length:32}),allow_any_organization:w("allow_any_organization").default(0),is_system:w("is_system").default(0),subject_type:r("subject_type",{length:32}),authorization_details_types:r("authorization_details_types").default("[]"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Ae({columns:[n.tenant_id,n.id],name:"pk_client_grants"}),D("idx_client_grants_audience").on(n.audience)]),pe=j("connections",{id:r("id",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:255}).notNull(),response_type:r("response_type",{length:255}),response_mode:r("response_mode",{length:255}),strategy:r("strategy",{length:64}),options:r("options",{length:8192}).notNull().default("{}"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),display_name:r("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:r("metadata",{length:4096})},n=>[Ae({columns:[n.tenant_id,n.id]}),D("connections_tenant_id_index").on(n.tenant_id),vt("connections_id_unique").on(n.id)]),Ie=j("custom_domains",{custom_domain_id:r("custom_domain_id",{length:256}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),domain:r("domain",{length:255}).notNull(),primary:w("primary",{mode:"boolean"}).notNull(),status:r("status",{length:50}).notNull(),type:r("type",{length:50}).notNull(),origin_domain_name:r("origin_domain_name",{length:255}),verification:r("verification",{length:2048}),custom_client_ip_header:r("custom_client_ip_header",{length:50}),tls_policy:r("tls_policy",{length:50}),domain_metadata:r("domain_metadata",{length:2048}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[vt("custom_domains_domain_unique").on(n.domain)]),pr=j("domains",{id:r("id",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),domain:r("domain",{length:255}).notNull(),email_service:r("email_service",{length:255}),email_api_key:r("email_api_key",{length:255}),dkim_private_key:r("dkim_private_key",{length:2048}),dkim_public_key:r("dkim_public_key",{length:2048}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()}),ee=j("organizations",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),name:r("name",{length:256}).notNull(),display_name:r("display_name",{length:256}),branding:r("branding"),metadata:r("metadata"),enabled_connections:r("enabled_connections"),token_quota:r("token_quota"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("idx_organizations_tenant_id").on(n.tenant_id)]),le=j("user_organizations",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[vt("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)]),xe=j("invites",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull(),inviter:r("inviter").notNull(),invitee:r("invitee").notNull(),client_id:r("client_id",{length:191}).notNull(),connection_id:r("connection_id",{length:21}),invitation_url:r("invitation_url").notNull(),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),app_metadata:r("app_metadata"),user_metadata:r("user_metadata"),roles:r("roles"),ticket_id:r("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=j("roles",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull(),name:r("name",{length:50}).notNull(),description:r("description",{length:255}),is_system:w("is_system").notNull().default(0),metadata:r("metadata",{length:4096}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Ae({columns:[n.tenant_id,n.id],name:"roles_pk"})]),Re=j("role_permissions",{tenant_id:r("tenant_id",{length:191}).notNull(),role_id:r("role_id",{length:21}).notNull(),resource_server_identifier:r("resource_server_identifier",{length:191}).notNull(),permission_name:r("permission_name",{length:191}).notNull(),created_at:r("created_at",{length:35}).notNull()},n=>[Ae({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)]),qe=j("user_permissions",{tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),resource_server_identifier:r("resource_server_identifier",{length:191}).notNull(),permission_name:r("permission_name",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull().default(""),created_at:r("created_at",{length:35}).notNull()},n=>[Ae({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)]),Be=j("user_roles",{tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),role_id:r("role_id",{length:21}).notNull(),organization_id:r("organization_id",{length:191}).notNull().default(""),created_at:r("created_at",{length:35}).notNull()},n=>[Ae({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)]),te=j("resource_servers",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull(),identifier:r("identifier",{length:191}).notNull(),name:r("name",{length:255}).notNull(),scopes:r("scopes",{length:4096}),signing_alg:r("signing_alg",{length:64}),signing_secret:r("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:r("verification_key",{length:4096}),options:r("options",{length:4096}),is_system:w("is_system").notNull().default(0),metadata:r("metadata",{length:4096}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Ae({columns:[n.tenant_id,n.id],name:"resource_servers_pk"})]),Rt=j("branding",{tenant_id:r("tenant_id",{length:191}).primaryKey().references(()=>B.id,{onDelete:"cascade"}),logo_url:r("logo_url",{length:512}),favicon_url:r("favicon_url",{length:512}),font_url:r("font_url",{length:512}),colors_primary:r("colors_primary",{length:8}),colors_page_background_type:r("colors_page_background_type",{length:32}),colors_page_background_start:r("colors_page_background_start",{length:8}),colors_page_background_end:r("colors_page_background_end",{length:8}),colors_page_background_angle_dev:w("colors_page_background_angle_dev"),dark_mode:r("dark_mode",{length:8})}),lt=j("universal_login_templates",{tenant_id:r("tenant_id",{length:191}).primaryKey().references(()=>B.id,{onDelete:"cascade"}),body:r("body").notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()}),He=j("themes",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),themeId:r("themeId",{length:255}).notNull(),displayName:r("displayName",{length:255}).notNull(),colors_primary_button_label:r("colors_primary_button_label",{length:24}).notNull(),colors_primary_button:r("colors_primary_button",{length:24}).notNull(),colors_secondary_button_border:r("colors_secondary_button_border",{length:24}).notNull(),colors_secondary_button_label:r("colors_secondary_button_label",{length:24}).notNull(),colors_base_focus_color:r("colors_base_focus_color",{length:24}).notNull(),colors_base_hover_color:r("colors_base_hover_color",{length:24}).notNull(),colors_body_text:r("colors_body_text",{length:24}).notNull(),colors_captcha_widget_theme:r("colors_captcha_widget_theme",{length:24}).notNull(),colors_error:r("colors_error",{length:24}).notNull(),colors_header:r("colors_header",{length:24}).notNull(),colors_icons:r("colors_icons",{length:24}).notNull(),colors_input_background:r("colors_input_background",{length:24}).notNull(),colors_input_border:r("colors_input_border",{length:24}).notNull(),colors_input_filled_text:r("colors_input_filled_text",{length:24}).notNull(),colors_input_labels_placeholders:r("colors_input_labels_placeholders",{length:24}).notNull(),colors_links_focused_components:r("colors_links_focused_components",{length:24}).notNull(),colors_success:r("colors_success",{length:24}).notNull(),colors_widget_background:r("colors_widget_background",{length:24}).notNull(),colors_widget_border:r("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:r("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:r("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:r("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:r("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:r("page_background_background_color",{length:24}).notNull(),page_background_background_image_url:r("page_background_background_image_url",{length:255}).notNull(),page_background_page_layout:r("page_background_page_layout",{length:24}).notNull(),widget_header_text_alignment:r("widget_header_text_alignment",{length:24}).notNull(),widget_logo_height:w("widget_logo_height").notNull(),widget_logo_position:r("widget_logo_position",{length:24}).notNull(),widget_logo_url:r("widget_logo_url",{length:255}).notNull(),widget_social_buttons_layout:r("widget_social_buttons_layout",{length:24}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Ae({columns:[n.tenant_id,n.themeId],name:"themes_pkey"}),D("themes_tenant_id_idx").on(n.tenant_id)]),ke=j("forms",{id:r("id",{length:255}).primaryKey(),name:r("name",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),messages:r("messages",{length:255}),languages:r("languages",{length:255}),translations:r("translations",{length:4096}),nodes:r("nodes",{length:4096}),start:r("start",{length:255}),ending:r("ending",{length:255}),style:r("style",{length:1042}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("forms_tenant_id_idx").on(n.tenant_id)]),Oe=j("flows",{id:r("id",{length:24}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:150}).notNull(),actions:r("actions"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("flows_tenant_id_idx").on(n.tenant_id)]),Ut=j("prompt_settings",{tenant_id:r("tenant_id",{length:191}).primaryKey(),universal_login_experience:r("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)}),dt=j("email_providers",{tenant_id:r("tenant_id",{length:191}).primaryKey(),name:r("name",{length:255}).notNull(),enabled:w("enabled",{mode:"boolean"}).notNull(),default_from_address:r("default_from_address",{length:255}),credentials:r("credentials",{length:2048}).notNull().default("{}"),settings:r("settings",{length:2048}).notNull().default("{}"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()}),Ue=j("email_templates",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),template:r("template",{length:64}).notNull(),body:r("body").notNull(),from:r("from",{length:255}).notNull(),subject:r("subject",{length:255}).notNull(),syntax:r("syntax",{length:16}).notNull().default("liquid"),result_url:r("result_url",{length:2048}),url_lifetime_in_seconds:w("url_lifetime_in_seconds"),include_email_in_redirect:w("include_email_in_redirect",{mode:"boolean"}).notNull().default(!1),enabled:w("enabled",{mode:"boolean"}).notNull().default(!0),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Ae({columns:[n.tenant_id,n.template]})]),me=j("hooks",{hook_id:r("hook_id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),url:r("url",{length:512}),trigger_id:r("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:r("form_id",{length:128}),template_id:r("template_id",{length:64}),code_id:r("code_id",{length:21}),metadata:r("metadata")},n=>[D("hooks_tenant_id_idx").on(n.tenant_id)]),Ke=j("hook_code",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),code:r("code").notNull(),secrets:r("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)]),Je=j("keys",{kid:r("kid",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).references(()=>B.id,{onDelete:"cascade"}),created_at:r("created_at",{length:35}).notNull(),revoked_at:r("revoked_at",{length:35}),cert:r("cert",{length:4096}),pkcs7:r("pkcs7",{length:4096}),fingerprint:r("fingerprint",{length:256}),thumbprint:r("thumbprint",{length:256}),current_since:r("current_since",{length:35}),current_until:r("current_until",{length:35}),type:r("type",{length:50}).notNull().default("jwt_signing"),connection:r("connection",{length:255}).references(()=>pe.id,{onDelete:"cascade"})}),Ne=j("custom_text",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),prompt:r("prompt",{length:64}).notNull(),language:r("language",{length:16}).notNull(),custom_text:r("custom_text").notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()},n=>[Ae({columns:[n.tenant_id,n.prompt,n.language]})]),ue=j("authentication_methods",{id:r("id",{length:26}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}).notNull(),type:r("type",{length:32}).notNull(),phone_number:r("phone_number",{length:32}),totp_secret:r("totp_secret",{length:255}),credential_id:r("credential_id",{length:512}),public_key:r("public_key"),sign_count:w("sign_count"),credential_backed_up:w("credential_backed_up"),transports:r("transports",{length:512}),friendly_name:r("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)]),z=j("logs",{log_id:r("log_id",{length:21}).primaryKey(),category:r("category",{length:255}),tenant_id:r("tenant_id",{length:64}),user_id:r("user_id",{length:64}),ip:r("ip",{length:255}),type:r("type",{length:8}).notNull(),date:r("date",{length:35}).notNull(),client_id:r("client_id",{length:255}),client_name:r("client_name",{length:255}),user_agent:r("user_agent",{length:255}),description:r("description",{length:255}),details:r("details",{length:2048}),isMobile:w("isMobile"),user_name:r("user_name",{length:255}),connection:r("connection",{length:255}),connection_id:r("connection_id",{length:255}),audience:r("audience",{length:255}),scope:r("scope",{length:255}),strategy:r("strategy",{length:255}),strategy_type:r("strategy_type",{length:255}),hostname:r("hostname",{length:255}),auth0_client:r("auth0_client",{length:8192}),session_connection:r("session_connection",{length:255}),country_code:r("country_code",{length:2}),city_name:r("city_name",{length:255}),latitude:r("latitude",{length:255}),longitude:r("longitude",{length:255}),time_zone:r("time_zone",{length:255}),continent_code:r("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)]),M=j("outbox_events",{id:r("id",{length:26}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),event_type:r("event_type",{length:64}).notNull(),log_type:r("log_type",{length:64}).notNull(),aggregate_type:r("aggregate_type",{length:64}).notNull(),aggregate_id:r("aggregate_id",{length:255}).notNull(),payload:r("payload").notNull(),created_at:r("created_at",{length:35}).notNull(),processed_at:r("processed_at",{length:35}),retry_count:w("retry_count").notNull().default(0),next_retry_at:r("next_retry_at",{length:35}),error:r("error"),claimed_by:r("claimed_by",{length:255}),claim_expires_at:r("claim_expires_at",{length:35}),dead_lettered_at:r("dead_lettered_at",{length:35}),final_error:r("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)]),fr=Object.freeze(Object.defineProperty({__proto__:null,authenticationCodes:cr,authenticationMethods:ue,branding:Rt,clientGrants:ye,clientRegistrationTokens:X,clients:H,codes:re,connections:pe,customDomains:Ie,customText:Ne,domains:pr,emailProviders:dt,emailTemplates:Ue,flows:Oe,forms:ke,hookCode:Ke,hooks:me,invites:xe,keys:Je,loginSessions:Y,logs:z,organizations:ee,otps:_r,outboxEvents:M,passwords:oe,promptSettings:Ut,refreshTokens:J,resourceServers:te,rolePermissions:Re,roles:_e,sessions:ae,tenants:B,themes:He,tickets:ur,universalLoginTemplates:lt,userOrganizations:le,userPermissions:qe,userRoles:Be,users:Z},Symbol.toStringTag,{value:"Module"}));function Q(n){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(t=>t!==null&&typeof t=="object"?Q(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(o=>o!==null&&typeof o=="object"?Q(o):o):e[t]=Q(i))}return e}function hr(n,e,t={...n}){for(const i of e)n[i]!==void 0&&(t[i]=JSON.stringify(n[i]));return t}function gr(n,e,t=n){for(const i of e)n[i]!==void 0&&(t[i]=n[i]?1:0)}function cs(n){const e={};for(const t in n)n[t]!==void 0&&n[t]!==null&&(e[t]=n[t]);return e}function F(n,e){if(n==null)return e;if(typeof n=="string")try{return JSON.parse(n)}catch{return e}return n}function Yn(n,e="",t={}){for(const i in n)if(Object.prototype.hasOwnProperty.call(n,i)){const o=e?`${e}_${i}`:i,s=n[i];typeof s=="object"&&s!==null&&!Array.isArray(s)?Yn(s,o,t):typeof s=="boolean"?t[o]=s?1:0:t[o]=s}return t}function _s(n,e){const t={};for(const[i,o]of Object.entries(n)){const s=e.find(l=>i.startsWith(`${l}_`));if(!s)t[i]=o;else{const l=i.slice(s.length+1);t[s]={...t[s],[l]:o}}}return t}function mr(n){return typeof n=="string"?parseInt(n,10):typeof n=="bigint"?Number(n):n}function yr(n){return n==="dark"||n==="light"||n==="auto"}function vr(n){return{async get(e){const t=await n.select().from(Rt).where(c(Rt.tenant_id,e)).get();if(!t)return null;const{tenant_id:i,colors_primary:o,colors_page_background_type:s,colors_page_background_start:l,colors_page_background_end:d,colors_page_background_angle_dev:u,font_url:f,dark_mode:p,...m}=t;return Q({...m,colors:{primary:o,page_background:{type:s,start:l,end:d,angle_deg:u}},font:f?{url:f}:void 0,dark_mode:yr(p)?p:void 0})},async set(e,t){const{colors:i,font:o,dark_mode:s,...l}=t,d=i==null?void 0:i.page_background,u=d&&typeof d=="object"?d:void 0,f={...l,colors_primary:i==null?void 0:i.primary,colors_page_background_type:u==null?void 0:u.type,colors_page_background_start:u==null?void 0:u.start,colors_page_background_end:u==null?void 0:u.end,colors_page_background_angle_dev:u==null?void 0:u.angle_deg,font_url:o==null?void 0:o.url,dark_mode:s};await n.insert(Rt).values({tenant_id:e,...f}).onConflictDoUpdate({target:Rt.tenant_id,set:f})}}}var _t=class extends Error{constructor(e=500,t){super(t==null?void 0:t.message,{cause:t==null?void 0:t.cause});v(this,"res");v(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 We(n,e,t){const i=e.split(/ OR /i);if(i.length>1){const f=i.map(p=>{const m=p.trim().match(/^([^:]+):(.+)$/);if(m){const[,y,E]=m;if(!y||!E)return null;const T=E.replace(/^"(.*)"$/,"$1"),G=n[y.trim()];return G?c(G,T.trim()):null}return null}).filter(Boolean);return f.length===0?void 0:$e(...f)}const o=[];let s="",l=!1;for(let f=0;f<e.length;f++){const p=e[f];p==='"'?(l=!l,s+=p):p===" "&&!l?s.trim()&&(o.push(s.trim()),s=""):s+=p}s.trim()&&o.push(s.trim());const d=o.filter(f=>f!=="AND").map(f=>f.replace(/^([^:]+)=/g,"$1:")).map(f=>{let p=f.startsWith("-"),m=null,y="",E=!1,T;if(f.startsWith("-_exists_:"))m=f.substring(10),E=!0,p=!0;else if(f.startsWith("_exists_:"))m=f.substring(9),E=!0,p=!1;else if(f.includes(":")){const G=p?f.substring(1):f,W=G.indexOf(":");m=G.substring(0,W),y=G.substring(W+1),E=!1,y.startsWith(">=")?(T=">=",y=y.substring(2)):y.startsWith(">")?(T=">",y=y.substring(1)):y.startsWith("<=")?(T="<=",y=y.substring(2)):y.startsWith("<")?(T="<",y=y.substring(1)):T="=",y.startsWith('"')&&y.endsWith('"')&&y.length>1&&(y=y.slice(1,-1))}else m=null,y=f,E=!1;return{key:m,value:y,isNegation:p,isExistsQuery:E,operator:T}}),u=[];for(const{key:f,value:p,isNegation:m,isExistsQuery:y,operator:E}of d)if(f){const T=n[f];if(!T){y?u.push(m?O`${O.identifier(f)} IS NULL`:O`${O.identifier(f)} IS NOT NULL`):u.push(O`${O.identifier(f)} ${O.raw(m?"!=":E??"=")} ${p}`);continue}if(y)u.push(m?Ce(T):cn(T));else if(m)switch(E){case">":u.push(yt(T,p));break;case">=":u.push(Qe(T,p));break;case"<":u.push(Tt(T,p));break;case"<=":u.push(pn(T,p));break;default:u.push(Ys(T,p))}else switch(E){case">":u.push(pn(T,p));break;case">=":u.push(Tt(T,p));break;case"<":u.push(Qe(T,p));break;case"<=":u.push(yt(T,p));break;default:u.push(c(T,p))}}else if(p){const G=(p.includes("|")?[...t,"user_id"]:t).map(W=>{const ie=n[W];return ie?W==="user_id"?c(ie,p):xt(ie,`%${p}%`):null}).filter(Boolean);G.length>0&&u.push($e(...G))}if(u.length!==0)return u.length===1?u[0]:g(...u)}const yi=["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","hide_sign_up_disabled_error"],vi=["callbacks","allowed_origins","web_origins","client_aliases","allowed_clients","allowed_logout_urls","grant_types","signing_keys"],wi=["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 on(n){const{tenant_id:e,connections:t,...i}=n,o={...i};for(const s of yi)o[s]=!!i[s];for(const s of vi)o[s]=F(i[s],[]);for(const s of wi)o[s]=F(i[s],{});return o.connections=F(t,[]),Q(o)}function Ti(n){const e={...n};gr(n,yi,e);for(const t of vi)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]||[]));for(const t of wi)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]||{}));return n.connections!==void 0&&(e.connections=JSON.stringify(n.connections||[])),cs(e)}function wr(n){return{async create(e,t){var l,d;const i=new Date().toISOString(),o={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 yi)o[u]=t[u]??!1;o.oidc_conformant=t.oidc_conformant??!0,o.auth0_conformant=t.auth0_conformant??!0,o.sso_disabled=t.sso_disabled??!1;for(const u of vi)o[u]=t[u]||[];for(const u of wi)o[u]=t[u]||{};o.connections=t.connections||[];const s=Ti(o);try{await n.insert(H).values({...s,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 _t(409,{message:"Client already exists"}):u}return on({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(H).where(g(c(H.tenant_id,e),c(H.client_id,t))).get();return i?on(i):null},async getByClientId(e){const t=await n.select().from(H).where(c(H.client_id,e)).get();return t?{...on(t),tenant_id:t.tenant_id}:null},async update(e,t,i){const o=Ti({...i,updated_at:new Date().toISOString()});return delete o.client_id,delete o.tenant_id,await n.update(H).set(o).where(g(c(H.tenant_id,e),c(H.client_id,t))),!0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(H).where(c(H.tenant_id,e)).$dynamic();if(d){const y=We(H,d,["name","client_id"]);y&&(u=u.where(g(c(H.tenant_id,e),y)))}if(l!=null&&l.sort_by){const y=H[l.sort_by];y&&(u=u.orderBy(l.sort_order==="desc"?se(y):he(y)))}const p=(await u.offset(i*o).limit(o)).map(on);if(!s)return{clients:p};const[m]=await n.select({count:ge()}).from(H).where(c(H.tenant_id,e));return{clients:p,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async remove(e,t){return(await n.delete(H).where(g(c(H.tenant_id,e),c(H.client_id,t))).returning()).length>0}}}function Sr(n){const{tenant_id:e,is_system:t,options:i,metadata:o,...s}=n;return Q({...s,options:F(i,{}),metadata:F(o),is_system:t?!0:void 0})}function Nr(n){return{async listByClient(e,t){const i=await n.select({connections:H.connections}).from(H).where(g(c(H.tenant_id,e),c(H.client_id,t))).get();if(!i)return[];const o=F(i.connections,[])||[];if(o.length===0)return[];const l=(await n.select().from(pe).where(g(c(pe.tenant_id,e),De(pe.id,o))).all()).map(Sr);return o.map(d=>l.find(u=>u.id===d)).filter(Boolean)},async updateByClient(e,t,i){return(await n.update(H).set({connections:JSON.stringify([...new Set(i)])}).where(g(c(H.tenant_id,e),c(H.client_id,t))).returning()).length>0},async listByConnection(e,t){return(await n.select({client_id:H.client_id,connections:H.connections}).from(H).where(c(H.tenant_id,e)).all()).filter(o=>(F(o.connections,[])||[]).includes(t)).map(o=>o.client_id)},async addClientToConnection(e,t,i){var d;if(!await n.select({client_id:H.client_id}).from(H).where(g(c(H.tenant_id,e),c(H.client_id,i))).get())return!1;const s=await n.run(O`UPDATE clients SET connections = CASE
1
+ "use strict";var Zs=Object.defineProperty;var Ks=(n,e,t)=>e in n?Zs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var v=(n,e,t)=>Ks(n,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const L=Symbol.for("drizzle:entityKind");function ve(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 $i;$i=L;class en{constructor(e,t){v(this,"name");v(this,"keyAsName");v(this,"primary");v(this,"notNull");v(this,"default");v(this,"defaultFn");v(this,"onUpdateFn");v(this,"hasDefault");v(this,"isUnique");v(this,"uniqueName");v(this,"uniqueType");v(this,"dataType");v(this,"columnType");v(this,"enumValues");v(this,"generated");v(this,"generatedIdentity");v(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"}}v(en,$i,"Column");var ji;ji=L;class Aa{constructor(e,t,i){v(this,"config");v(this,"$default",this.$defaultFn);v(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)}}v(Aa,ji,"ColumnBuilder");const Ot=Symbol.for("drizzle:Name"),Ei=Symbol.for("drizzle:isPgEnum");function Ws(n){return!!n&&typeof n=="function"&&Ei in n&&n[Ei]===!0}var Vi;Vi=L;class hi{constructor(e,t,i,o=!1,s=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:i,isWith:o,usedTables:s}}}v(hi,Vi,"Subquery");const Gs={startActiveSpan(n,e){return e()}},Ft=Symbol.for("drizzle:ViewBaseConfig"),In=Symbol.for("drizzle:Schema"),xi=Symbol.for("drizzle:Columns"),ki=Symbol.for("drizzle:ExtraConfigColumns"),Cn=Symbol.for("drizzle:OriginalName"),Dn=Symbol.for("drizzle:BaseName"),_n=Symbol.for("drizzle:IsAlias"),Oi=Symbol.for("drizzle:ExtraConfigBuilder"),Js=Symbol.for("drizzle:IsDrizzleTable");var Hi,Zi,Ki,Wi,Gi,Ji,Qi,Xi,Yi,eo;eo=L,Yi=Ot,Xi=Cn,Qi=In,Ji=xi,Gi=ki,Wi=Dn,Ki=_n,Zi=Js,Hi=Oi;class fe{constructor(e,t,i){v(this,Yi);v(this,Xi);v(this,Qi);v(this,Ji);v(this,Gi);v(this,Wi);v(this,Ki,!1);v(this,Zi,!0);v(this,Hi);this[Ot]=this[Cn]=e,this[In]=t,this[Dn]=i}}v(fe,eo,"Table"),v(fe,"Symbol",{Name:Ot,Schema:In,OriginalName:Cn,Columns:xi,ExtraConfigColumns:ki,BaseName:Dn,IsAlias:_n,ExtraConfigBuilder:Oi});function Ta(n){return n!=null&&typeof n.getSQL=="function"}function Qs(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 to;to=L;class we{constructor(e){v(this,"value");this.value=Array.isArray(e)?e:[e]}getSQL(){return new ce([this])}}v(we,to,"StringChunk");var no;no=L;const mt=class mt{constructor(e){v(this,"decoder",Ia);v(this,"shouldInlineParams",!1);v(this,"usedTables",[]);this.queryChunks=e;for(const t of e)if(ve(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 Gs.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:o,escapeName:s,escapeParam:l,prepareTyping:d,inlineParams:u,paramStartIndex:f}=i;return Qs(e.map(p=>{var m;if(ve(p,we))return{sql:p.value.join(""),params:[]};if(ve(p,un))return{sql:s(p.value),params:[]};if(p===void 0)return{sql:"",params:[]};if(Array.isArray(p)){const y=[new we("(")];for(const[E,A]of p.entries())y.push(A),E<p.length-1&&y.push(new we(", "));return y.push(new we(")")),this.buildQueryFromSourceParams(y,i)}if(ve(p,mt))return this.buildQueryFromSourceParams(p.queryChunks,{...i,inlineParams:u||p.shouldInlineParams});if(ve(p,fe)){const y=p[fe.Symbol.Schema],E=p[fe.Symbol.Name];return{sql:y===void 0||p[_n]?s(E):s(y)+"."+s(E),params:[]}}if(ve(p,en)){const y=o.getColumnCasing(p);if(t.invokeSource==="indexes")return{sql:s(y),params:[]};const E=p.table[fe.Symbol.Schema];return{sql:p.table[_n]||E===void 0?s(p.table[fe.Symbol.Name])+"."+s(y):s(E)+"."+s(p.table[fe.Symbol.Name])+"."+s(y),params:[]}}if(ve(p,gi)){const y=p[Ft].schema,E=p[Ft].name;return{sql:y===void 0||p[Ft].isAlias?s(E):s(y)+"."+s(E),params:[]}}if(ve(p,zt)){if(ve(p.value,Mt))return{sql:l(f.value++,p),params:[p],typings:["none"]};const y=p.value===null?null:p.encoder.mapToDriverValue(p.value);if(ve(y,mt))return this.buildQueryFromSourceParams([y],i);if(u)return{sql:this.mapInlineParam(y,i),params:[]};let E=["none"];return d&&(E=[d(p.encoder)]),{sql:l(f.value++,y),params:[y],typings:E}}return ve(p,Mt)?{sql:l(f.value++,p),params:[p],typings:["none"]}:ve(p,mt.Aliased)&&p.fieldAlias!==void 0?{sql:s(p.fieldAlias),params:[]}:ve(p,hi)?p._.isWith?{sql:s(p._.alias),params:[]}:this.buildQueryFromSourceParams([new we("("),p._.sql,new we(") "),new un(p._.alias)],i):Ws(p)?p.schema?{sql:s(p.schema)+"."+s(p.enumName),params:[]}:{sql:s(p.enumName),params:[]}:Ta(p)?(m=p.shouldOmitSQLParens)!=null&&m.call(p)?this.buildQueryFromSourceParams([p.getSQL()],i):this.buildQueryFromSourceParams([new we("("),p.getSQL(),new we(")")],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 mt.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}};v(mt,no,"SQL");let ce=mt;var io;io=L;class un{constructor(e){v(this,"brand");this.value=e}getSQL(){return new ce([this])}}v(un,io,"Name");function Xs(n){return typeof n=="object"&&n!==null&&"mapToDriverValue"in n&&typeof n.mapToDriverValue=="function"}const Ia={mapFromDriverValue:n=>n},Ca={mapToDriverValue:n=>n};({...Ia,...Ca});var oo;oo=L;class zt{constructor(e,t=Ca){v(this,"brand");this.value=e,this.encoder=t}getSQL(){return new ce([this])}}v(zt,oo,"Param");function O(n,...e){const t=[];(e.length>0||n.length>0&&n[0]!=="")&&t.push(new we(n[0]));for(const[i,o]of e.entries())t.push(o,new we(n[i+1]));return new ce(t)}(n=>{function e(){return new ce([])}n.empty=e;function t(u){return new ce(u)}n.fromList=t;function i(u){return new ce([new we(u)])}n.raw=i;function o(u,f){const p=[];for(const[m,y]of u.entries())m>0&&f!==void 0&&p.push(f),p.push(y);return new ce(p)}n.join=o;function s(u){return new un(u)}n.identifier=s;function l(u){return new Mt(u)}n.placeholder=l;function d(u,f){return new zt(u,f)}n.param=d})(O||(O={}));(n=>{var t;t=L;const i=class i{constructor(s,l){v(this,"isSelectionField",!1);this.sql=s,this.fieldAlias=l}getSQL(){return this.sql}clone(){return new i(this.sql,this.fieldAlias)}};v(i,t,"SQL.Aliased");let e=i;n.Aliased=e})(ce||(ce={}));var ao;ao=L;class Mt{constructor(e){this.name=e}getSQL(){return new ce([this])}}v(Mt,ao,"Placeholder");const Ys=Symbol.for("drizzle:IsDrizzleView");var so,ro,lo;lo=L,ro=Ft,so=Ys;class gi{constructor({name:e,schema:t,selectedFields:i,query:o}){v(this,ro);v(this,so,!0);this[Ft]={name:e,originalName:e,schema:t,selectedFields:i,query:o,isExisting:!o,isAlias:!1}}getSQL(){return new ce([this])}}v(gi,lo,"View");en.prototype.getSQL=function(){return new ce([this])};fe.prototype.getSQL=function(){return new ce([this])};hi.prototype.getSQL=function(){return new ce([this])};function tn(n,e){return{name:typeof n=="string"&&n.length>0?n:"",config:typeof n=="object"?n:e}}const Da=typeof TextDecoder>"u"?null:new TextDecoder;function ct(n,e){return Xs(e)&&!Ta(n)&&!ve(n,zt)&&!ve(n,Mt)&&!ve(n,en)&&!ve(n,fe)&&!ve(n,gi)?new zt(n,e):n}const c=(n,e)=>O`${n} = ${ct(e,n)}`,er=(n,e)=>O`${n} <> ${ct(e,n)}`;function g(...n){const e=n.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new ce(e):new ce([new we("("),O.join(e,new we(" and ")),new we(")")])}function $e(...n){const e=n.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new ce(e):new ce([new we("("),O.join(e,new we(" or ")),new we(")")])}const pn=(n,e)=>O`${n} > ${ct(e,n)}`,At=(n,e)=>O`${n} >= ${ct(e,n)}`,Ge=(n,e)=>O`${n} < ${ct(e,n)}`,yt=(n,e)=>O`${n} <= ${ct(e,n)}`;function De(n,e){return Array.isArray(e)?e.length===0?O`false`:O`${n} in ${e.map(t=>ct(t,n))}`:O`${n} in ${ct(e,n)}`}function Ce(n){return O`${n} is null`}function cn(n){return O`${n} is not null`}function xt(n,e){return O`${n} like ${e}`}function he(n){return O`${n} asc`}function se(n){return O`${n} desc`}function ge(n){return O`count(${O.raw("*")})`.mapWith(Number)}function tr(){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")}}function nr(){const n=e=>{throw new Error(`Action executions 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")}}function ir(){const n=e=>{throw new Error(`Action versions 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"),removeForAction:()=>n("removeForAction")}}var co;co=L;class La{constructor(e,t){v(this,"reference");v(this,"_onUpdate");v(this,"_onDelete");this.reference=()=>{const{name:i,columns:o,foreignColumns:s}=e();return{name:i,columns:o,foreignTable:s[0].table,foreignColumns:s}},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 Ra(e,this)}}v(La,co,"SQLiteForeignKeyBuilder");var _o;_o=L;class Ra{constructor(e,t){v(this,"reference");v(this,"onUpdate");v(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(),o=t.map(d=>d.name),s=i.map(d=>d.name),l=[this.table[Ot],...o,i[0].table[Ot],...s];return e??`${l.join("_")}_fk`}}v(Ra,_o,"SQLiteForeignKey");function or(n,e){return`${n[Ot]}_${e.join("_")}_unique`}var uo,po;class je extends(po=Aa,uo=L,po){constructor(){super(...arguments);v(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:o,actions:s})=>((l,d)=>{const u=new La(()=>{const f=l();return{columns:[t],foreignColumns:[f]}});return d.onUpdate&&u.onUpdate(d.onUpdate),d.onDelete&&u.onDelete(d.onDelete),u.build(i)})(o,s))}}v(je,uo,"SQLiteColumnBuilder");var fo,ho;class Ve extends(ho=en,fo=L,ho){constructor(e,t){t.uniqueName||(t.uniqueName=or(e,[t.name])),super(e,t),this.table=e}}v(Ve,fo,"SQLiteColumn");var go,mo;class Ua extends(mo=je,go=L,mo){constructor(e){super(e,"bigint","SQLiteBigInt")}build(e){return new Fa(e,this.config)}}v(Ua,go,"SQLiteBigIntBuilder");var yo,vo;class Fa extends(vo=Ve,yo=L,vo){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(Da.decode(e))}mapToDriverValue(e){return Buffer.from(e.toString())}}v(Fa,yo,"SQLiteBigInt");var wo,No;class za extends(No=je,wo=L,No){constructor(e){super(e,"json","SQLiteBlobJson")}build(e){return new Ma(e,this.config)}}v(za,wo,"SQLiteBlobJsonBuilder");var So,bo;class Ma extends(bo=Ve,So=L,bo){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(Da.decode(e))}mapToDriverValue(e){return Buffer.from(JSON.stringify(e))}}v(Ma,So,"SQLiteBlobJson");var Eo,xo;class Pa extends(xo=je,Eo=L,xo){constructor(e){super(e,"buffer","SQLiteBlobBuffer")}build(e){return new qa(e,this.config)}}v(Pa,Eo,"SQLiteBlobBufferBuilder");var ko,Oo;class qa extends(Oo=Ve,ko=L,Oo){mapFromDriverValue(e){return Buffer.isBuffer(e)?e:Buffer.from(e)}getSQLType(){return"blob"}}v(qa,ko,"SQLiteBlobBuffer");function ar(n,e){const{name:t,config:i}=tn(n,e);return(i==null?void 0:i.mode)==="json"?new za(t):(i==null?void 0:i.mode)==="bigint"?new Ua(t):new Pa(t)}var Ao,To;class Ba extends(To=je,Ao=L,To){constructor(e,t,i){super(e,"custom","SQLiteCustomColumn"),this.config.fieldConfig=t,this.config.customTypeParams=i}build(e){return new $a(e,this.config)}}v(Ba,Ao,"SQLiteCustomColumnBuilder");var Io,Co;class $a extends(Co=Ve,Io=L,Co){constructor(t,i){super(t,i);v(this,"sqlName");v(this,"mapTo");v(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}}v($a,Io,"SQLiteCustomColumn");function sr(n){return(e,t)=>{const{name:i,config:o}=tn(e,t);return new Ba(i,o,n)}}var Do,Lo;class vn extends(Lo=je,Do=L,Lo){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()}}v(vn,Do,"SQLiteBaseIntegerBuilder");var Ro,Uo;class wn extends(Uo=Ve,Ro=L,Uo){constructor(){super(...arguments);v(this,"autoIncrement",this.config.autoIncrement)}getSQLType(){return"integer"}}v(wn,Ro,"SQLiteBaseInteger");var Fo,zo;class ja extends(zo=vn,Fo=L,zo){constructor(e){super(e,"number","SQLiteInteger")}build(e){return new Va(e,this.config)}}v(ja,Fo,"SQLiteIntegerBuilder");var Mo,Po;class Va extends(Po=wn,Mo=L,Po){}v(Va,Mo,"SQLiteInteger");var qo,Bo;class Ha extends(Bo=vn,qo=L,Bo){constructor(e,t){super(e,"date","SQLiteTimestamp"),this.config.mode=t}defaultNow(){return this.default(O`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build(e){return new Za(e,this.config)}}v(Ha,qo,"SQLiteTimestampBuilder");var $o,jo;class Za extends(jo=wn,$o=L,jo){constructor(){super(...arguments);v(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}}v(Za,$o,"SQLiteTimestamp");var Vo,Ho;class Ka extends(Ho=vn,Vo=L,Ho){constructor(e,t){super(e,"boolean","SQLiteBoolean"),this.config.mode=t}build(e){return new Wa(e,this.config)}}v(Ka,Vo,"SQLiteBooleanBuilder");var Zo,Ko;class Wa extends(Ko=wn,Zo=L,Ko){constructor(){super(...arguments);v(this,"mode",this.config.mode)}mapFromDriverValue(t){return Number(t)===1}mapToDriverValue(t){return t?1:0}}v(Wa,Zo,"SQLiteBoolean");function w(n,e){const{name:t,config:i}=tn(n,e);return(i==null?void 0:i.mode)==="timestamp"||(i==null?void 0:i.mode)==="timestamp_ms"?new Ha(t,i.mode):(i==null?void 0:i.mode)==="boolean"?new Ka(t,i.mode):new ja(t)}var Wo,Go;class Ga extends(Go=je,Wo=L,Go){constructor(e){super(e,"string","SQLiteNumeric")}build(e){return new Ja(e,this.config)}}v(Ga,Wo,"SQLiteNumericBuilder");var Jo,Qo;class Ja extends(Qo=Ve,Jo=L,Qo){mapFromDriverValue(e){return typeof e=="string"?e:String(e)}getSQLType(){return"numeric"}}v(Ja,Jo,"SQLiteNumeric");var Xo,Yo;class Qa extends(Yo=je,Xo=L,Yo){constructor(e){super(e,"number","SQLiteNumericNumber")}build(e){return new Xa(e,this.config)}}v(Qa,Xo,"SQLiteNumericNumberBuilder");var ea,ta;class Xa extends(ta=Ve,ea=L,ta){constructor(){super(...arguments);v(this,"mapToDriverValue",String)}mapFromDriverValue(t){return typeof t=="number"?t:Number(t)}getSQLType(){return"numeric"}}v(Xa,ea,"SQLiteNumericNumber");var na,ia;class Ya extends(ia=je,na=L,ia){constructor(e){super(e,"bigint","SQLiteNumericBigInt")}build(e){return new es(e,this.config)}}v(Ya,na,"SQLiteNumericBigIntBuilder");var oa,aa;class es extends(aa=Ve,oa=L,aa){constructor(){super(...arguments);v(this,"mapFromDriverValue",BigInt);v(this,"mapToDriverValue",String)}getSQLType(){return"numeric"}}v(es,oa,"SQLiteNumericBigInt");function rr(n,e){const{name:t,config:i}=tn(n,e),o=i==null?void 0:i.mode;return o==="number"?new Qa(t):o==="bigint"?new Ya(t):new Ga(t)}var sa,ra;class ts extends(ra=je,sa=L,ra){constructor(e){super(e,"number","SQLiteReal")}build(e){return new ns(e,this.config)}}v(ts,sa,"SQLiteRealBuilder");var la,da;class ns extends(da=Ve,la=L,da){getSQLType(){return"real"}}v(ns,la,"SQLiteReal");function lr(n){return new ts(n??"")}var ca,_a;class is extends(_a=je,ca=L,_a){constructor(e,t){super(e,"string","SQLiteText"),this.config.enumValues=t.enum,this.config.length=t.length}build(e){return new os(e,this.config)}}v(is,ca,"SQLiteTextBuilder");var ua,pa;class os extends(pa=Ve,ua=L,pa){constructor(t,i){super(t,i);v(this,"enumValues",this.config.enumValues);v(this,"length",this.config.length)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}v(os,ua,"SQLiteText");var fa,ha;class as extends(ha=je,fa=L,ha){constructor(e){super(e,"json","SQLiteTextJson")}build(e){return new ss(e,this.config)}}v(as,fa,"SQLiteTextJsonBuilder");var ga,ma;class ss extends(ma=Ve,ga=L,ma){getSQLType(){return"text"}mapFromDriverValue(e){return JSON.parse(e)}mapToDriverValue(e){return JSON.stringify(e)}}v(ss,ga,"SQLiteTextJson");function r(n,e={}){const{name:t,config:i}=tn(n,e);return i.mode==="json"?new as(t):new is(t,i)}function dr(){return{blob:ar,customType:sr,integer:w,numeric:rr,real:lr,text:r}}const Qn=Symbol.for("drizzle:SQLiteInlineForeignKeys");var ya,va,wa,Na,Sa;class Pt extends(Sa=fe,Na=L,wa=fe.Symbol.Columns,va=Qn,ya=fe.Symbol.ExtraConfigBuilder,Sa){constructor(){super(...arguments);v(this,wa);v(this,va,[]);v(this,ya)}}v(Pt,Na,"SQLiteTable"),v(Pt,"Symbol",Object.assign({},fe.Symbol,{InlineForeignKeys:Qn}));function cr(n,e,t,i,o=n){const s=new Pt(n,i,o),l=typeof e=="function"?e(dr()):e,d=Object.fromEntries(Object.entries(l).map(([f,p])=>{const m=p;m.setName(f);const y=m.build(s);return s[Qn].push(...m.buildForeignKeys(y,s)),[f,y]})),u=Object.assign(s,d);return u[fe.Symbol.Columns]=d,u[fe.Symbol.ExtraConfigColumns]=d,t&&(u[Pt.Symbol.ExtraConfigBuilder]=t),u}const j=(n,e,t)=>cr(n,e,t);var ba;ba=L;class mi{constructor(e,t){this.name=e,this.unique=t}on(...e){return new rs(this.name,e,this.unique)}}v(mi,ba,"SQLiteIndexBuilderOn");var Ea;Ea=L;class rs{constructor(e,t,i){v(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 ls(this.config,e)}}v(rs,Ea,"SQLiteIndexBuilder");var xa;xa=L;class ls{constructor(e,t){v(this,"config");this.config={...e,table:t}}}v(ls,xa,"SQLiteIndex");function D(n){return new mi(n,!1)}function vt(n){return new mi(n,!0)}function Te(...n){return n[0].columns?new Xn(n[0].columns,n[0].name):new Xn(n)}var ka;ka=L;class Xn{constructor(e,t){v(this,"columns");v(this,"name");this.columns=e,this.name=t}build(e){return new ds(e,this.columns,this.name)}}v(Xn,ka,"SQLitePrimaryKeyBuilder");var Oa;Oa=L;class ds{constructor(e,t,i){v(this,"columns");v(this,"name");this.table=e,this.columns=t,this.name=i}getName(){return this.name??`${this.table[Pt.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}v(ds,Oa,"SQLitePrimaryKey");const B=j("tenants",{id:r("id",{length:191}).primaryKey(),name:r("name",{length:255}),audience:r("audience",{length:255}),sender_email:r("sender_email",{length:255}),sender_name:r("sender_name",{length:255}),language:r("language",{length:255}),logo:r("logo",{length:255}),primary_color:r("primary_color",{length:255}),secondary_color:r("secondary_color",{length:255}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),support_url:r("support_url",{length:255}),idle_session_lifetime:w("idle_session_lifetime"),session_lifetime:w("session_lifetime"),session_cookie:r("session_cookie"),allowed_logout_urls:r("allowed_logout_urls"),ephemeral_session_lifetime:w("ephemeral_session_lifetime"),idle_ephemeral_session_lifetime:w("idle_ephemeral_session_lifetime"),default_redirection_uri:r("default_redirection_uri"),default_client_id:r("default_client_id",{length:255}),enabled_locales:r("enabled_locales"),default_directory:r("default_directory",{length:255}),error_page:r("error_page"),flags:r("flags"),friendly_name:r("friendly_name",{length:255}),picture_url:r("picture_url"),support_email:r("support_email",{length:255}),sandbox_version:r("sandbox_version",{length:50}),sandbox_versions_available:r("sandbox_versions_available"),legacy_sandbox_version:r("legacy_sandbox_version",{length:50}),change_password:r("change_password"),guardian_mfa_page:r("guardian_mfa_page"),device_flow:r("device_flow"),default_token_quota:r("default_token_quota"),default_audience:r("default_audience",{length:255}),default_organization:r("default_organization",{length:255}),sessions:r("sessions"),oidc_logout:r("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:r("acr_values_supported"),mtls:r("mtls"),pushed_authorization_requests_supported:w("pushed_authorization_requests_supported"),authorization_response_iss_parameter_supported:w("authorization_response_iss_parameter_supported")}),H=j("users",{user_id:r("user_id",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),email:r("email",{length:255}),given_name:r("given_name",{length:255}),family_name:r("family_name",{length:255}),nickname:r("nickname",{length:255}),name:r("name",{length:255}),picture:r("picture",{length:2083}),tags:r("tags",{length:255}),phone_number:r("phone_number",{length:17}),phone_verified:w("phone_verified",{mode:"boolean"}),username:r("username",{length:128}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),linked_to:r("linked_to",{length:255}),last_ip:r("last_ip",{length:255}),login_count:w("login_count").notNull(),last_login:r("last_login",{length:255}),registration_completed_at:r("registration_completed_at",{length:35}),provider:r("provider",{length:255}).notNull(),connection:r("connection",{length:255}),email_verified:w("email_verified",{mode:"boolean"}).notNull(),is_social:w("is_social",{mode:"boolean"}).notNull(),app_metadata:r("app_metadata",{length:4096}).notNull().default("{}"),user_metadata:r("user_metadata").notNull().default("{}"),profileData:r("profileData",{length:2048}),locale:r("locale",{length:255}),middle_name:r("middle_name",{length:100}),preferred_username:r("preferred_username",{length:255}),profile:r("profile"),website:r("website"),gender:r("gender",{length:50}),birthdate:r("birthdate",{length:10}),zoneinfo:r("zoneinfo",{length:100}),address:r("address")},n=>[Te({columns:[n.user_id,n.tenant_id],name:"users_tenants"}),vt("unique_email_provider").on(n.email,n.provider,n.tenant_id),vt("unique_phone_provider").on(n.phone_number,n.provider,n.tenant_id),vt("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)]),oe=j("passwords",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),password:r("password",{length:255}).notNull(),algorithm:r("algorithm",{length:16}).notNull().default("bcrypt"),is_current:w("is_current").notNull().default(1)}),ae=j("sessions",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("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:r("device").notNull(),clients:r("clients").notNull(),login_session_id:r("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)]),W=j("refresh_tokens",{id:r("id",{length:26}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),client_id:r("client_id",{length:191}).notNull(),login_id:r("login_id",{length:26}).notNull(),user_id:r("user_id",{length:255}),resource_servers:r("resource_servers").notNull(),device:r("device").notNull(),rotating:w("rotating",{mode:"boolean"}).notNull(),token_lookup:r("token_lookup",{length:16}),token_hash:r("token_hash",{length:64}),family_id:r("family_id",{length:26}),rotated_to:r("rotated_to",{length:26}),rotated_at_ts:w("rotated_at_ts"),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),D("idx_refresh_tokens_token_lookup").on(n.tenant_id,n.token_lookup),D("idx_refresh_tokens_family_id").on(n.tenant_id,n.family_id)]),Y=j("login_sessions",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),session_id:r("session_id",{length:21}),csrf_token:r("csrf_token",{length:21}).notNull(),auth_params:r("auth_params"),authorization_url:r("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:r("ip",{length:39}),useragent:r("useragent"),auth0Client:r("auth0Client",{length:255}),state:r("state",{length:50}).notNull().default("pending"),state_data:r("state_data"),failure_reason:r("failure_reason"),user_id:r("user_id",{length:255}),auth_connection:r("auth_connection",{length:255}),auth_strategy_strategy:r("auth_strategy_strategy",{length:64}),auth_strategy_strategy_type:r("auth_strategy_strategy_type",{length:64}),authenticated_at:r("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=j("codes",{code_id:r("code_id",{length:191}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}),login_id:r("login_id",{length:255}),connection_id:r("connection_id",{length:255}),code_type:r("code_type",{length:255}).notNull(),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35}),code_verifier:r("code_verifier",{length:128}),code_challenge:r("code_challenge",{length:128}),code_challenge_method:r("code_challenge_method",{length:5}),redirect_uri:r("redirect_uri",{length:1024}),nonce:r("nonce",{length:1024}),state:r("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)]),_r=j("authentication_codes",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),code:r("code",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),user_id:r("user_id",{length:255}).notNull(),nonce:r("nonce",{length:255}),state:r("state",{length:8192}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35})}),ur=j("otps",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),id:r("id",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),code:r("code",{length:255}).notNull(),email:r("email",{length:255}).notNull(),user_id:r("user_id",{length:255}),send:r("send",{length:255}),nonce:r("nonce",{length:255}),state:r("state",{length:1024}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35}),audience:r("audience",{length:255}),ip:r("ip",{length:64})},n=>[D("otps_email_index").on(n.email),D("otps_expires_at_index").on(n.expires_at)]),pr=j("tickets",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),id:r("id",{length:255}).primaryKey(),client_id:r("client_id",{length:255}).notNull(),email:r("email",{length:255}).notNull(),nonce:r("nonce",{length:255}),state:r("state",{length:1024}),scope:r("scope",{length:1024}),response_type:r("response_type",{length:256}),response_mode:r("response_mode",{length:256}),redirect_uri:r("redirect_uri",{length:1024}),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),used_at:r("used_at",{length:35})}),Z=j("clients",{client_id:r("client_id",{length:191}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:255}).notNull(),description:r("description",{length:140}),global:w("global").notNull().default(0),client_secret:r("client_secret",{length:255}),app_type:r("app_type",{length:64}).default("regular_web"),logo_uri:r("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:r("callbacks").notNull(),allowed_origins:r("allowed_origins").notNull(),web_origins:r("web_origins").notNull(),client_aliases:r("client_aliases").notNull(),allowed_clients:r("allowed_clients").notNull(),allowed_logout_urls:r("allowed_logout_urls").notNull(),session_transfer:r("session_transfer").notNull(),oidc_logout:r("oidc_logout").notNull(),grant_types:r("grant_types").notNull(),jwt_configuration:r("jwt_configuration").notNull(),signing_keys:r("signing_keys").notNull(),encryption_key:r("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:r("cross_origin_loc",{length:2083}),custom_login_page_on:w("custom_login_page_on").notNull().default(0),custom_login_page:r("custom_login_page"),custom_login_page_preview:r("custom_login_page_preview"),form_template:r("form_template"),addons:r("addons").notNull(),token_endpoint_auth_method:r("token_endpoint_auth_method",{length:64}).default("client_secret_basic"),client_metadata:r("client_metadata").notNull(),mobile:r("mobile").notNull(),initiate_login_uri:r("initiate_login_uri",{length:2083}),native_social_login:r("native_social_login").notNull(),refresh_token:r("refresh_token").notNull(),default_organization:r("default_organization").notNull(),organization_usage:r("organization_usage",{length:32}).default("deny"),organization_require_behavior:r("organization_require_behavior",{length:32}).default("no_prompt"),client_authentication_methods:r("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),hide_sign_up_disabled_error:w("hide_sign_up_disabled_error").notNull().default(0),signed_request_object:r("signed_request_object").notNull(),compliance_level:r("compliance_level",{length:64}),par_request_expiry:w("par_request_expiry"),token_quota:r("token_quota").notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),connections:r("connections").notNull().default("[]"),owner_user_id:r("owner_user_id",{length:255}),registration_type:r("registration_type",{length:32}),registration_metadata:r("registration_metadata"),user_linking_mode:r("user_linking_mode",{length:16})},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)]),X=j("client_registration_tokens",{id:r("id",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),token_hash:r("token_hash",{length:64}).notNull(),type:r("type",{length:8}).notNull(),client_id:r("client_id",{length:191}),sub:r("sub",{length:255}),constraints:r("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=>[vt("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)]),ye=j("client_grants",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),client_id:r("client_id",{length:191}).notNull(),audience:r("audience",{length:191}).notNull(),scope:r("scope").default("[]"),organization_usage:r("organization_usage",{length:32}),allow_any_organization:w("allow_any_organization").default(0),is_system:w("is_system").default(0),subject_type:r("subject_type",{length:32}),authorization_details_types:r("authorization_details_types").default("[]"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("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=j("connections",{id:r("id",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:255}).notNull(),response_type:r("response_type",{length:255}),response_mode:r("response_mode",{length:255}),strategy:r("strategy",{length:64}),options:r("options",{length:8192}).notNull().default("{}"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull(),display_name:r("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:r("metadata",{length:4096})},n=>[Te({columns:[n.tenant_id,n.id]}),D("connections_tenant_id_index").on(n.tenant_id),vt("connections_id_unique").on(n.id)]),Ie=j("custom_domains",{custom_domain_id:r("custom_domain_id",{length:256}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),domain:r("domain",{length:255}).notNull(),primary:w("primary",{mode:"boolean"}).notNull(),status:r("status",{length:50}).notNull(),type:r("type",{length:50}).notNull(),origin_domain_name:r("origin_domain_name",{length:255}),verification:r("verification",{length:2048}),custom_client_ip_header:r("custom_client_ip_header",{length:50}),tls_policy:r("tls_policy",{length:50}),domain_metadata:r("domain_metadata",{length:2048}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[vt("custom_domains_domain_unique").on(n.domain)]),fr=j("domains",{id:r("id",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),domain:r("domain",{length:255}).notNull(),email_service:r("email_service",{length:255}),email_api_key:r("email_api_key",{length:255}),dkim_private_key:r("dkim_private_key",{length:2048}),dkim_public_key:r("dkim_public_key",{length:2048}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()}),ee=j("organizations",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),name:r("name",{length:256}).notNull(),display_name:r("display_name",{length:256}),branding:r("branding"),metadata:r("metadata"),enabled_connections:r("enabled_connections"),token_quota:r("token_quota"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("idx_organizations_tenant_id").on(n.tenant_id)]),le=j("user_organizations",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[vt("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)]),xe=j("invites",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull(),inviter:r("inviter").notNull(),invitee:r("invitee").notNull(),client_id:r("client_id",{length:191}).notNull(),connection_id:r("connection_id",{length:21}),invitation_url:r("invitation_url").notNull(),created_at:r("created_at",{length:35}).notNull(),expires_at:r("expires_at",{length:35}).notNull(),app_metadata:r("app_metadata"),user_metadata:r("user_metadata"),roles:r("roles"),ticket_id:r("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=j("roles",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull(),name:r("name",{length:50}).notNull(),description:r("description",{length:255}),is_system:w("is_system").notNull().default(0),metadata:r("metadata",{length:4096}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.id],name:"roles_pk"})]),Re=j("role_permissions",{tenant_id:r("tenant_id",{length:191}).notNull(),role_id:r("role_id",{length:21}).notNull(),resource_server_identifier:r("resource_server_identifier",{length:191}).notNull(),permission_name:r("permission_name",{length:191}).notNull(),created_at:r("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)]),qe=j("user_permissions",{tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),resource_server_identifier:r("resource_server_identifier",{length:191}).notNull(),permission_name:r("permission_name",{length:191}).notNull(),organization_id:r("organization_id",{length:21}).notNull().default(""),created_at:r("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)]),Be=j("user_roles",{tenant_id:r("tenant_id",{length:191}).notNull(),user_id:r("user_id",{length:191}).notNull(),role_id:r("role_id",{length:21}).notNull(),organization_id:r("organization_id",{length:191}).notNull().default(""),created_at:r("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)]),te=j("resource_servers",{id:r("id",{length:21}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull(),identifier:r("identifier",{length:191}).notNull(),name:r("name",{length:255}).notNull(),scopes:r("scopes",{length:4096}),signing_alg:r("signing_alg",{length:64}),signing_secret:r("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:r("verification_key",{length:4096}),options:r("options",{length:4096}),is_system:w("is_system").notNull().default(0),metadata:r("metadata",{length:4096}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.id],name:"resource_servers_pk"})]),Rt=j("branding",{tenant_id:r("tenant_id",{length:191}).primaryKey().references(()=>B.id,{onDelete:"cascade"}),logo_url:r("logo_url",{length:512}),favicon_url:r("favicon_url",{length:512}),font_url:r("font_url",{length:512}),colors_primary:r("colors_primary",{length:8}),colors_page_background_type:r("colors_page_background_type",{length:32}),colors_page_background_start:r("colors_page_background_start",{length:8}),colors_page_background_end:r("colors_page_background_end",{length:8}),colors_page_background_angle_dev:w("colors_page_background_angle_dev"),dark_mode:r("dark_mode",{length:8})}),lt=j("universal_login_templates",{tenant_id:r("tenant_id",{length:191}).primaryKey().references(()=>B.id,{onDelete:"cascade"}),body:r("body").notNull(),created_at_ts:w("created_at_ts").notNull(),updated_at_ts:w("updated_at_ts").notNull()}),Ze=j("themes",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),themeId:r("themeId",{length:255}).notNull(),displayName:r("displayName",{length:255}).notNull(),colors_primary_button_label:r("colors_primary_button_label",{length:24}).notNull(),colors_primary_button:r("colors_primary_button",{length:24}).notNull(),colors_secondary_button_border:r("colors_secondary_button_border",{length:24}).notNull(),colors_secondary_button_label:r("colors_secondary_button_label",{length:24}).notNull(),colors_base_focus_color:r("colors_base_focus_color",{length:24}).notNull(),colors_base_hover_color:r("colors_base_hover_color",{length:24}).notNull(),colors_body_text:r("colors_body_text",{length:24}).notNull(),colors_captcha_widget_theme:r("colors_captcha_widget_theme",{length:24}).notNull(),colors_error:r("colors_error",{length:24}).notNull(),colors_header:r("colors_header",{length:24}).notNull(),colors_icons:r("colors_icons",{length:24}).notNull(),colors_input_background:r("colors_input_background",{length:24}).notNull(),colors_input_border:r("colors_input_border",{length:24}).notNull(),colors_input_filled_text:r("colors_input_filled_text",{length:24}).notNull(),colors_input_labels_placeholders:r("colors_input_labels_placeholders",{length:24}).notNull(),colors_links_focused_components:r("colors_links_focused_components",{length:24}).notNull(),colors_success:r("colors_success",{length:24}).notNull(),colors_widget_background:r("colors_widget_background",{length:24}).notNull(),colors_widget_border:r("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:r("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:r("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:r("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:r("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:r("page_background_background_color",{length:24}).notNull(),page_background_background_image_url:r("page_background_background_image_url",{length:255}).notNull(),page_background_page_layout:r("page_background_page_layout",{length:24}).notNull(),widget_header_text_alignment:r("widget_header_text_alignment",{length:24}).notNull(),widget_logo_height:w("widget_logo_height").notNull(),widget_logo_position:r("widget_logo_position",{length:24}).notNull(),widget_logo_url:r("widget_logo_url",{length:255}).notNull(),widget_social_buttons_layout:r("widget_social_buttons_layout",{length:24}).notNull(),created_at:r("created_at",{length:35}).notNull(),updated_at:r("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)]),ke=j("forms",{id:r("id",{length:255}).primaryKey(),name:r("name",{length:255}).notNull(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),messages:r("messages",{length:255}),languages:r("languages",{length:255}),translations:r("translations",{length:4096}),nodes:r("nodes",{length:4096}),start:r("start",{length:255}),ending:r("ending",{length:255}),style:r("style",{length:1042}),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("forms_tenant_id_idx").on(n.tenant_id)]),Oe=j("flows",{id:r("id",{length:24}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),name:r("name",{length:150}).notNull(),actions:r("actions"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[D("flows_tenant_id_idx").on(n.tenant_id)]),Ut=j("prompt_settings",{tenant_id:r("tenant_id",{length:191}).primaryKey(),universal_login_experience:r("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)}),dt=j("email_providers",{tenant_id:r("tenant_id",{length:191}).primaryKey(),name:r("name",{length:255}).notNull(),enabled:w("enabled",{mode:"boolean"}).notNull(),default_from_address:r("default_from_address",{length:255}),credentials:r("credentials",{length:2048}).notNull().default("{}"),settings:r("settings",{length:2048}).notNull().default("{}"),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()}),Ue=j("email_templates",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),template:r("template",{length:64}).notNull(),body:r("body").notNull(),from:r("from",{length:255}).notNull(),subject:r("subject",{length:255}).notNull(),syntax:r("syntax",{length:16}).notNull().default("liquid"),result_url:r("result_url",{length:2048}),url_lifetime_in_seconds:w("url_lifetime_in_seconds"),include_email_in_redirect:w("include_email_in_redirect",{mode:"boolean"}).notNull().default(!1),enabled:w("enabled",{mode:"boolean"}).notNull().default(!0),created_at:r("created_at",{length:35}).notNull(),updated_at:r("updated_at",{length:35}).notNull()},n=>[Te({columns:[n.tenant_id,n.template]})]),me=j("hooks",{hook_id:r("hook_id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),url:r("url",{length:512}),trigger_id:r("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:r("form_id",{length:128}),template_id:r("template_id",{length:64}),code_id:r("code_id",{length:21}),metadata:r("metadata")},n=>[D("hooks_tenant_id_idx").on(n.tenant_id)]),Ke=j("hook_code",{id:r("id",{length:21}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),code:r("code").notNull(),secrets:r("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)]),We=j("keys",{kid:r("kid",{length:255}).primaryKey(),tenant_id:r("tenant_id",{length:191}).references(()=>B.id,{onDelete:"cascade"}),created_at:r("created_at",{length:35}).notNull(),revoked_at:r("revoked_at",{length:35}),cert:r("cert",{length:4096}),pkcs7:r("pkcs7",{length:4096}),fingerprint:r("fingerprint",{length:256}),thumbprint:r("thumbprint",{length:256}),current_since:r("current_since",{length:35}),current_until:r("current_until",{length:35}),type:r("type",{length:50}).notNull().default("jwt_signing"),connection:r("connection",{length:255}).references(()=>pe.id,{onDelete:"cascade"})}),Se=j("custom_text",{tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),prompt:r("prompt",{length:64}).notNull(),language:r("language",{length:16}).notNull(),custom_text:r("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=j("authentication_methods",{id:r("id",{length:26}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),user_id:r("user_id",{length:255}).notNull(),type:r("type",{length:32}).notNull(),phone_number:r("phone_number",{length:32}),totp_secret:r("totp_secret",{length:255}),credential_id:r("credential_id",{length:512}),public_key:r("public_key"),sign_count:w("sign_count"),credential_backed_up:w("credential_backed_up"),transports:r("transports",{length:512}),friendly_name:r("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)]),F=j("logs",{log_id:r("log_id",{length:21}).primaryKey(),category:r("category",{length:255}),tenant_id:r("tenant_id",{length:64}),user_id:r("user_id",{length:64}),ip:r("ip",{length:255}),type:r("type",{length:8}).notNull(),date:r("date",{length:35}).notNull(),client_id:r("client_id",{length:255}),client_name:r("client_name",{length:255}),user_agent:r("user_agent",{length:255}),description:r("description",{length:255}),details:r("details",{length:2048}),isMobile:w("isMobile"),user_name:r("user_name",{length:255}),connection:r("connection",{length:255}),connection_id:r("connection_id",{length:255}),audience:r("audience",{length:255}),scope:r("scope",{length:255}),strategy:r("strategy",{length:255}),strategy_type:r("strategy_type",{length:255}),hostname:r("hostname",{length:255}),auth0_client:r("auth0_client",{length:8192}),session_connection:r("session_connection",{length:255}),country_code:r("country_code",{length:2}),city_name:r("city_name",{length:255}),latitude:r("latitude",{length:255}),longitude:r("longitude",{length:255}),time_zone:r("time_zone",{length:255}),continent_code:r("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)]),P=j("outbox_events",{id:r("id",{length:26}).primaryKey(),tenant_id:r("tenant_id",{length:191}).notNull().references(()=>B.id,{onDelete:"cascade"}),event_type:r("event_type",{length:64}).notNull(),log_type:r("log_type",{length:64}).notNull(),aggregate_type:r("aggregate_type",{length:64}).notNull(),aggregate_id:r("aggregate_id",{length:255}).notNull(),payload:r("payload").notNull(),created_at:r("created_at",{length:35}).notNull(),processed_at:r("processed_at",{length:35}),retry_count:w("retry_count").notNull().default(0),next_retry_at:r("next_retry_at",{length:35}),error:r("error"),claimed_by:r("claimed_by",{length:255}),claim_expires_at:r("claim_expires_at",{length:35}),dead_lettered_at:r("dead_lettered_at",{length:35}),final_error:r("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)]),hr=Object.freeze(Object.defineProperty({__proto__:null,authenticationCodes:_r,authenticationMethods:ue,branding:Rt,clientGrants:ye,clientRegistrationTokens:X,clients:Z,codes:re,connections:pe,customDomains:Ie,customText:Se,domains:fr,emailProviders:dt,emailTemplates:Ue,flows:Oe,forms:ke,hookCode:Ke,hooks:me,invites:xe,keys:We,loginSessions:Y,logs:F,organizations:ee,otps:ur,outboxEvents:P,passwords:oe,promptSettings:Ut,refreshTokens:W,resourceServers:te,rolePermissions:Re,roles:_e,sessions:ae,tenants:B,themes:Ze,tickets:pr,universalLoginTemplates:lt,userOrganizations:le,userPermissions:qe,userRoles:Be,users:H},Symbol.toStringTag,{value:"Module"}));function G(n){if(n==null||typeof n!="object")return n;if(Array.isArray(n))return n.map(t=>t!==null&&typeof t=="object"?G(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(o=>o!==null&&typeof o=="object"?G(o):o):e[t]=G(i))}return e}function gr(n,e,t={...n}){for(const i of e)n[i]!==void 0&&(t[i]=JSON.stringify(n[i]));return t}function mr(n,e,t=n){for(const i of e)n[i]!==void 0&&(t[i]=n[i]?1:0)}function cs(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 Yn(n,e="",t={}){for(const i in n)if(Object.prototype.hasOwnProperty.call(n,i)){const o=e?`${e}_${i}`:i,s=n[i];typeof s=="object"&&s!==null&&!Array.isArray(s)?Yn(s,o,t):typeof s=="boolean"?t[o]=s?1:0:t[o]=s}return t}function _s(n,e){const t={};for(const[i,o]of Object.entries(n)){const s=e.find(l=>i.startsWith(`${l}_`));if(!s)t[i]=o;else{const l=i.slice(s.length+1);t[s]={...t[s],[l]:o}}}return t}function yr(n){return typeof n=="string"?parseInt(n,10):typeof n=="bigint"?Number(n):n}function vr(n){return n==="dark"||n==="light"||n==="auto"}function wr(n){return{async get(e){const t=await n.select().from(Rt).where(c(Rt.tenant_id,e)).get();if(!t)return null;const{tenant_id:i,colors_primary:o,colors_page_background_type:s,colors_page_background_start:l,colors_page_background_end:d,colors_page_background_angle_dev:u,font_url:f,dark_mode:p,...m}=t;return G({...m,colors:{primary:o,page_background:{type:s,start:l,end:d,angle_deg:u}},font:f?{url:f}:void 0,dark_mode:vr(p)?p:void 0})},async set(e,t){const{colors:i,font:o,dark_mode:s,...l}=t,d=i==null?void 0:i.page_background,u=d&&typeof d=="object"?d:void 0,f={...l,colors_primary:i==null?void 0:i.primary,colors_page_background_type:u==null?void 0:u.type,colors_page_background_start:u==null?void 0:u.start,colors_page_background_end:u==null?void 0:u.end,colors_page_background_angle_dev:u==null?void 0:u.angle_deg,font_url:o==null?void 0:o.url,dark_mode:s};await n.insert(Rt).values({tenant_id:e,...f}).onConflictDoUpdate({target:Rt.tenant_id,set:f})}}}var _t=class extends Error{constructor(e=500,t){super(t==null?void 0:t.message,{cause:t==null?void 0:t.cause});v(this,"res");v(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 Qe(n,e,t){const i=e.split(/ OR /i);if(i.length>1){const f=i.map(p=>{const m=p.trim().match(/^([^:]+):(.+)$/);if(m){const[,y,E]=m;if(!y||!E)return null;const A=E.replace(/^"(.*)"$/,"$1"),J=n[y.trim()];return J?c(J,A.trim()):null}return null}).filter(Boolean);return f.length===0?void 0:$e(...f)}const o=[];let s="",l=!1;for(let f=0;f<e.length;f++){const p=e[f];p==='"'?(l=!l,s+=p):p===" "&&!l?s.trim()&&(o.push(s.trim()),s=""):s+=p}s.trim()&&o.push(s.trim());const d=o.filter(f=>f!=="AND").map(f=>f.replace(/^([^:]+)=/g,"$1:")).map(f=>{let p=f.startsWith("-"),m=null,y="",E=!1,A;if(f.startsWith("-_exists_:"))m=f.substring(10),E=!0,p=!0;else if(f.startsWith("_exists_:"))m=f.substring(9),E=!0,p=!1;else if(f.includes(":")){const J=p?f.substring(1):f,Q=J.indexOf(":");m=J.substring(0,Q),y=J.substring(Q+1),E=!1,y.startsWith(">=")?(A=">=",y=y.substring(2)):y.startsWith(">")?(A=">",y=y.substring(1)):y.startsWith("<=")?(A="<=",y=y.substring(2)):y.startsWith("<")?(A="<",y=y.substring(1)):A="=",y.startsWith('"')&&y.endsWith('"')&&y.length>1&&(y=y.slice(1,-1))}else m=null,y=f,E=!1;return{key:m,value:y,isNegation:p,isExistsQuery:E,operator:A}}),u=[];for(const{key:f,value:p,isNegation:m,isExistsQuery:y,operator:E}of d)if(f){const A=n[f];if(!A){y?u.push(m?O`${O.identifier(f)} IS NULL`:O`${O.identifier(f)} IS NOT NULL`):u.push(O`${O.identifier(f)} ${O.raw(m?"!=":E??"=")} ${p}`);continue}if(y)u.push(m?Ce(A):cn(A));else if(m)switch(E){case">":u.push(yt(A,p));break;case">=":u.push(Ge(A,p));break;case"<":u.push(At(A,p));break;case"<=":u.push(pn(A,p));break;default:u.push(er(A,p))}else switch(E){case">":u.push(pn(A,p));break;case">=":u.push(At(A,p));break;case"<":u.push(Ge(A,p));break;case"<=":u.push(yt(A,p));break;default:u.push(c(A,p))}}else if(p){const J=(p.includes("|")?[...t,"user_id"]:t).map(Q=>{const ie=n[Q];return ie?Q==="user_id"?c(ie,p):xt(ie,`%${p}%`):null}).filter(Boolean);J.length>0&&u.push($e(...J))}if(u.length!==0)return u.length===1?u[0]:g(...u)}const yi=["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","hide_sign_up_disabled_error"],vi=["callbacks","allowed_origins","web_origins","client_aliases","allowed_clients","allowed_logout_urls","grant_types","signing_keys"],wi=["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 on(n){const{tenant_id:e,connections:t,...i}=n,o={...i};for(const s of yi)o[s]=!!i[s];for(const s of vi)o[s]=z(i[s],[]);for(const s of wi)o[s]=z(i[s],{});return o.connections=z(t,[]),G(o)}function Ai(n){const e={...n};mr(n,yi,e);for(const t of vi)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]||[]));for(const t of wi)n[t]!==void 0&&(e[t]=JSON.stringify(n[t]||{}));return n.connections!==void 0&&(e.connections=JSON.stringify(n.connections||[])),cs(e)}function Nr(n){return{async create(e,t){var l,d;const i=new Date().toISOString(),o={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 yi)o[u]=t[u]??!1;o.oidc_conformant=t.oidc_conformant??!0,o.auth0_conformant=t.auth0_conformant??!0,o.sso_disabled=t.sso_disabled??!1;for(const u of vi)o[u]=t[u]||[];for(const u of wi)o[u]=t[u]||{};o.connections=t.connections||[];const s=Ai(o);try{await n.insert(Z).values({...s,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 _t(409,{message:"Client already exists"}):u}return on({...s,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?on(i):null},async getByClientId(e){const t=await n.select().from(Z).where(c(Z.client_id,e)).get();return t?{...on(t),tenant_id:t.tenant_id}:null},async update(e,t,i){const o=Ai({...i,updated_at:new Date().toISOString()});return delete o.client_id,delete o.tenant_id,await n.update(Z).set(o).where(g(c(Z.tenant_id,e),c(Z.client_id,t))),!0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(Z).where(c(Z.tenant_id,e)).$dynamic();if(d){const y=Qe(Z,d,["name","client_id"]);y&&(u=u.where(g(c(Z.tenant_id,e),y)))}if(l!=null&&l.sort_by){const y=Z[l.sort_by];y&&(u=u.orderBy(l.sort_order==="desc"?se(y):he(y)))}const p=(await u.offset(i*o).limit(o)).map(on);if(!s)return{clients:p};const[m]=await n.select({count:ge()}).from(Z).where(c(Z.tenant_id,e));return{clients:p,start:i*o,limit:o,length:Number((m==null?void 0:m.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 Sr(n){const{tenant_id:e,is_system:t,options:i,metadata:o,...s}=n;return G({...s,options:z(i,{}),metadata:z(o),is_system:t?!0:void 0})}function br(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 o=z(i.connections,[])||[];if(o.length===0)return[];const l=(await n.select().from(pe).where(g(c(pe.tenant_id,e),De(pe.id,o))).all()).map(Sr);return o.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(o=>(z(o.connections,[])||[]).includes(t)).map(o=>o.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 s=await n.run(O`UPDATE clients SET connections = CASE
2
2
  WHEN connections IS NULL OR connections = '[]' OR connections = ''
3
3
  THEN json_array(${t})
4
4
  WHEN EXISTS (SELECT 1 FROM json_each(connections) WHERE value = ${t})
@@ -10,4 +10,4 @@
10
10
  FROM json_each(COALESCE(connections, '[]')) AS je
11
11
  WHERE je.value != ${t}
12
12
  )
13
- WHERE tenant_id = ${e} AND client_id = ${i}`);return(o.changes??((l=o.meta)==null?void 0:l.changes)??0)>0}}}let br="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Er=n=>crypto.getRandomValues(new Uint8Array(n)),xr=(n,e,t)=>{let i=256-256%n.length;if(i===256){let s=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]&s],d.length>=l)return d}}}let o=Math.ceil(1.6*256*e/i);return(s=e)=>{if(!s)return"";let l="";for(;;){let d=t(o),u=o;for(;u--;)if(d[u]<i&&(l+=n[d[u]%n.length],l.length>=s))return l}}},kr=(n,e=21)=>xr(n,e|0,Er),Le=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=br[t[n]&63];return e};function Ln(n){const{tenant_id:e,scope:t,authorization_details_types:i,allow_any_organization:o,is_system:s,...l}=n;return Q({...l,scope:F(t,[]),authorization_details_types:F(i,[]),allow_any_organization:!!o,is_system:!!s})}function Or(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||Le(),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(ye).values(s),Ln({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(ye).where(g(c(ye.tenant_id,e),c(ye.id,t))).get();return i?Ln(i):null},async update(e,t,i){const{scope:o,authorization_details_types:s,allow_any_organization:l,is_system:d,...u}=i,f={...u,updated_at:new Date().toISOString()};return o!==void 0&&(f.scope=JSON.stringify(o)),s!==void 0&&(f.authorization_details_types=JSON.stringify(s)),l!==void 0&&(f.allow_any_organization=l?1:0),d!==void 0&&(f.is_system=d?1:0),(await n.update(ye).set(f).where(g(c(ye.tenant_id,e),c(ye.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?We(ye,d,["client_id","audience"]):void 0,f=u?g(c(ye.tenant_id,e),u):c(ye.tenant_id,e);let p=n.select().from(ye).where(f).$dynamic();if(l!=null&&l.sort_by){const T=ye[l.sort_by];T&&(p=p.orderBy(l.sort_order==="desc"?se(T):he(T)))}else p=p.orderBy(he(ye.created_at));const y=(await p.offset(i*o).limit(o)).map(Ln);if(!s)return{client_grants:y};const[E]=await n.select({count:ge()}).from(ye).where(f);return{client_grants:y,start:i*o,limit:o,length:Number((E==null?void 0:E.count)??0)}},async remove(e,t){return(await n.delete(ye).where(g(c(ye.tenant_id,e),c(ye.id,t))).returning()).length>0}}}function Tr(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 o=0,i=Object.getOwnPropertySymbols(n);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(n,i[o])&&(t[i[o]]=n[i[o]]);return t}function Ar(n,e){var t;return((t=n==null?void 0:n._def)===null||t===void 0?void 0:t.typeName)===e}function Lt(n,e){const t=n.ZodType.prototype[e];n.ZodType.prototype[e]=function(...i){const o=t.apply(this,i);return o._def.openapi=this._def.openapi,o}}function Ir(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(o,s){var l,d,u,f,p,m;const y=typeof o=="string"?s:o,E=y??{},{param:T}=E,G=Tr(E,["param"]),W=Object.assign(Object.assign({},(l=this._def.openapi)===null||l===void 0?void 0:l._internal),typeof o=="string"?{refId:o}:void 0),ie=Object.assign(Object.assign(Object.assign({},(d=this._def.openapi)===null||d===void 0?void 0:d.metadata),G),!((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({},(m=(p=this._def.openapi)===null||p===void 0?void 0:p.metadata)===null||m===void 0?void 0:m.param),T)}:void 0),Me=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(W).length>0?{_internal:W}:void 0),Object.keys(ie).length>0?{metadata:ie}:void 0)}));if(Ar(this,"ZodObject")){const Se=this.extend;Me.extend=function(...Ee){var it,rt,En,xn,kn,On,Tn;const An=Se.apply(this,Ee);return An._def.openapi={_internal:{extendedFrom:!((rt=(it=this._def.openapi)===null||it===void 0?void 0:it._internal)===null||rt===void 0)&&rt.refId?{refId:(xn=(En=this._def.openapi)===null||En===void 0?void 0:En._internal)===null||xn===void 0?void 0:xn.refId,schema:this}:(On=(kn=this._def.openapi)===null||kn===void 0?void 0:kn._internal)===null||On===void 0?void 0:On.extendedFrom},metadata:(Tn=An._def.openapi)===null||Tn===void 0?void 0:Tn.metadata},An}}return Me},Lt(n,"optional"),Lt(n,"nullable"),Lt(n,"default"),Lt(n,"transform"),Lt(n,"refine");const e=n.ZodObject.prototype.deepPartial;n.ZodObject.prototype.deepPartial=function(){const o=this._def.shape(),s=e.apply(this),l=s._def.shape();return Object.entries(l).forEach(([d,u])=>{var f,p;u._def.openapi=(p=(f=o[d])===null||f===void 0?void 0:f._def)===null||p===void 0?void 0:p.openapi}),s._def.openapi=void 0,s};const t=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...o){const s=t.apply(this,o);return s._def.openapi=void 0,s};const i=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...o){const s=i.apply(this,o);return s._def.openapi=void 0,s}}new Set(".\\+*[^]$()");var K;(function(n){n.assertEqual=o=>{};function e(o){}n.assertIs=e;function t(o){throw new Error}n.assertNever=t,n.arrayToEnum=o=>{const s={};for(const l of o)s[l]=l;return s},n.getValidEnumValues=o=>{const s=n.objectKeys(o).filter(d=>typeof o[o[d]]!="number"),l={};for(const d of s)l[d]=o[d];return n.objectValues(l)},n.objectValues=o=>n.objectKeys(o).map(function(s){return o[s]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const l in o)Object.prototype.hasOwnProperty.call(o,l)&&s.push(l);return s},n.find=(o,s)=>{for(const l of o)if(s(l))return l},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function i(o,s=" | "){return o.map(l=>typeof l=="string"?`'${l}'`:l).join(s)}n.joinValues=i,n.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var ei;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(ei||(ei={}));const A=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=n=>{switch(typeof n){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(n)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(n)?A.array:n===null?A.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?A.promise:typeof Map<"u"&&n instanceof Map?A.map:typeof Set<"u"&&n instanceof Set?A.set:typeof Date<"u"&&n instanceof Date?A.date:A.object;default:return A.unknown}},S=K.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 et 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(s){return s.message},i={_errors:[]},o=s=>{for(const l of s.issues)if(l.code==="invalid_union")l.unionErrors.map(o);else if(l.code==="invalid_return_type")o(l.returnTypeError);else if(l.code==="invalid_arguments")o(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 o(this),i}static assert(e){if(!(e instanceof et))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];t[s]=t[s]||[],t[s].push(e(o))}else i.push(e(o));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}et.create=n=>new et(n);const fn=(n,e)=>{let t;switch(n.code){case S.invalid_type:n.received===A.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case S.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,K.jsonStringifyReplacer)}`;break;case S.unrecognized_keys:t=`Unrecognized key(s) in object: ${K.joinValues(n.keys,", ")}`;break;case S.invalid_union:t="Invalid input";break;case S.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${K.joinValues(n.options)}`;break;case S.invalid_enum_value:t=`Invalid enum value. Expected ${K.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}"`:K.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,K.assertNever(n)}return{message:t}};let Cr=fn;function us(){return Cr}const ps=n=>{const{data:e,path:t,errorMaps:i,issueData:o}=n,s=[...t,...o.path||[]],l={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.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{...o,path:s,message:d}};function k(n,e){const t=us(),i=ps({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===fn?void 0:fn].filter(o=>!!o)});n.common.issues.push(i)}class Te{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 o of t){if(o.status==="aborted")return R;o.status==="dirty"&&e.dirty(),i.push(o.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const o of t){const s=await o.key,l=await o.value;i.push({key:s,value:l})}return Te.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const o of t){const{key:s,value:l}=o;if(s.status==="aborted"||l.status==="aborted")return R;s.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof l.value<"u"||o.alwaysSet)&&(i[s.value]=l.value)}return{status:e.value,value:i}}}const R=Object.freeze({status:"aborted"}),kt=n=>({status:"dirty",value:n}),Fe=n=>({status:"valid",value:n}),ti=n=>n.status==="aborted",ni=n=>n.status==="dirty",St=n=>n.status==="valid",qt=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 tt{constructor(e,t,i,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=o}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 Ai=(n,e)=>{if(St(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 et(n.common.issues);return this._error=t,this._error}}};function q(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:o}=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:o}:{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:o}}class ${get description(){return this._def.description}_getType(e){return at(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:at(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Te,ctx:{common:e.parent.common,data:e.data,parsedType:at(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(qt(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:at(e)},o=this._parseSync({data:e,path:i.path,parent:i});return Ai(i,o)}"~validate"(e){var i,o;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:at(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return St(s)?{value:s.value}:{issues:t.common.issues}}catch(s){(o=(i=s==null?void 0:s.message)==null?void 0:i.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>St(s)?{value:s.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:at(e)},o=this._parse({data:e,path:i.path,parent:i}),s=await(qt(o)?o:Promise.resolve(o));return Ai(i,s)}refine(e,t){const i=o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t;return this._refinement((o,s)=>{const l=e(o),d=()=>s.addIssue({code:S.custom,...i(o)});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,o)=>e(i)?!0:(o.addIssue(typeof t=="function"?t(i,o):t),!1))}_refinement(e){return new nt({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 Ye.create(this,this._def)}nullable(){return ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ge.create(this)}promise(){return Qt.create(this,this._def)}or(e){return Vt.create([this,e],this._def)}and(e){return Zt.create(this,e,this._def)}transform(e){return new nt({...q(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Gt({...q(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new Si({typeName:U.ZodBranded,type:this,...q(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Wt({...q(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 Nn.create(this,e)}readonly(){return Xt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Dr=/^c[^\s-]{8,}$/i,Lr=/^[0-9a-z]+$/,Rr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ur=/^[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,zr=/^[a-z0-9_-]{21}$/i,Fr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Pr=/^[-+]?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)?)??$/,Mr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,qr="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Rn;const Br=/^(?:(?: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])$/,$r=/^(?:(?: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])$/,jr=/^(([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]))$/,Vr=/^(([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])$/,Zr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fs="((\\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])))",Kr=new RegExp(`^${fs}$`);function hs(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 Jr(n){return new RegExp(`^${hs(n)}$`)}function gs(n){let e=`${fs}T${hs(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 Qr(n,e){return!!((e==="v4"||!e)&&Br.test(n)||(e==="v6"||!e)&&jr.test(n))}function Gr(n,e){if(!Fr.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,"="),o=JSON.parse(atob(i));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Wr(n,e){return!!((e==="v4"||!e)&&$r.test(n)||(e==="v6"||!e)&&Vr.test(n))}class Xe extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.string){const s=this._getOrReturnCtx(e);return k(s,{code:S.invalid_type,expected:A.string,received:s.parsedType}),R}const i=new Te;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:S.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:S.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="length"){const l=e.data.length>s.value,d=e.data.length<s.value;(l||d)&&(o=this._getOrReturnCtx(e,o),l?k(o,{code:S.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):d&&k(o,{code:S.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),i.dirty())}else if(s.kind==="email")Mr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"email",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="emoji")Rn||(Rn=new RegExp(qr,"u")),Rn.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"emoji",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="uuid")Ur.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"uuid",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="nanoid")zr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"nanoid",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid")Dr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid2")Lr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid2",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="ulid")Rr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ulid",code:S.invalid_string,message:s.message}),i.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),k(o,{validation:"url",code:S.invalid_string,message:s.message}),i.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"regex",code:S.invalid_string,message:s.message}),i.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),i.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:{startsWith:s.value},message:s.message}),i.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()):s.kind==="datetime"?gs(s).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:"datetime",message:s.message}),i.dirty()):s.kind==="date"?Kr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:"date",message:s.message}),i.dirty()):s.kind==="time"?Jr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:S.invalid_string,validation:"time",message:s.message}),i.dirty()):s.kind==="duration"?Pr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"duration",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="ip"?Qr(e.data,s.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ip",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="jwt"?Gr(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"jwt",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="cidr"?Wr(e.data,s.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cidr",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="base64"?Zr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64",code:S.invalid_string,message:s.message}),i.dirty()):s.kind==="base64url"?Hr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64url",code:S.invalid_string,message:s.message}),i.dirty()):K.assertNever(s);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(o=>e.test(o),{validation:t,code:S.invalid_string,...C.errToObj(i)})}_addCheck(e){return new Xe({...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 Xe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Xe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Xe({...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}}Xe.create=n=>new Xe({checks:[],typeName:U.ZodString,coerce:(n==null?void 0:n.coerce)??!1,...q(n)});function Xr(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,o=t>i?t:i,s=Number.parseInt(n.toFixed(o).replace(".","")),l=Number.parseInt(e.toFixed(o).replace(".",""));return s%l/10**o}class Nt extends ${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)!==A.number){const s=this._getOrReturnCtx(e);return k(s,{code:S.invalid_type,expected:A.number,received:s.parsedType}),R}let i;const o=new Te;for(const s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:S.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Xr(e.data,s.value)!==0&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:S.not_finite,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.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,o){return new Nt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(o)}]})}_addCheck(e){return new Nt({...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"&&K.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)}}Nt.create=n=>new Nt({checks:[],typeName:U.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...q(n)});class At extends ${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)!==A.bigint)return this._getInvalidInput(e);let i;const o=new Te;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),k(i,{code:S.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return k(t,{code:S.invalid_type,expected:A.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,o){return new At({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(o)}]})}_addCheck(e){return new At({...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}}At.create=n=>new At({checks:[],typeName:U.ZodBigInt,coerce:(n==null?void 0:n.coerce)??!1,...q(n)});class hn extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.boolean){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:A.boolean,received:i.parsedType}),R}return Fe(e.data)}}hn.create=n=>new hn({typeName:U.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...q(n)});class Bt extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.date){const s=this._getOrReturnCtx(e);return k(s,{code:S.invalid_type,expected:A.date,received:s.parsedType}),R}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return k(s,{code:S.invalid_date}),R}const i=new Te;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:S.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),i.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:S.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()):K.assertNever(s);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Bt({...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}}Bt.create=n=>new Bt({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:U.ZodDate,...q(n)});class ii extends ${_parse(e){if(this._getType(e)!==A.symbol){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:A.symbol,received:i.parsedType}),R}return Fe(e.data)}}ii.create=n=>new ii({typeName:U.ZodSymbol,...q(n)});class gn extends ${_parse(e){if(this._getType(e)!==A.undefined){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:A.undefined,received:i.parsedType}),R}return Fe(e.data)}}gn.create=n=>new gn({typeName:U.ZodUndefined,...q(n)});class $t extends ${_parse(e){if(this._getType(e)!==A.null){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:A.null,received:i.parsedType}),R}return Fe(e.data)}}$t.create=n=>new $t({typeName:U.ZodNull,...q(n)});class jt extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return Fe(e.data)}}jt.create=n=>new jt({typeName:U.ZodAny,...q(n)});class mn extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return Fe(e.data)}}mn.create=n=>new mn({typeName:U.ZodUnknown,...q(n)});class st extends ${_parse(e){const t=this._getOrReturnCtx(e);return k(t,{code:S.invalid_type,expected:A.never,received:t.parsedType}),R}}st.create=n=>new st({typeName:U.ZodNever,...q(n)});class oi extends ${_parse(e){if(this._getType(e)!==A.undefined){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:A.void,received:i.parsedType}),R}return Fe(e.data)}}oi.create=n=>new oi({typeName:U.ZodVoid,...q(n)});class Ge extends ${_parse(e){const{ctx:t,status:i}=this._processInputParams(e),o=this._def;if(t.parsedType!==A.array)return k(t,{code:S.invalid_type,expected:A.array,received:t.parsedType}),R;if(o.exactLength!==null){const l=t.data.length>o.exactLength.value,d=t.data.length<o.exactLength.value;(l||d)&&(k(t,{code:l?S.too_big:S.too_small,minimum:d?o.exactLength.value:void 0,maximum:l?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),i.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(k(t,{code:S.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),i.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(k(t,{code:S.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,d)=>o.type._parseAsync(new tt(t,l,t.path,d)))).then(l=>Te.mergeArray(i,l));const s=[...t.data].map((l,d)=>o.type._parseSync(new tt(t,l,t.path,d)));return Te.mergeArray(i,s)}get element(){return this._def.type}min(e,t){return new Ge({...this._def,minLength:{value:e,message:C.toString(t)}})}max(e,t){return new Ge({...this._def,maxLength:{value:e,message:C.toString(t)}})}length(e,t){return new Ge({...this._def,exactLength:{value:e,message:C.toString(t)}})}nonempty(e){return this.min(1,e)}}Ge.create=(n,e)=>new Ge({type:n,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...q(e)});function Et(n){if(n instanceof de){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=Ye.create(Et(i))}return new de({...n._def,shape:()=>e})}else return n instanceof Ge?new Ge({...n._def,type:Et(n.element)}):n instanceof Ye?Ye.create(Et(n.unwrap())):n instanceof ft?ft.create(Et(n.unwrap())):n instanceof ut?ut.create(n.items.map(e=>Et(e))):n}class de extends ${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=K.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==A.object){const f=this._getOrReturnCtx(e);return k(f,{code:S.invalid_type,expected:A.object,received:f.parsedType}),R}const{status:i,ctx:o}=this._processInputParams(e),{shape:s,keys:l}=this._getCached(),d=[];if(!(this._def.catchall instanceof st&&this._def.unknownKeys==="strip"))for(const f in o.data)l.includes(f)||d.push(f);const u=[];for(const f of l){const p=s[f],m=o.data[f];u.push({key:{status:"valid",value:f},value:p._parse(new tt(o,m,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof st){const f=this._def.unknownKeys;if(f==="passthrough")for(const p of d)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(f==="strict")d.length>0&&(k(o,{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 m=o.data[p];u.push({key:{status:"valid",value:p},value:f._parse(new tt(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const p of u){const m=await p.key,y=await p.value;f.push({key:m,value:y,alwaysSet:p.alwaysSet})}return f}).then(f=>Te.mergeObjectSync(i,f)):Te.mergeObjectSync(i,u)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new de({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var s,l;const o=((l=(s=this._def).errorMap)==null?void 0:l.call(s,t,i).message)??i.defaultError;return t.code==="unrecognized_keys"?{message:C.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({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 de({...this._def,catchall:e})}pick(e){const t={};for(const i of K.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const i of K.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new de({...this._def,shape:()=>t})}deepPartial(){return Et(this)}partial(e){const t={};for(const i of K.objectKeys(this.shape)){const o=this.shape[i];e&&!e[i]?t[i]=o:t[i]=o.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const i of K.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let s=this.shape[i];for(;s instanceof Ye;)s=s._def.innerType;t[i]=s}return new de({...this._def,shape:()=>t})}keyof(){return ms(K.objectKeys(this.shape))}}de.create=(n,e)=>new de({shape:()=>n,unknownKeys:"strip",catchall:st.create(),typeName:U.ZodObject,...q(e)});de.strictCreate=(n,e)=>new de({shape:()=>n,unknownKeys:"strict",catchall:st.create(),typeName:U.ZodObject,...q(e)});de.lazycreate=(n,e)=>new de({shape:n,unknownKeys:"strip",catchall:st.create(),typeName:U.ZodObject,...q(e)});class Vt extends ${_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function o(s){for(const d of s)if(d.result.status==="valid")return d.result;for(const d of s)if(d.result.status==="dirty")return t.common.issues.push(...d.ctx.common.issues),d.result;const l=s.map(d=>new et(d.ctx.common.issues));return k(t,{code:S.invalid_union,unionErrors:l}),R}if(t.common.async)return Promise.all(i.map(async s=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(o);{let s;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"&&!s&&(s={result:p,ctx:f}),f.common.issues.length&&l.push(f.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const d=l.map(u=>new et(u));return k(t,{code:S.invalid_union,unionErrors:d}),R}}get options(){return this._def.options}}Vt.create=(n,e)=>new Vt({options:n,typeName:U.ZodUnion,...q(e)});const ot=n=>n instanceof yn?ot(n.schema):n instanceof nt?ot(n.innerType()):n instanceof Kt?[n.value]:n instanceof pt?n.options:n instanceof Jt?K.objectValues(n.enum):n instanceof Gt?ot(n._def.innerType):n instanceof gn?[void 0]:n instanceof $t?[null]:n instanceof Ye?[void 0,...ot(n.unwrap())]:n instanceof ft?[null,...ot(n.unwrap())]:n instanceof Si||n instanceof Xt?ot(n.unwrap()):n instanceof Wt?ot(n._def.innerType):[];class Sn extends ${_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.object)return k(t,{code:S.invalid_type,expected:A.object,received:t.parsedType}),R;const i=this.discriminator,o=t.data[i],s=this.optionsMap.get(o);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(k(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 o=new Map;for(const s of t){const l=ot(s.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(o.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);o.set(d,s)}}return new Sn({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...q(i)})}}function ai(n,e){const t=at(n),i=at(e);if(n===e)return{valid:!0,data:n};if(t===A.object&&i===A.object){const o=K.objectKeys(e),s=K.objectKeys(n).filter(d=>o.indexOf(d)!==-1),l={...n,...e};for(const d of s){const u=ai(n[d],e[d]);if(!u.valid)return{valid:!1};l[d]=u.data}return{valid:!0,data:l}}else if(t===A.array&&i===A.array){if(n.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<n.length;s++){const l=n[s],d=e[s],u=ai(l,d);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return t===A.date&&i===A.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Zt extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e),o=(s,l)=>{if(ti(s)||ti(l))return R;const d=ai(s.value,l.value);return d.valid?((ni(s)||ni(l))&&t.dirty(),{status:t.value,value:d.data}):(k(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(([s,l])=>o(s,l)):o(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Zt.create=(n,e,t)=>new Zt({left:n,right:e,typeName:U.ZodIntersection,...q(t)});class ut extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==A.array)return k(i,{code:S.invalid_type,expected:A.array,received:i.parsedType}),R;if(i.data.length<this._def.items.length)return k(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&&(k(i,{code:S.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...i.data].map((l,d)=>{const u=this._def.items[d]||this._def.rest;return u?u._parse(new tt(i,l,i.path,d)):null}).filter(l=>!!l);return i.common.async?Promise.all(s).then(l=>Te.mergeArray(t,l)):Te.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ut({...this._def,rest:e})}}ut.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ut({items:n,typeName:U.ZodTuple,rest:null,...q(e)})};class Ht extends ${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!==A.object)return k(i,{code:S.invalid_type,expected:A.object,received:i.parsedType}),R;const o=[],s=this._def.keyType,l=this._def.valueType;for(const d in i.data)o.push({key:s._parse(new tt(i,d,i.path,d)),value:l._parse(new tt(i,i.data[d],i.path,d)),alwaysSet:d in i.data});return i.common.async?Te.mergeObjectAsync(t,o):Te.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof $?new Ht({keyType:e,valueType:t,typeName:U.ZodRecord,...q(i)}):new Ht({keyType:Xe.create(),valueType:e,typeName:U.ZodRecord,...q(t)})}}class si extends ${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!==A.map)return k(i,{code:S.invalid_type,expected:A.map,received:i.parsedType}),R;const o=this._def.keyType,s=this._def.valueType,l=[...i.data.entries()].map(([d,u],f)=>({key:o._parse(new tt(i,d,i.path,[f,"key"])),value:s._parse(new tt(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}}}}si.create=(n,e,t)=>new si({valueType:e,keyType:n,typeName:U.ZodMap,...q(t)});class It extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==A.set)return k(i,{code:S.invalid_type,expected:A.set,received:i.parsedType}),R;const o=this._def;o.minSize!==null&&i.data.size<o.minSize.value&&(k(i,{code:S.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&i.data.size>o.maxSize.value&&(k(i,{code:S.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());const s=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)=>s._parse(new tt(i,u,i.path,f)));return i.common.async?Promise.all(d).then(u=>l(u)):l(d)}min(e,t){return new It({...this._def,minSize:{value:e,message:C.toString(t)}})}max(e,t){return new It({...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)}}It.create=(n,e)=>new It({valueType:n,minSize:null,maxSize:null,typeName:U.ZodSet,...q(e)});class yn extends ${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})}}yn.create=(n,e)=>new yn({getter:n,typeName:U.ZodLazy,...q(e)});class Kt extends ${_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return k(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}}Kt.create=(n,e)=>new Kt({value:n,typeName:U.ZodLiteral,...q(e)});function ms(n,e){return new pt({values:n,typeName:U.ZodEnum,...q(e)})}class pt extends ${_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return k(t,{expected:K.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 k(t,{received:t.data,code:S.invalid_enum_value,options:i}),R}return Fe(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 pt.create(e,{...this._def,...t})}exclude(e,t=this._def){return pt.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}pt.create=ms;class Jt extends ${_parse(e){const t=K.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==A.string&&i.parsedType!==A.number){const o=K.objectValues(t);return k(i,{expected:K.joinValues(o),received:i.parsedType,code:S.invalid_type}),R}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const o=K.objectValues(t);return k(i,{received:i.data,code:S.invalid_enum_value,options:o}),R}return Fe(e.data)}get enum(){return this._def.values}}Jt.create=(n,e)=>new Jt({values:n,typeName:U.ZodNativeEnum,...q(e)});class Qt extends ${unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.promise&&t.common.async===!1)return k(t,{code:S.invalid_type,expected:A.promise,received:t.parsedType}),R;const i=t.parsedType===A.promise?t.data:Promise.resolve(t.data);return Fe(i.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Qt.create=(n,e)=>new Qt({type:n,typeName:U.ZodPromise,...q(e)});class nt extends ${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),o=this._def.effect||null,s={addIssue:l=>{k(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const l=o.transform(i.data,s);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"?kt(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"?kt(d.value):d}}if(o.type==="refinement"){const l=d=>{const u=o.refinement(d,s);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(o.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!St(l))return R;const d=o.transform(l.value,s);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=>St(l)?Promise.resolve(o.transform(l.value,s)).then(d=>({status:t.value,value:d})):R);K.assertNever(o)}}nt.create=(n,e,t)=>new nt({schema:n,typeName:U.ZodEffects,effect:e,...q(t)});nt.createWithPreprocess=(n,e,t)=>new nt({schema:e,effect:{type:"preprocess",transform:n},typeName:U.ZodEffects,...q(t)});class Ye extends ${_parse(e){return this._getType(e)===A.undefined?Fe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ye.create=(n,e)=>new Ye({innerType:n,typeName:U.ZodOptional,...q(e)});class ft extends ${_parse(e){return this._getType(e)===A.null?Fe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ft.create=(n,e)=>new ft({innerType:n,typeName:U.ZodNullable,...q(e)});class Gt extends ${_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===A.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Gt.create=(n,e)=>new Gt({innerType:n,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...q(e)});class Wt extends ${_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return qt(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new et(i.common.issues)},input:i.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new et(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Wt.create=(n,e)=>new Wt({innerType:n,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...q(e)});class ri extends ${_parse(e){if(this._getType(e)!==A.nan){const i=this._getOrReturnCtx(e);return k(i,{code:S.invalid_type,expected:A.nan,received:i.parsedType}),R}return{status:"valid",value:e.data}}}ri.create=n=>new ri({typeName:U.ZodNaN,...q(n)});class Si extends ${_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 Nn extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?R:s.status==="dirty"?(t.dirty(),kt(s.value)):this._def.out._parseAsync({data:s.value,path:i.path,parent:i})})();{const o=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?R:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:i.path,parent:i})}}static create(e,t){return new Nn({in:e,out:t,typeName:U.ZodPipeline})}}class Xt extends ${_parse(e){const t=this._def.innerType._parse(e),i=o=>(St(o)&&(o.value=Object.freeze(o.value)),o);return qt(t)?t.then(o=>i(o)):i(t)}unwrap(){return this._def.innerType}}Xt.create=(n,e)=>new Xt({innerType:n,typeName:U.ZodReadonly,...q(e)});function li(n,e={},t){return jt.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 a=Xe.create,x=Nt.create,h=hn.create,ys=$t.create,V=jt.create,ze=mn.create;st.create;const N=Ge.create,_=de.create,Pe=Vt.create,Ct=Sn.create;Zt.create;ut.create;const P=Ht.create,I=Kt.create,b=pt.create,wt=Jt.create;Qt.create;Ye.create;ft.create;const vs=nt.createWithPreprocess,Yr=Object.freeze(Object.defineProperty({__proto__:null,DIRTY:kt,INVALID:R,OK:Fe,ParseStatus:Te,Schema:$,ZodAny:jt,ZodArray:Ge,ZodBigInt:At,ZodBoolean:hn,ZodBranded:Si,ZodCatch:Wt,ZodDate:Bt,ZodDefault:Gt,ZodDiscriminatedUnion:Sn,ZodEffects:nt,ZodEnum:pt,ZodError:et,get ZodFirstPartyTypeKind(){return U},ZodIntersection:Zt,ZodIssueCode:S,ZodLazy:yn,ZodLiteral:Kt,ZodMap:si,ZodNaN:ri,ZodNativeEnum:Jt,ZodNever:st,ZodNull:$t,ZodNullable:ft,ZodNumber:Nt,ZodObject:de,ZodOptional:Ye,ZodParsedType:A,ZodPipeline:Nn,ZodPromise:Qt,ZodReadonly:Xt,ZodRecord:Ht,ZodSchema:$,ZodSet:It,ZodString:Xe,ZodSymbol:ii,ZodTransformer:nt,ZodTuple:ut,ZodType:$,ZodUndefined:gn,ZodUnion:Vt,ZodUnknown:mn,ZodVoid:oi,addIssueToContext:k,any:V,array:N,boolean:h,custom:li,datetimeRegex:gs,defaultErrorMap:fn,discriminatedUnion:Ct,enum:b,getErrorMap:us,getParsedType:at,isAborted:ti,isAsync:qt,isDirty:ni,isValid:St,literal:I,makeIssue:ps,nativeEnum:wt,null:ys,number:x,object:_,get objectUtil(){return ei},preprocess:vs,record:P,string:a,union:Pe,unknown:ze,get util(){return K}},Symbol.toStringTag,{value:"Module"}));Ir(Yr);const Ze=_({created_at:a(),updated_at:a()}),ws=_({id:a(),version:a().optional()}),Ss=_({name:a(),version:a()}),Ns=_({name:a(),value:a().optional()}),bs=_({name:a().max(255),code:a().max(1e5),supported_triggers:N(ws).optional(),runtime:a().max(50).optional(),dependencies:N(Ss).optional(),secrets:N(Ns).optional(),is_system:h().optional(),inherit:h().optional()});bs.partial().extend({status:b(["draft","built"]).optional(),deployed_at:a().optional()});bs.extend({id:a(),tenant_id:a(),status:b(["draft","built"]).default("built"),deployed_at:a().optional(),secrets:N(_({name:a(),value:a().optional()})).optional(),...Ze.shape});const el=a(),tl=b(["unspecified","pending","final","partial","canceled","suspended"]),nl=_({id:a(),msg:a(),url:a().optional()}),il=_({action_name:a(),error:nl.nullable(),started_at:a(),ended_at:a()}),ol=_({level:b(["log","info","warn","error","debug"]),message:a()}),al=N(_({action_name:a(),lines:N(ol)})),sl=_({id:a(),tenant_id:a(),trigger_id:el,status:tl,results:N(il),logs:al.optional(),created_at:a(),updated_at:a()});sl.omit({tenant_id:!0,created_at:!0,updated_at:!0});const rl=_({action_id:a(),code:a().max(1e5),runtime:a().max(50).optional(),dependencies:N(Ss).optional(),secrets:N(Ns).optional(),supported_triggers:N(ws).optional(),deployed:h().default(!0)});rl.extend({id:a(),tenant_id:a(),number:x().int(),...Ze.shape});const ll=b(["user_action","admin_action","system","api"]),dl=_({type:b(["user","admin","system","api_key","client_credentials"]),id:a().optional(),email:a().optional(),org_id:a().optional(),org_name:a().optional(),scopes:N(a()).optional(),client_id:a().optional()}),cl=_({type:a(),id:a(),before:P(ze()).optional(),after:P(ze()).optional(),diff:P(_({old:ze(),new:ze()})).optional()}),_l=_({method:a(),path:a(),query:P(a()).optional(),body:ze().optional(),ip:a(),user_agent:a().optional(),correlation_id:a().optional()}),ul=_({status_code:x(),body:ze().optional()}),pl=_({country_code:a(),city_name:a(),latitude:a(),longitude:a(),time_zone:a(),continent_code:a()}),fl=_({name:a(),version:a(),env:P(a()).optional()}),hl=_({tenant_id:a(),event_type:a(),log_type:a(),description:a().optional(),category:ll,actor:dl,target:cl,request:_l,response:ul.optional(),connection:a().optional(),strategy:a().optional(),strategy_type:a().optional(),audience:a().optional(),scope:a().optional(),location:pl.optional(),auth0_client:fl.optional(),hostname:a(),is_mobile:h().optional(),timestamp:a()});hl.extend({id:a()});b(["AUTH0","EMAIL","REDIRECT"]);b(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]);b(["VERIFY_EMAIL"]);const gl=_({require_mx_record:h().optional(),block_aliases:h().optional(),block_free_emails:h().optional(),block_disposable_emails:h().optional(),blocklist:N(a()).optional(),allowlist:N(a()).optional()}),ml=_({id:a(),alias:a().max(100).optional(),type:I("AUTH0"),action:I("UPDATE_USER"),allow_failure:h().optional(),mask_output:h().optional(),params:_({connection_id:a().optional(),user_id:a(),changes:P(a(),V())})}),yl=_({id:a(),alias:a().max(100).optional(),type:I("EMAIL"),action:I("VERIFY_EMAIL"),allow_failure:h().optional(),mask_output:h().optional(),params:_({email:a(),rules:gl.optional()})}),vl=b(["change-email","account","custom"]),wl=_({id:a(),alias:a().max(100).optional(),type:I("REDIRECT"),action:I("REDIRECT_USER"),allow_failure:h().optional(),mask_output:h().optional(),params:_({target:vl.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:a().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),Sl=Pe([ml,yl,wl]),Nl=_({name:a().min(1).max(150).openapi({description:"The name of the flow"}),actions:N(Sl).optional().default([]).openapi({description:"The list of actions to execute in sequence"})});Nl.extend({...Ze.shape,id:a().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})});_({page:a().min(0).optional().default("0").transform(n=>parseInt(n,10)).openapi({description:"The page number where 0 is the first page"}),per_page:a().min(1).optional().default("10").transform(n=>parseInt(n,10)).openapi({description:"The number of items per page"}),include_totals:a().optional().default("false").transform(n=>n==="true").openapi({description:"If the total number of items should be included in the response"}),sort:a().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:a().optional().openapi({description:"A lucene query string used to filter the results"})});_({start:x(),limit:x(),length:x(),total:x().optional()});const bl=_({email:a().optional(),email_verified:h().optional(),name:a().optional(),username:a().optional(),given_name:a().optional(),phone_number:a().optional(),phone_verified:h().optional(),family_name:a().optional()}).catchall(V()),El=_({connection:a(),user_id:a(),provider:a(),isSocial:h(),email:a().optional(),email_verified:h().optional(),phone_number:a().optional(),phone_verified:h().optional(),username:a().optional(),access_token:a().optional(),access_token_secret:a().optional(),refresh_token:a().optional(),profileData:bl.optional()}),xl=_({formatted:a().optional(),street_address:a().optional(),locality:a().optional(),region:a().optional(),postal_code:a().optional(),country:a().optional()}).optional(),Es=_({email:a().optional().transform(n=>n&&n.toLowerCase()),username:a().refine(n=>!n.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:a().optional(),phone_verified:h().optional(),given_name:a().optional(),family_name:a().optional(),nickname:a().optional(),name:a().optional(),picture:a().optional(),locale:a().optional(),linked_to:a().optional(),profileData:a().optional(),user_id:a().optional(),app_metadata:V().default({}).optional(),user_metadata:V().default({}).optional(),middle_name:a().optional(),preferred_username:a().optional(),profile:a().optional(),website:a().optional(),gender:a().optional(),birthdate:a().optional(),zoneinfo:a().optional(),address:xl}),kl=Es.extend({email_verified:h().default(!1),verify_email:h().optional(),last_ip:a().optional(),last_login:a().optional(),user_id:a().optional(),provider:a().optional(),connection:a(),is_social:h().optional(),registration_completed_at:a().optional(),password:_({hash:a(),algorithm:a()}).optional()}),Ol=_({...kl.omit({password:!0}).shape,...Ze.shape,user_id:a(),provider:a(),is_social:h(),email:a().optional(),login_count:x().default(0),identities:N(El).optional()});Ol.omit({registration_completed_at:!0});Es.extend({login_count:x(),multifactor:N(a()).optional(),last_ip:a().optional(),last_login:a().optional(),user_id:a()}).catchall(V());let Tl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Al=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=Tl[t[n]&63];return e};const Il=_({client_id:a().optional().openapi({description:"ID of this client. Generated server-side if omitted (Auth0 behavior)."}),name:a().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:a().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:a().default(()=>Al()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:b(["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:a().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:N(a()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:N(a()).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:N(a()).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:N(a()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:N(a()).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:N(a()).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:N(a()).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(V()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:P(V()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:N(a()).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(V()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:N(P(V())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:P(V()).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:a().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:a().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:a().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:a().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:P(V()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:b(["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. `none` (public client), `client_secret_post` / `client_secret_basic` (HTTP POST / Basic), `client_secret_jwt` (RFC 7523 HMAC assertion using client_secret), or `private_key_jwt` (RFC 7523 asymmetric assertion verified against the client's `jwks` / `jwks_uri`)."}),client_metadata:P(a().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]'}),hide_sign_up_disabled_error:h().default(!1).optional().openapi({description:"Enumeration-safe variant of the connection-level `disable_signup` flag. When a signup is blocked by the password connection and this is true, the identifier screen does not reveal that an email is unknown — it advances to the OTP/password challenge as if the account existed and fails at credential check. Mitigates email enumeration at the cost of UX: users without an account see a generic credential failure instead of an explicit signup-disabled message."}),mobile:P(V()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:a().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:P(V()).default({}).optional(),refresh_token:_({rotation_type:b(["rotating","non-rotating"]).optional().openapi({description:"Whether refresh tokens for this client are rotated on every exchange (Auth0 'rotating' behavior) or kept stable (legacy non-rotating). Defaults to 'non-rotating' when unset."}),leeway:x().int().min(0).max(600).optional().openapi({description:"Seconds after a parent token's first rotation during which presenting it again still mints a fresh sibling child instead of triggering reuse-detection. Defaults to 30s when unset."}),expiration_type:b(["expiring","non-expiring"]).optional().openapi({description:"Auth0-compatible: whether refresh tokens expire."}),token_lifetime:x().int().min(0).optional().openapi({description:"Auth0-compatible: refresh-token absolute lifetime in seconds."}),infinite_token_lifetime:h().optional().openapi({description:"Auth0-compatible: when true, refresh tokens have no absolute expiry."}),idle_token_lifetime:x().int().min(0).optional().openapi({description:"Auth0-compatible: refresh-token idle (sliding) lifetime in seconds."}),infinite_idle_token_lifetime:h().optional().openapi({description:"Auth0-compatible: when true, refresh tokens have no idle expiry."})}).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:P(V()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:b(["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:b(["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(V()).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(V()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:b(["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:x().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:P(V()).default({}).optional(),owner_user_id:a().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:b(["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(V()).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."}),user_linking_mode:b(["builtin","off"]).optional().openapi({description:"Per-client override for the built-in email-based user-linking path. `builtin` runs the legacy in-process linking at user creation/email update. `off` disables the legacy path; linking only happens if the tenant has enabled the `account-linking` template hook. When unset, the service-level `userLinkingMode` default applies."})});_({created_at:a(),updated_at:a(),...Il.shape,client_id:a()});const Cl=_({client_id:a().min(1).openapi({description:"ID of the client."}),audience:a().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:N(a()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:b(["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:b(["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:N(a()).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."})}),Dl=_({id:a().openapi({description:"ID of the client grant."}),...Cl.shape,created_at:a().optional(),updated_at:a().optional()});N(Dl);const xs=b(["iat","rat"]),Ll=_({id:a(),token_hash:a(),type:xs,client_id:a().optional(),sub:a().optional(),constraints:P(ze()).optional(),single_use:h().default(!1),expires_at:a().optional()});_({created_at:a(),used_at:a().optional(),revoked_at:a().optional(),...Ll.shape});const Dt=_({x:x(),y:x()});var ks=(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))(ks||{}),Os=(n=>(n.BLOCK="BLOCK",n.FIELD="FIELD",n))(Os||{});const bn=_({id:a(),category:wt(Os),type:wt(ks)}),Rl=bn.extend({category:I("BLOCK"),type:I("RICH_TEXT"),config:_({content:a()}).passthrough()}),Ul=bn.extend({category:I("BLOCK"),type:Pe([I("NEXT_BUTTON"),I("BACK_BUTTON"),I("SUBMIT_BUTTON")]),config:_({text:a()}).passthrough()}),zl=bn.extend({category:I("FIELD"),type:I("LEGAL"),required:h().optional(),sensitive:h().optional(),config:_({text:a()}).passthrough()}),Fl=bn.extend({category:I("FIELD"),type:Pe([I("TEXT"),I("EMAIL"),I("PASSWORD"),I("NUMBER"),I("PHONE"),I("DATE"),I("CHECKBOX"),I("RADIO"),I("SELECT"),I("HIDDEN")]),required:h().optional(),sensitive:h().optional(),config:_({label:a().optional(),placeholder:a().optional()}).passthrough()}),Pl=_({id:a(),category:a(),type:a()}).passthrough(),Ml=Pe([Rl,Ul,zl,Fl,Pl]),ql=_({id:a(),type:I("STEP"),coordinates:Dt,alias:a().optional(),config:_({components:N(Ml),next_node:a()}).passthrough()}),Bl=_({id:a(),type:I("FLOW"),coordinates:Dt,alias:a().optional(),config:_({flow_id:a(),next_node:a()})}),$l=_({id:a(),type:I("ACTION"),coordinates:Dt,alias:a().optional(),config:_({action_type:b(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:b(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:a().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:a().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),jl=_({id:a(),type:a(),coordinates:Dt}).passthrough(),Vl=Pe([ql,Bl,$l,jl]),Zl=_({next_node:a(),coordinates:Dt}).passthrough(),Hl=_({resume_flow:h().optional(),coordinates:Dt}).passthrough(),Kl=_({id:a(),name:a(),languages:_({primary:a()}).passthrough(),nodes:N(Vl),start:Zl,ending:Hl,created_at:a(),updated_at:a(),links:_({sdkSrc:a().optional(),sdk_src:a().optional()}).passthrough()}).passthrough();Kl.omit({id:!0,created_at:!0,updated_at:!0});var Ts=(n=>(n.TOKEN="token",n.ID_TOKEN="id_token",n.TOKEN_ID_TOKEN="id_token token",n.CODE="code",n.CODE_ID_TOKEN="code id_token",n.CODE_TOKEN="code token",n.CODE_ID_TOKEN_TOKEN="code id_token token",n))(Ts||{}),As=(n=>(n.QUERY="query",n.FRAGMENT="fragment",n.FORM_POST="form_post",n.WEB_MESSAGE="web_message",n.SAML_POST="saml_post",n))(As||{}),Is=(n=>(n.S256="S256",n.Plain="plain",n))(Is||{});const Ii=Pe([ys(),_({essential:h().optional(),value:ze().optional(),values:N(ze()).optional()})]).nullable(),Jl=_({userinfo:P(a(),Ii).optional(),id_token:P(a(),Ii).optional()}),Ql=_({client_id:a(),act_as:a().optional(),response_type:wt(Ts).optional(),response_mode:wt(As).optional(),redirect_uri:a().optional(),audience:a().optional(),organization:a().optional(),state:a().optional(),nonce:a().optional(),scope:a().optional(),prompt:a().optional(),code_challenge_method:wt(Is).optional(),code_challenge:a().optional(),username:a().optional(),ui_locales:a().optional(),max_age:x().optional(),acr_values:a().optional(),claims:Jl.optional(),vendor_id:a().optional()});_({colors:_({primary:a(),page_background:Pe([a(),_({type:a().optional(),start:a().optional(),end:a().optional(),angle_deg:x().optional()})]).optional()}).optional(),logo_url:a().optional(),favicon_url:a().optional(),powered_by_logo_url:a().optional(),font:_({url:a()}).optional(),dark_mode:b(["dark","light","auto"]).optional()});const Gl=b(["password_reset","email_verification","otp","mfa_otp","authorization_code","oauth2_state","ticket"]),Wl=_({code_id:a().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:a().openapi({description:"The id of the login session that the code is connected to"}),connection_id:a().optional().openapi({description:"The connection that the code is connected to"}),code_type:Gl,code_verifier:a().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:a().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:b(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:a().optional().openapi({description:"The redirect URI associated with the code"}),otp:a().optional().openapi({description:"The one-time password value for OTP-based flows"}),nonce:a().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:a().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:a(),used_at:a().optional(),user_id:a().optional()});_({...Wl.shape,created_at:a()});const Xl=_({kid:a().optional(),team_id:a().optional(),realms:a().optional(),authentication_method:a().optional(),client_id:a().optional(),client_secret:a().optional(),app_secret:a().optional(),scope:a().optional(),authorization_endpoint:a().optional(),token_endpoint:a().optional(),userinfo_endpoint:a().optional(),jwks_uri:a().optional(),discovery_url:a().optional(),issuer:a().optional(),token_endpoint_auth_method:b(["client_secret_basic","client_secret_post"]).optional(),provider:a().optional(),from:a().optional(),twilio_sid:a().optional(),twilio_token:a().optional(),icon_url:a().optional(),domain_aliases:N(a()).optional(),callback_url:a().url().optional(),passwordPolicy:b(["none","low","fair","good","excellent"]).optional(),password_complexity_options:_({min_length:x().optional()}).optional(),password_history:_({enable:h().optional(),size:x().optional()}).optional(),password_no_personal_info:_({enable:h().optional()}).optional(),password_dictionary:_({enable:h().optional(),dictionary:N(a()).optional()}).optional(),disable_signup:h().optional(),brute_force_protection:h().optional(),import_mode:h().optional(),configuration:_({token_endpoint:a().optional(),userinfo_endpoint:a().optional(),client_id:a().optional(),client_secret:a().optional(),realm:a().optional()}).optional(),attributes:_({email:_({identifier:_({active:h().optional()}).optional(),signup:_({status:b(["required","optional","disabled"]).optional(),verification:_({active:h().optional()}).optional()}).optional(),validation:_({allowed:h().optional()}).optional(),unique:h().optional(),profile_required:h().optional(),verification_method:b(["link","code"]).optional()}).optional(),username:_({identifier:_({active:h().optional()}).optional(),signup:_({status:b(["required","optional","disabled"]).optional()}).optional(),validation:_({max_length:x().optional(),min_length:x().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:b(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:_({password:_({enabled:h().optional()}).optional(),passkey:_({enabled:h().optional()}).optional()}).optional(),passkey_options:_({challenge_ui:b(["both","autofill","button"]).optional(),local_enrollment_enabled:h().optional(),progressive_enrollment_enabled:h().optional()}).optional(),requires_username:h().optional(),validation:_({username:_({min:x().optional(),max:x().optional()}).optional()}).optional(),set_user_root_attributes:b(["on_each_login","on_first_login","never_on_login"]).optional()});function di(n){if(n!==null){if(Array.isArray(n))return n.filter(e=>e!==null).map(di);if(n&&typeof n=="object"){const e={};for(const[t,i]of Object.entries(n))i!==null&&(e[t]=di(i));return e}return n}}const Yl=_({id:a().optional(),name:a(),display_name:a().optional(),strategy:a(),options:vs(n=>n===null?{}:di(n),Xl).default({}),enabled_clients:N(a()).default([]).optional(),response_type:li().optional(),response_mode:li().optional(),is_domain_connection:h().optional(),show_as_button:h().optional(),metadata:P(V()).optional(),is_system:h().optional()});_({id:a(),created_at:a().transform(n=>n===null?"":n),updated_at:a().transform(n=>n===null?"":n)}).extend(Yl.shape);const ed=_({domain:a(),custom_domain_id:a().optional(),type:b(["auth0_managed_certs","self_managed_certs"]),verification_method:b(["txt"]).optional(),tls_policy:b(["recommended"]).optional(),custom_client_ip_header:b(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:P(a().max(255)).optional()}),td=Ct("name",[_({name:I("txt"),record:a(),domain:a()}),_({name:I("http"),http_body:a(),http_url:a()})]),nd=_({...ed.shape,custom_domain_id:a(),primary:h(),status:b(["disabled","pending","pending_verification","ready"]),origin_domain_name:a().optional(),verification:_({methods:N(td)}).optional(),tls_policy:a().optional()});nd.extend({tenant_id:a()});const Ni=_({id:a(),order:x().optional(),visible:h().optional().default(!0)}),ht=Ni.extend({category:I("BLOCK").optional()}),id=ht.extend({type:I("DIVIDER"),config:_({text:a().optional()}).optional()}),od=ht.extend({type:I("HTML"),config:_({content:a().optional()}).optional()}),ad=ht.extend({type:I("IMAGE"),config:_({src:a().optional(),alt:a().optional(),width:x().optional(),height:x().optional()}).optional()}),sd=ht.extend({type:I("JUMP_BUTTON"),config:_({text:a().optional(),target_step:a().optional()})}),rd=ht.extend({type:I("RESEND_BUTTON"),config:_({text:a().optional(),resend_action:a().optional()})}),ld=ht.extend({type:I("NEXT_BUTTON"),config:_({text:a().optional()})}),dd=ht.extend({type:I("PREVIOUS_BUTTON"),config:_({text:a().optional()})}),cd=ht.extend({type:I("RICH_TEXT"),config:_({content:a().optional()}).optional()}),bi=Ni.extend({category:I("WIDGET").optional(),label:a().min(1).optional(),hint:a().min(1).max(500).optional(),required:h().optional(),sensitive:h().optional()}),_d=bi.extend({type:I("AUTH0_VERIFIABLE_CREDENTIALS"),config:_({credential_type:a().optional()})}),ud=bi.extend({type:I("GMAPS_ADDRESS"),config:_({api_key:a().optional()})}),pd=bi.extend({type:I("RECAPTCHA"),config:_({site_key:a().optional()})}),be=Ni.extend({category:I("FIELD").optional(),label:a().min(1).optional(),hint:a().min(1).max(500).optional(),messages:N(_({id:x().optional(),text:a(),type:b(["info","error","success","warning"])})).optional(),required:h().optional(),sensitive:h().optional()}),fd=be.extend({type:I("BOOLEAN"),config:_({default_value:h().optional()}).optional()}),hd=be.extend({type:I("CARDS"),config:_({options:N(_({value:a(),label:a(),description:a().optional(),image:a().optional()})).optional(),multi_select:h().optional()}).optional()}),gd=be.extend({type:I("CHOICE"),config:_({options:N(_({value:a(),label:a()})).optional(),display:b(["radio","checkbox"]).optional(),multiple:h().optional(),default_value:Pe([a(),N(a())]).optional()}).optional()}),md=be.extend({type:I("CUSTOM"),config:_({component:a().optional(),props:P(V()).optional(),schema:P(V()).optional(),code:a().optional()})}),yd=be.extend({type:I("DATE"),config:_({format:a().optional(),min:a().optional(),max:a().optional(),default_value:a().optional()}).optional()}),vd=be.extend({type:I("DROPDOWN"),config:_({options:N(_({value:a(),label:a()})).optional(),placeholder:a().optional(),searchable:h().optional(),multiple:h().optional(),default_value:Pe([a(),N(a())]).optional()}).optional()}),wd=be.extend({type:I("EMAIL"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Sd=be.extend({type:I("FILE"),config:_({accept:a().optional(),max_size:x().optional(),multiple:h().optional()}).optional()}),Nd=be.extend({type:I("LEGAL"),config:_({text:a(),html:h().optional()}).optional()}),bd=be.extend({type:I("NUMBER"),config:_({placeholder:a().optional(),min:x().optional(),max:x().optional(),step:x().optional(),default_value:a().optional()}).optional()}),Ed=be.extend({type:I("PASSWORD"),config:_({placeholder:a().optional(),min_length:x().optional(),show_toggle:h().optional(),forgot_password_link:a().optional(),default_value:a().optional()}).optional()}),xd=be.extend({type:I("PAYMENT"),config:_({provider:a().optional(),currency:a().optional()}).optional()}),kd=be.extend({type:I("SOCIAL"),config:_({providers:N(a()).optional(),provider_details:N(_({name:a(),strategy:a().optional(),display_name:a().optional(),icon_url:a().optional(),href:a().optional()})).optional()}).optional()}),Od=be.extend({type:I("TEL"),config:_({placeholder:a().optional(),default_country:a().optional(),default_value:a().optional(),allow_email:h().optional()}).optional()}),Td=be.extend({type:I("TEXT"),config:_({placeholder:a().optional(),multiline:h().optional(),max_length:x().optional(),default_value:a().optional()}).optional()}),Ad=be.extend({type:I("COUNTRY"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Id=be.extend({type:I("URL"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Cd=Ct("type",[id,od,ad,sd,rd,ld,dd,cd]),Dd=Ct("type",[_d,ud,pd]),Ld=Ct("type",[fd,hd,gd,Ad,md,yd,vd,wd,Sd,Nd,bd,Ed,xd,kd,Od,Td,Id]),Cs=Pe([Cd,Dd,Ld]);_({id:a(),type:I("submit"),label:a(),className:a().optional(),disabled:h().optional().default(!1),order:x().optional(),visible:h().optional().default(!0),customizations:P(a(),V()).optional()});const Yt=_({x:x(),y:x()}),Rd=_({id:a(),type:I("FLOW"),coordinates:Yt,alias:a().min(1).max(150).optional(),config:_({flow_id:a().max(30),next_node:a().optional()})}),Ud=_({id:a(),type:I("ROUTER"),coordinates:Yt,alias:a().min(1).max(150),config:_({rules:N(_({id:a(),alias:a().min(1).max(150).optional(),condition:V(),next_node:a()})),fallback:a()})}),zd=_({id:a(),type:I("STEP"),coordinates:Yt,alias:a().min(1).max(150).optional(),config:_({components:N(Cs),next_node:a().optional()})}),Fd=Ct("type",[Rd,Ud,zd]),Pd=_({name:a().openapi({description:"The name of the form"}),messages:_({errors:P(a(),V()).optional(),custom:P(a(),V()).optional()}).optional(),languages:_({primary:a().optional(),default:a().optional()}).optional(),translations:P(a(),V()).optional(),nodes:N(Fd).optional(),start:_({hidden_fields:N(_({key:a(),value:a()})).optional(),next_node:a().optional(),coordinates:Yt.optional()}).optional(),ending:_({redirection:_({delay:x().optional(),target:a().optional()}).optional(),after_submit:_({flow_id:a().optional()}).optional(),coordinates:Yt.optional(),resume_flow:h().optional()}).optional(),style:_({css:a().optional()}).optional(),links:_({sdkSrc:a().optional(),sdk_src:a().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"});_({...Ze.shape,...Pd.shape,id:a()});const Md=_({id:x().optional(),text:a(),type:b(["info","error","success","warning"])}),qd=_({id:a().optional(),text:a(),href:a(),linkText:a().optional()});_({name:a().optional(),action:a(),method:b(["POST","GET"]),title:a().optional(),description:a().optional(),components:N(Cs),messages:N(Md).optional(),links:N(qd).optional(),footer:a().optional()});const Ds=b(["pre-user-registration","post-user-registration","post-user-login","post-user-update","validate-registration-username","pre-user-deletion","post-user-deletion"]),Ls=b(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Rs=b(["post-user-login","post-user-registration","post-user-update","credentials-exchange"]),Us=b(["post-user-login","credentials-exchange","pre-user-registration","post-user-registration"]),zs=b(["ensure-username","set-preferred-username","account-linking"]),gt={enabled:h().default(!1),synchronous:h().default(!1),priority:x().optional(),hook_id:a().optional(),metadata:P(ze()).optional()},Bd=_({...gt,trigger_id:Ds,url:a()}),$d=_({...gt,trigger_id:Ls,form_id:a()}),jd=_({...gt,trigger_id:Rs,template_id:zs}),Vd=_({...gt,trigger_id:Us,code_id:a()});Pe([Bd,$d,jd,Vd]);const Zd=_({...gt,trigger_id:Ds,...Ze.shape,hook_id:a(),url:a()}),Hd=_({...gt,trigger_id:Ls,...Ze.shape,hook_id:a(),form_id:a()}),Kd=_({...gt,trigger_id:Rs,...Ze.shape,hook_id:a(),template_id:zs}),Jd=_({...gt,trigger_id:Us,...Ze.shape,hook_id:a(),code_id:a()});Pe([Zd,Hd,Kd,Jd]);const Qd=_({code:a().max(1e5),secrets:P(a()).optional()});Qd.extend({id:a(),tenant_id:a(),...Ze.shape});const Gd=_({name:a().optional()}),Wd=_({email:a().optional()}),Xd=_({organization_id:a().max(50),inviter:Gd,invitee:Wd,invitation_url:a().url(),client_id:a(),connection_id:a().optional(),app_metadata:P(V()).default({}).optional(),user_metadata:P(V()).default({}).optional(),ttl_sec:x().int().max(2592e3).default(604800).optional(),roles:N(a()).default([]).optional(),send_invitation_email:h().default(!0).optional()});_({id:a(),organization_id:a().max(50),created_at:a().datetime(),expires_at:a().datetime(),ticket_id:a().optional()}).extend(Xd.shape);const Yd=_({alg:b(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),kid:a(),kty:b(["RSA","EC","oct"]),use:b(["sig","enc"]).optional(),n:a().optional(),e:a().optional(),crv:a().optional(),x:a().optional(),y:a().optional(),x5t:a().optional(),x5c:N(a()).optional()}).superRefine((n,e)=>{if(n.kty==="RSA")for(const t of["n","e"])n[t]||e.addIssue({code:S.custom,path:[t],message:`RSA JWK is missing required member '${t}'`});else if(n.kty==="EC")for(const t of["crv","x","y"])n[t]||e.addIssue({code:S.custom,path:[t],message:`EC JWK is missing required member '${t}'`})});_({keys:N(Yd)});_({issuer:a(),authorization_endpoint:a(),token_endpoint:a(),userinfo_endpoint:a(),jwks_uri:a(),registration_endpoint:a().optional(),revocation_endpoint:a(),end_session_endpoint:a().optional(),scopes_supported:N(a()),response_types_supported:N(a()),grant_types_supported:N(a()).optional(),code_challenge_methods_supported:N(a()),response_modes_supported:N(a()),subject_types_supported:N(a()),id_token_signing_alg_values_supported:N(a()),token_endpoint_auth_methods_supported:N(a()),claims_supported:N(a()),request_uri_parameter_supported:h(),request_parameter_supported:h(),claims_parameter_supported:h().optional(),request_object_signing_alg_values_supported:N(a()).optional(),token_endpoint_auth_signing_alg_values_supported:N(a())});var Fs=(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))(Fs||{});const ec=wt(Fs),tc=_({strategy:a(),strategy_type:a()}),nc=_({csrf_token:a(),auth0Client:a().optional(),authParams:Ql,expires_at:a(),deleted_at:a().optional(),ip:a().optional(),useragent:a().optional(),session_id:a().optional(),authorization_url:a().optional(),state:ec.optional().default("pending"),state_data:a().optional(),failure_reason:a().optional(),user_id:a().optional(),auth_connection:a().optional(),auth_strategy:tc.optional(),authenticated_at:a().optional()}).openapi({description:"This represents a login sesion"});_({...nc.shape,id:a().openapi({description:"This is is used as the state in the universal login"}),created_at:a(),updated_at:a()});const ic={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_HOOK:"sh",SUCCESS_PASSWORD_MIGRATION:"spm",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"},oc=a().refine(n=>Object.values(ic).includes(n),{message:"Invalid log type"}),ac=_({name:a(),version:a(),env:_({node:a().optional()}).optional()}),sc=_({country_code:a().length(2),city_name:a(),latitude:a(),longitude:a(),time_zone:a(),continent_code:a()}),rc=_({type:oc,date:a(),description:a().optional(),ip:a().optional(),user_agent:a().optional(),details:V().optional(),isMobile:h(),user_id:a().optional(),user_name:a().optional(),connection:a().optional(),connection_id:a().optional(),client_id:a().optional(),client_name:a().optional(),audience:a().optional(),scope:a().optional(),strategy:a().optional(),strategy_type:a().optional(),hostname:a().optional(),auth0_client:ac.optional(),log_id:a().optional(),location_info:sc.optional()});_({...rc.shape,log_id:a()});const lc=b(["http","eventbridge","eventgrid","splunk","datadog","sumo"]),Ps=b(["active","paused","suspended"]),dc=_({type:a(),name:a()}),cc=_({name:a(),type:lc,status:Ps.optional(),sink:P(a(),ze()),filters:N(dc).optional(),isPriority:h().optional()});cc.extend({id:a(),status:Ps,created_at:a().optional(),updated_at:a().optional()});const _c=b(["auth0","cognito","okta","oidc"]),uc=_({domain:a(),client_id:a(),client_secret:a(),audience:a().optional(),scope:a().optional()}),pc=_({id:a().optional(),name:a(),provider:_c,connection:a(),enabled:h().default(!0),credentials:uc});_({id:a(),created_at:a(),updated_at:a()}).extend(pc.shape);const fc=_({enabled:h().optional(),shields:N(a()).optional(),admin_notification_frequency:N(a()).optional(),method:a().optional(),stage:_({"pre-user-registration":_({shields:N(a()).optional()}).optional(),"pre-change-password":_({shields:N(a()).optional()}).optional()}).optional()}),hc=_({enabled:h().optional(),shields:N(a()).optional(),allowlist:N(a()).optional(),mode:a().optional(),max_attempts:x().optional()}),gc=_({enabled:h().optional(),shields:N(a()).optional(),allowlist:N(a()).optional(),stage:_({"pre-login":_({max_attempts:x().optional(),rate:x().optional()}).optional(),"pre-user-registration":_({max_attempts:x().optional(),rate:x().optional()}).optional()}).optional()}),mc=_({breached_password_detection:fc.optional(),brute_force_protection:hc.optional(),suspicious_ip_throttling:gc.optional()}),yc=_({id:a().optional(),user_id:a(),password:a(),algorithm:b(["bcrypt","argon2id"]).default("argon2id"),is_current:h().default(!0)});yc.extend({id:a(),created_at:a(),updated_at:a()});const Ms=_({initial_user_agent:a().describe("First user agent of the device from which this user logged in"),initial_ip:a().describe("First IP address associated with this session"),initial_asn:a().describe("First autonomous system number associated with this session"),last_user_agent:a().describe("Last user agent of the device from which this user logged in"),last_ip:a().describe("Last IP address from which this user logged in"),last_asn:a().describe("Last autonomous system number from which this user logged in")}),vc=_({id:a(),revoked_at:a().optional(),used_at:a().optional(),user_id:a().describe("The user ID associated with the session"),expires_at:a().optional(),login_session_id:a(),idle_expires_at:a().optional(),device:Ms.describe("Metadata related to the device used in the session"),clients:N(a()).describe("List of client details for the session")});_({created_at:a(),updated_at:a(),authenticated_at:a(),last_interaction_at:a(),...vc.shape});_({kid:a().openapi({description:"The key id of the signing key"}),tenant_id:a().optional().openapi({description:"The tenant the key belongs to. Omitted means the key is shared / control-plane scoped."}),cert:a().openapi({description:"The public certificate of the signing key"}),fingerprint:a().openapi({description:"The cert fingerprint"}),thumbprint:a().openapi({description:"The cert thumbprint"}),pkcs7:a().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:a().optional().openapi({description:"The date and time when the key became the current key"}),current_until:a().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:a().optional().openapi({description:"The date and time when the key was revoked"}),connection:a().optional().openapi({description:"The connection identifier associated with the key"}),type:b(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})});const wc=_({id:a().optional(),audience:a(),friendly_name:a(),picture_url:a().optional(),support_email:a().optional(),support_url:a().optional(),sender_email:a().email(),sender_name:a(),session_lifetime:x().optional(),idle_session_lifetime:x().optional(),ephemeral_session_lifetime:x().optional(),idle_ephemeral_session_lifetime:x().optional(),session_cookie:_({mode:b(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:N(a()).optional(),default_redirection_uri:a().optional(),default_client_id:a().optional(),enabled_locales:N(a()).optional(),default_directory:a().optional(),error_page:_({html:a().optional(),show_log_link:h().optional(),url:a().optional()}).nullish(),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:N(a()).optional(),allow_http_return_to:N(a().refine(n=>{try{const e=new URL(n);return e.protocol==="http:"&&(e.pathname===""||e.pathname==="/")&&!e.search&&!e.hash&&n===e.origin}catch{return!1}},{message:"must be a fully-qualified http origin (scheme + host + port, no path)"})).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:a().optional(),legacy_sandbox_version:a().optional(),sandbox_versions_available:N(a()).optional(),change_password:_({enabled:h().optional(),html:a().optional()}).optional(),guardian_mfa_page:_({enabled:h().optional(),html:a().optional()}).optional(),device_flow:_({charset:b(["base20","digits"]).optional(),mask:a().max(20).optional()}).optional(),default_token_quota:_({clients:_({client_credentials:P(V()).optional()}).optional(),organizations:_({client_credentials:P(V()).optional()}).optional()}).nullish(),default_audience:a().optional(),default_organization:a().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:N(a()).optional(),mtls:_({enable_endpoint_aliases:h().optional()}).nullish(),pushed_authorization_requests_supported:h().optional(),authorization_response_iss_parameter_supported:h().optional(),attack_protection:mc.optional(),mfa:_({policy:b(["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:b(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:_({sid:a().optional(),auth_token:a().optional(),from:a().optional(),messaging_service_sid:a().optional()}).optional(),phone_message:_({message:a().optional()}).optional()}).optional()});_({created_at:a().nullable().transform(n=>n??""),updated_at:a().nullable().transform(n=>n??""),...wc.shape,id:a(),is_control_plane:h().optional()});_({access_token:a(),id_token:a().optional(),scope:a().optional(),state:a().optional(),refresh_token:a().optional(),token_type:a(),expires_in:x()});_({code:a(),state:a().optional()});const Sc=_({button_border_radius:x(),button_border_weight:x(),buttons_style:b(["pill","rounded","sharp"]),input_border_radius:x(),input_border_weight:x(),inputs_style:b(["pill","rounded","sharp"]),show_widget_shadow:h(),widget_border_weight:x(),widget_corner_radius:x()}),Nc=_({base_focus_color:a(),base_hover_color:a(),body_text:a(),captcha_widget_theme:b(["auto","dark","light"]),error:a(),header:a(),icons:a(),input_background:a(),input_border:a(),input_filled_text:a(),input_labels_placeholders:a(),links_focused_components:a(),primary_button:a(),primary_button_label:a(),secondary_button_border:a(),secondary_button_label:a(),success:a(),widget_background:a(),widget_border:a()}),bt=_({bold:h(),size:x()}),bc=_({body_text:bt,buttons_text:bt,font_url:a(),input_labels:bt,links:bt,links_style:b(["normal","underlined"]),reference_text_size:x(),subtitle:bt,title:bt}),Ec=_({background_color:a(),background_image_url:a(),page_layout:b(["center","left","right"]),logo_placement:b(["widget","chip","none"]).optional()}),xc=_({header_text_alignment:b(["center","left","right"]),logo_height:x(),logo_position:b(["center","left","none","right"]),logo_url:a(),social_buttons_layout:b(["bottom","top"])}),kc=_({borders:Sc,colors:Nc,displayName:a(),fonts:bc,page_background:Ec,widget:xc});kc.extend({themeId:a()});_({universal_login_experience:b(["new","classic"]).default("new"),identifier_first:h().default(!0),password_first:h().default(!1),webauthn_platform_first_factor:h()});_({name:a(),enabled:h().optional().default(!0),default_from_address:a().optional(),credentials:P(a(),ze()),settings:_({}).optional()});const Oc=b(["verify_email","verify_email_by_code","reset_email","reset_email_by_code","welcome_email","blocked_account","stolen_credentials","enrollment_email","mfa_oob_code","change_password","password_reset","user_invitation"]);_({template:Oc,body:a(),from:a(),subject:a(),syntax:I("liquid").default("liquid"),resultUrl:a().optional(),urlLifetimeInSeconds:x().int().nonnegative().optional(),includeEmailInRedirect:h().default(!1),enabled:h().default(!0)});const Tc=_({id:a(),login_id:a(),user_id:a(),client_id:a(),expires_at:a().optional(),idle_expires_at:a().optional(),last_exchanged_at:a().optional(),device:Ms,resource_servers:N(_({audience:a(),scopes:a()})),rotating:h(),token_lookup:a().optional(),token_hash:a().optional(),family_id:a().optional(),rotated_to:a().optional(),rotated_at:a().optional()});_({created_at:a(),revoked_at:a().optional(),...Tc.shape});_({to:a(),message:a()});_({name:a(),options:_({})});const Ac=_({value:a(),description:a().optional()}),Ic=_({token_dialect:b(["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()}),Cc=_({id:a().optional(),name:a(),identifier:a(),scopes:N(Ac).optional(),signing_alg:a().optional(),signing_secret:a().optional(),token_lifetime:x().default(86400),token_lifetime_for_web:x().default(7200),skip_consent_for_verifiable_first_party_clients:h().optional(),allow_offline_access:h().optional(),verificationKey:a().optional(),options:Ic.optional(),is_system:h().optional(),metadata:P(V()).optional()}),Dc=_({...Cc.shape,created_at:a().optional(),updated_at:a().optional()});N(Dc);const Lc=_({role_id:a(),resource_server_identifier:a(),permission_name:a()}),Rc=_({...Lc.shape,created_at:a()});N(Rc);const Uc=_({user_id:a(),resource_server_identifier:a(),permission_name:a(),organization_id:a().optional()}),zc=_({...Uc.shape,tenant_id:a(),created_at:a().optional()});N(zc);const Fc=_({user_id:a(),resource_server_identifier:a(),resource_server_name:a(),permission_name:a(),description:a().nullable().optional(),created_at:a().optional(),organization_id:a().optional()});N(Fc);const Pc=_({user_id:a(),role_id:a(),organization_id:a().optional()}),Mc=_({...Pc.shape,tenant_id:a(),created_at:a().optional()});N(Mc);const qc=_({id:a().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:a().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:a().max(255).optional().openapi({description:"The description of the role"}),is_system:h().optional(),metadata:P(V()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})}),Bc=qc.extend({id:a().openapi({description:"The unique identifier of the role"}),created_at:a().optional(),updated_at:a().optional()});N(Bc);const $c=_({logo_url:a().optional().openapi({description:"URL of the organization's logo"}),colors:_({primary:a().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:a().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),jc=_({connection_id:a().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"})}),Vc=_({client_credentials:_({enforce:h().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:x().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:x().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),Zc=_({id:a().optional(),name:a().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:a().optional().openapi({description:"The display name of the organization"}),branding:$c,metadata:P(V()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:N(jc).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Vc});_({...Zc.shape,...Ze.shape,id:a(),name:a().min(1).openapi({description:"The name of the organization"})});const Hc=_({connection_id:a().openapi({description:"ID of the tenant-level connection to enable for the org."}),assign_membership_on_login:h().optional().default(!1),show_as_button:h().optional().default(!0),is_signup_enabled:h().optional().default(!0)}),Kc=_({...Hc.shape,connection:_({name:a().optional(),strategy:a().optional()}).optional(),created_at:a().optional(),updated_at:a().optional()});N(Kc);const Jc=_({user_id:a().openapi({description:"ID of the user"}),organization_id:a().openapi({description:"ID of the organization"})});_({...Jc.shape,...Ze.shape,id:a()});_({idle_session_lifetime:x().default(72),session_lifetime:x().default(168),session_cookie:_({mode:b(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:h().optional(),default_redirection_uri:a().optional(),enabled_locales:N(a()).optional(),default_directory:a().optional(),error_page:_({html:a().optional(),show_log_link:h().optional(),url:a().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:a().optional(),picture_url:a().optional(),support_email:a().optional(),support_url:a().optional(),sandbox_version:a().optional(),sandbox_versions_available:N(a()).optional(),change_password:_({enabled:h(),html:a()}).optional(),guardian_mfa_page:_({enabled:h(),html:a()}).optional(),default_audience:a().optional(),default_organization:a().optional(),sessions:_({oidc_logout_prompt_enabled:h().optional()}).optional(),mfa:_({policy:b(["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:b(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:_({sid:a().optional(),auth_token:a().optional(),from:a().optional(),messaging_service_sid:a().optional()}).optional(),phone_message:_({message:a().optional()}).optional()}).optional()});_({date:a().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:x().openapi({description:"Number of logins on this date",example:150}),signups:x().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:x().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:a().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:a().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})});x().openapi({description:"Number of active users in the last 30 days",example:1234});b(["active-users","logins","signups","refresh-tokens","sessions"]);b(["hour","day","week","month"]);b(["time","connection","client_id","user_type","event"]);b(["password","social","passwordless","enterprise"]);const Qc=_({name:a(),type:a()}),Gc=_({elapsed:x(),rows_read:x().optional(),bytes_read:x().optional()});_({meta:N(Qc),data:N(P(a(),V())),rows:x(),rows_before_limit_at_least:x().optional(),statistics:Gc.optional()});const Wc=b(["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"]),Xc=P(a(),P(a(),a())).openapi({type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}});_({prompt:Wc,language:a(),custom_text:Xc});const Yc=b(["phone","totp","email","push","webauthn-roaming","webauthn-platform","passkey"]),qs=_({user_id:a(),type:Yc,phone_number:a().optional(),totp_secret:a().optional(),credential_id:a().optional(),public_key:a().optional(),sign_count:x().int().nonnegative().optional(),credential_backed_up:h().optional(),transports:N(a()).optional(),friendly_name:a().optional(),confirmed:h().default(!1)});function Bs(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"]}))}qs.superRefine(Bs);_({...qs.shape,id:a(),created_at:a(),updated_at:a()}).superRefine(Bs);function e_(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function t_(n){if(!n)return;const e=JSON.parse(n);return e_(e)?e:void 0}function Un(n){return n==null?void 0:new Date(n).toISOString()}function an(n){if(!n)return null;const e=new Date(n);return isNaN(e.getTime())?null:e.getTime()}function zn(n){const e=xs.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:t_(n.constraints),single_use:!!n.single_use,expires_at:Un(n.expires_at_ts),used_at:Un(n.used_at_ts),revoked_at:Un(n.revoked_at_ts),created_at:new Date(n.created_at_ts).toISOString()}}function n_(n){return{async create(e,t){const i=Date.now();return await n.insert(X).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:an(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(X).where(g(c(X.tenant_id,e),c(X.id,t))).get();return i?zn(i):null},async getByHash(e,t){const i=await n.select().from(X).where(g(c(X.tenant_id,e),c(X.token_hash,t))).get();return i?zn(i):null},async listByClient(e,t){return(await n.select().from(X).where(g(c(X.tenant_id,e),c(X.client_id,t))).orderBy(se(X.created_at_ts))).map(zn)},async markUsed(e,t,i){return(await n.update(X).set({used_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.id,t),Ce(X.used_at_ts))).returning()).length>0},async revoke(e,t,i){return(await n.update(X).set({revoked_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.id,t),Ce(X.revoked_at_ts))).returning()).length>0},async revokeByClient(e,t,i){return(await n.update(X).set({revoked_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.client_id,t),Ce(X.revoked_at_ts))).returning()).length},async remove(e,t){return(await n.delete(X).where(g(c(X.tenant_id,e),c(X.id,t))).returning()).length>0}}}function Fn(n){const{tenant_id:e,...t}=n;return Q(t)}function i_(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),Fn(i)},async get(e,t,i){if(!e)throw new Error("tenant_id is required");const o=await n.select().from(re).where(g(c(re.tenant_id,e),c(re.code_id,t),c(re.code_type,i))).get();return o?Fn(o):null},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(re).where(c(re.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=re[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(Fn);if(!s)return{codes:f};const[p]=await n.select({count:ge()}).from(re).where(c(re.tenant_id,e));return{codes:f,start:i*o,limit:o,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),Ce(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 o_(){const{customAlphabet:n}=require("nanoid");return`con_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Pn(n){const{tenant_id:e,is_system:t,options:i,metadata:o,...s}=n;return Q({...s,options:F(i,{}),metadata:F(o),is_system:t?!0:void 0})}function a_(n){return{async create(e,t){var s,l;const i=new Date().toISOString(),o={id:t.id||o_(),...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(o)}catch(d){throw(s=d==null?void 0:d.message)!=null&&s.includes("UNIQUE constraint failed")||(l=d==null?void 0:d.message)!=null&&l.includes("duplicate key")?new _t(409,{message:"Connection already exists"}):d}return Pn(o)},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?Pn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.strategy!==void 0&&(o.strategy=i.strategy),i.options!==void 0&&(o.options=JSON.stringify(i.options)),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.display_name!==void 0&&(o.display_name=i.display_name),i.response_type!==void 0&&(o.response_type=i.response_type),i.response_mode!==void 0&&(o.response_mode=i.response_mode),await n.update(pe).set(o).where(g(c(pe.tenant_id,e),c(pe.id,t))),!0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=c(pe.tenant_id,e);if(d){const E=We(pe,d,["name"]);E&&(u=g(u,E))}let f=n.select().from(pe).where(u).$dynamic();if(l!=null&&l.sort_by){const E=pe[l.sort_by];E&&(f=f.orderBy(l.sort_order==="desc"?se(E):he(E)))}const m=(await f.offset(i*o).limit(o)).map(Pn);if(!s)return{connections:m};const[y]=await n.select({count:ge()}).from(pe).where(u);return{connections:m,start:i*o,limit:o,length:Number((y==null?void 0:y.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 sn(n){const{tenant_id:e,domain_metadata:t,...i}=n;return Q({...i,primary:!!i.primary,domain_metadata:F(t)})}function s_(n){return{async create(e,t){const i=new Date().toISOString(),s={custom_domain_id:t.custom_domain_id||Le(),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(Ie).values(s),sn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(Ie).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).get();return i?sn(i):null},async getByDomain(e){const t=await n.select().from(Ie).where(c(Ie.domain,e)).get();return t?{...sn(t),tenant_id:t.tenant_id}:null},async list(e){return(await n.select().from(Ie).where(c(Ie.tenant_id,e)).all()).map(sn)},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.domain!==void 0&&(o.domain=i.domain),i.primary!==void 0&&(o.primary=i.primary),i.status!==void 0&&(o.status=i.status),i.type!==void 0&&(o.type=i.type),i.origin_domain_name!==void 0&&(o.origin_domain_name=i.origin_domain_name),i.verification!==void 0&&(o.verification=i.verification),i.custom_client_ip_header!==void 0&&(o.custom_client_ip_header=i.custom_client_ip_header),i.tls_policy!==void 0&&(o.tls_policy=i.tls_policy),i.domain_metadata!==void 0&&(o.domain_metadata=JSON.stringify(i.domain_metadata)),(await n.update(Ie).set(o).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).returning()).length>0},async remove(e,t){return(await n.delete(Ie).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).returning()).length>0}}}function r_(n){return{async get(e,t,i){const o=await n.select().from(Ne).where(g(c(Ne.tenant_id,e),c(Ne.prompt,t),c(Ne.language,i))).get();if(!o)return null;try{return JSON.parse(o.custom_text)}catch{return null}},async set(e,t,i,o){const s=Date.now(),l=JSON.stringify(o);await n.insert(Ne).values({tenant_id:e,prompt:t,language:i,custom_text:l,created_at_ts:s,updated_at_ts:s}).onConflictDoUpdate({target:[Ne.tenant_id,Ne.prompt,Ne.language],set:{custom_text:l,updated_at_ts:s}})},async delete(e,t,i){await n.delete(Ne).where(g(c(Ne.tenant_id,e),c(Ne.prompt,t),c(Ne.language,i)))},async list(e){return await n.select({prompt:Ne.prompt,language:Ne.language}).from(Ne).where(c(Ne.tenant_id,e)).all()}}}function l_(n){return{async create(e,t){const i=new Date().toISOString();await n.insert(dt).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(dt).where(c(dt.tenant_id,e)).get();if(!t)return null;const{tenant_id:i,...o}=t;return Q({...o,enabled:!!o.enabled,credentials:F(o.credentials,{}),settings:F(o.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(dt).set(i).where(c(dt.tenant_id,e))},async remove(e){await n.delete(dt).where(c(dt.tenant_id,e))}}}function Ci(n){const e={template:n.template,body:n.body,from:n.from,subject:n.subject,syntax:"liquid",includeEmailInRedirect:!!n.include_email_in_redirect,enabled:!!n.enabled};return Q({...e,resultUrl:n.result_url??void 0,urlLifetimeInSeconds:n.url_lifetime_in_seconds??void 0})}function d_(n){return{async get(e,t){const i=await n.select().from(Ue).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).get();return i?Ci(i):null},async list(e){return(await n.select().from(Ue).where(c(Ue.tenant_id,e)).all()).map(Ci)},async create(e,t){const i=new Date().toISOString();return await n.insert(Ue).values({tenant_id:e,template:t.template,body:t.body,from:t.from,subject:t.subject,syntax:t.syntax,result_url:t.resultUrl??null,url_lifetime_in_seconds:t.urlLifetimeInSeconds??null,include_email_in_redirect:t.includeEmailInRedirect,enabled:t.enabled,created_at:i,updated_at:i}),t},async update(e,t,i){const o={updated_at:new Date().toISOString()};i.body!==void 0&&(o.body=i.body),i.from!==void 0&&(o.from=i.from),i.subject!==void 0&&(o.subject=i.subject),i.syntax!==void 0&&(o.syntax=i.syntax),i.resultUrl!==void 0&&(o.result_url=i.resultUrl),i.urlLifetimeInSeconds!==void 0&&(o.url_lifetime_in_seconds=i.urlLifetimeInSeconds),i.includeEmailInRedirect!==void 0&&(o.include_email_in_redirect=i.includeEmailInRedirect),i.enabled!==void 0&&(o.enabled=i.enabled);const s=await n.update(Ue).set(o).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).run();return Number(s.changes??0)>0},async remove(e,t){const i=await n.delete(Ue).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).run();return Number(i.changes??0)>0}}}function c_(n){return{async create(e,t){const i=new Date().toISOString(),o=`af_${Le()}`;return await n.insert(Oe).values({id:o,tenant_id:e,name:t.name,actions:JSON.stringify(t.actions||[]),created_at:i,updated_at:i}),{id:o,name:t.name,actions:t.actions||[],created_at:i,updated_at:i}},async get(e,t){const i=await n.select().from(Oe).where(g(c(Oe.tenant_id,e),c(Oe.id,t))).get();if(!i)return null;const{tenant_id:o,actions:s,...l}=i;return Q({...l,actions:F(s,[])})},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.actions!==void 0&&(o.actions=JSON.stringify(i.actions)),(await n.update(Oe).set(o).where(g(c(Oe.tenant_id,e),c(Oe.id,t))).returning()).length===0?null:this.get(e,t)},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(Oe).where(c(Oe.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=Oe[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(m=>{const{tenant_id:y,actions:E,...T}=m;return Q({...T,actions:F(E,[])})});if(!s)return{flows:f};const[p]=await n.select({count:ge()}).from(Oe).where(c(Oe.tenant_id,e));return{flows:f,start:i*o,limit:o,length:Number((p==null?void 0:p.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 rn=["nodes","start","ending"];function __(n){return{async create(e,t){const i=new Date().toISOString(),o=Le(),s={id:o,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 rn)s[l]=JSON.stringify(t[l]||(l==="nodes"?[]:{}));return await n.insert(ke).values(s),{id:o,...t,created_at:i,updated_at:i}},async get(e,t){const i=await n.select().from(ke).where(g(c(ke.tenant_id,e),c(ke.id,t))).get();if(!i)return null;const{tenant_id:o,...s}=i,l={...s};for(const d of rn)l[d]=F(s[d]);return Q(l)},async update(e,t,i){const o={updated_at:new Date().toISOString()};for(const[l,d]of Object.entries(i))d!==void 0&&(rn.includes(l)?o[l]=JSON.stringify(d):o[l]=d);return(await n.update(ke).set(o).where(g(c(ke.tenant_id,e),c(ke.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(ke).where(c(ke.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=ke[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(m=>{const{tenant_id:y,...E}=m,T={...E};for(const G of rn)T[G]=F(E[G]);return Q(T)});if(!s)return{forms:f};const[p]=await n.select({count:ge()}).from(ke).where(c(ke.tenant_id,e));return{forms:f,start:i*o,limit:o,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(ke).where(g(c(ke.tenant_id,e),c(ke.id,t))).returning()).length>0}}}function $s(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 ci(n,e=new Date(0).toISOString()){return $s(n)??e}function ne(n){if(!n||n==="")return null;const e=new Date(n);return isNaN(e.getTime())?null:e.getTime()}function nn(n,e,t=[]){const i={};for(const o of e){const s=o.replace(/_ts$/,"");i[s]=ci(n[o])}for(const o of t){const s=o.replace(/_ts$/,"");i[s]=$s(n[o])}return i}const u_=kr("0123456789abcdefghijklmnopqrstuvwxyz",17);function p_(){return`hc_${u_()}`}function Di(n){const{created_at_ts:e,updated_at_ts:t,secrets:i,...o}=n,s=nn({created_at_ts:e,updated_at_ts:t},["created_at_ts","updated_at_ts"]);return{...o,...s,secrets:i?JSON.parse(i):void 0}}function f_(n){return{async create(e,t){const i=Date.now(),s={id:p_(),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(Ke).values(s),Di({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(Ke).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).get();return i?Di(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.code!==void 0&&(o.code=i.code),i.secrets!==void 0&&(o.secrets=JSON.stringify(i.secrets)),(await n.update(Ke).set(o).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).returning()).length>0},async remove(e,t){return(await n.delete(Ke).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).returning()).length>0}}}function h_(){const{customAlphabet:n}=require("nanoid");return`h_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function g_(n){if(!(typeof n!="string"||!n))try{const e=JSON.parse(n);return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}function Mn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,metadata:o,...s}=n,l=nn({created_at_ts:t,updated_at_ts:i},["created_at_ts","updated_at_ts"]);return Q({...s,enabled:!!s.enabled,synchronous:!!s.synchronous,metadata:g_(o),...l})}function m_(n){return{async create(e,t){const i=Date.now(),s={hook_id:t.hook_id||h_(),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,metadata:t.metadata?JSON.stringify(t.metadata):null,created_at_ts:i,updated_at_ts:i};return await n.insert(me).values(s),Mn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(me).where(g(c(me.tenant_id,e),c(me.hook_id,t))).get();return i?Mn(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.trigger_id!==void 0&&(o.trigger_id=i.trigger_id),i.url!==void 0&&(o.url=i.url),i.enabled!==void 0&&(o.enabled=i.enabled),i.synchronous!==void 0&&(o.synchronous=i.synchronous),i.priority!==void 0&&(o.priority=i.priority),i.form_id!==void 0&&(o.form_id=i.form_id),i.template_id!==void 0&&(o.template_id=i.template_id),i.code_id!==void 0&&(o.code_id=i.code_id),i.metadata!==void 0&&(o.metadata=i.metadata===null?null:JSON.stringify(i.metadata)),(await n.update(me).set(o).where(g(c(me.tenant_id,e),c(me.hook_id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?We(me,d,["url","form_id","template_id","code_id"]):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();const m=l!=null&&l.sort_by?me[l.sort_by]:void 0;m?p=p.orderBy((l==null?void 0:l.sort_order)==="desc"?se(m):he(m)):p=p.orderBy(se(me.priority),he(me.created_at_ts));const E=(await p.offset(i*o).limit(o)).map(Mn);if(!s)return{hooks:E};const[T]=await n.select({count:ge()}).from(me).where(f);return{hooks:E,start:i*o,limit:o,length:Number((T==null?void 0:T.count)??0)}},async remove(e,t){return(await n.delete(me).where(g(c(me.tenant_id,e),c(me.hook_id,t))).returning()).length>0}}}function y_(){const{customAlphabet:n}=require("nanoid");return`inv_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const _i=["inviter","invitee","app_metadata","user_metadata","roles"];function qn(n){const{tenant_id:e,send_invitation_email:t,...i}=n,o={...i};for(const s of _i)o[s]=F(i[s],s==="roles"?[]:{});return o.send_invitation_email=!!t,Q(o)}function v_(n){return{async create(e,t){var u,f;const i=t.id||y_(),o=t.ttl_sec||604800,s=new Date,l=new Date(s.getTime()+o*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:o,send_invitation_email:t.send_invitation_email!==!1?1:0,created_at:s.toISOString(),expires_at:l};for(const p of _i)t[p]!==void 0&&(d[p]=JSON.stringify(t[p]));try{await n.insert(xe).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 _t(409,{message:"Invite already exists"}):p}return qn({...d,tenant_id:e})},async get(e,t){const i=await n.select().from(xe).where(g(c(xe.tenant_id,e),c(xe.id,t))).get();return i?qn(i):null},async update(e,t,i){const o={};for(const l of _i)i[l]!==void 0&&(o[l]=JSON.stringify(i[l]));return i.connection_id!==void 0&&(o.connection_id=i.connection_id),i.ttl_sec!==void 0&&(o.ttl_sec=i.ttl_sec,o.expires_at=new Date(Date.now()+i.ttl_sec*1e3).toISOString()),(await n.update(xe).set(o).where(g(c(xe.tenant_id,e),c(xe.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(xe).where(c(xe.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=xe[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(qn);if(!s)return{invites:f};const[p]=await n.select({count:ge()}).from(xe).where(c(xe.tenant_id,e));return{invites:f,start:i*o,limit:o,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}}}function w_(n){return{async create(e){await n.insert(Je).values({...e,created_at:new Date().toDateString()})},async list(e){const{page:t=0,per_page:i=50,include_totals:o=!1,sort:s}=e||{},l=new Date().toISOString();let d=n.select().from(Je).where($e(pn(Je.revoked_at,l),Ce(Je.revoked_at))).$dynamic();if(s!=null&&s.sort_by){const m=Je[s.sort_by];m&&(d=d.orderBy(s.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(t*i).limit(i)).map(m=>{const{created_at:y,...E}=m;return Q(E)});if(!o)return{signingKeys:f};const[p]=await n.select({count:ge()}).from(Je).where($e(pn(Je.revoked_at,l),Ce(Je.revoked_at)));return{signingKeys:f,start:t*i,limit:i,length:mr((p==null?void 0:p.count)??0)}},async update(e,t){return(await n.update(Je).set(t).where(c(Je.kid,e)).returning()).length>0}}}const ui="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Bn=ui.length;function S_(){let t=Date.now(),i="";for(let s=10;s>0;s--)i=ui.charAt(t%Bn)+i,t=Math.floor(t/Bn);const o=new Uint8Array(16);crypto.getRandomValues(o);for(let s=0;s<16;s++)i+=ui.charAt(o[s]%Bn);return i}function Li(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,expires_at_ts:o,state_data:s,auth_params:l,...d}=n,u=nn({created_at_ts:t,updated_at_ts:i,expires_at_ts:o},["created_at_ts","updated_at_ts","expires_at_ts"]),f={};for(const[m,y]of Object.entries(d))y!=null&&(f[m]=y);const p=_s(f,["auth_strategy"]);return Q({...p,authParams:typeof l=="string"&&l.length>0?JSON.parse(l):{},...u,state_data:F(s)})}function N_(n){return{async create(e,t){var l,d;const i=Date.now(),s={id:S_(),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(Y).values(s),Li({...s,tenant_id:e})},async get(e,t){const i=e?g(c(Y.tenant_id,e),c(Y.id,t)):c(Y.id,t),o=await n.select().from(Y).where(i).get();return o?Li(o):null},async update(e,t,i){var s,l,d;const o={updated_at_ts:Date.now()};if(i.session_id!==void 0&&(o.session_id=i.session_id),i.state!==void 0&&(o.state=i.state),i.state_data!==void 0&&(o.state_data=JSON.stringify(i.state_data)),i.failure_reason!==void 0&&(o.failure_reason=i.failure_reason),i.user_id!==void 0&&(o.user_id=i.user_id),i.auth_connection!==void 0&&(o.auth_connection=i.auth_connection),i.auth_strategy!==void 0&&(o.auth_strategy_strategy=(s=i.auth_strategy)==null?void 0:s.strategy,o.auth_strategy_strategy_type=(l=i.auth_strategy)==null?void 0:l.strategy_type),i.authenticated_at!==void 0&&(o.authenticated_at=i.authenticated_at),i.authorization_url!==void 0&&(o.authorization_url=(d=i.authorization_url)==null?void 0:d.substring(0,1024)),i.expires_at!==void 0&&(o.expires_at_ts=ne(i.expires_at)),i.authParams!==void 0){const u=await n.select({auth_params:Y.auth_params}).from(Y).where(g(c(Y.tenant_id,e),c(Y.id,t))).get(),f=u!=null&&u.auth_params&&typeof u.auth_params=="string"&&u.auth_params.length>0?JSON.parse(u.auth_params):{};o.auth_params=JSON.stringify({...f,...i.authParams})}return await n.update(Y).set(o).where(g(c(Y.tenant_id,e),c(Y.id,t))),!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 $n(n){const{tenant_id:e,isMobile:t,auth0_client:i,details:o,country_code:s,city_name:l,latitude:d,longitude:u,time_zone:f,continent_code:p,scope:m,...y}=n,E={...y,isMobile:!!t,auth0_client:F(i),details:F(o),scope:m?m.split(","):void 0};return s&&(E.location_info=Q({country_code:s,city_name:l,latitude:d,longitude:u,time_zone:f,continent_code:p})),Q(E)}function b_(n){return{async create(e,t){var s,l;const o={log_id:t.log_id||Le(),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:(s=t.user_agent)==null?void 0:s.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&&(o.auth0_client=JSON.stringify(t.auth0_client)),t.details&&(o.details=JSON.stringify(t.details).substring(0,8192)),t.location_info&&(o.country_code=t.location_info.country_code,o.city_name=t.location_info.city_name,o.latitude=t.location_info.latitude,o.longitude=t.location_info.longitude,o.time_zone=t.location_info.time_zone,o.continent_code=t.location_info.continent_code),await n.insert(z).values(o),$n({...o,tenant_id:e})},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d,from_date:u,to_date:f}=t||{},p=[c(z.tenant_id,e)];if(d){const W=We(z,d,["user_id","ip","type","client_id"]);W&&p.push(W)}typeof u=="number"&&Number.isFinite(u)&&p.push(Tt(z.date,new Date(Math.floor(u)*1e3).toISOString())),typeof f=="number"&&Number.isFinite(f)&&p.push(Qe(z.date,new Date((Math.floor(f)+1)*1e3).toISOString()));const m=g(...p);let y=n.select().from(z).where(m).$dynamic();if(l!=null&&l.sort_by){const W=z[l.sort_by];W&&(y=y.orderBy(l.sort_order==="desc"?se(W):he(W)))}else y=y.orderBy(se(z.date));const T=(await y.offset(i*o).limit(o)).map($n);if(!s)return{logs:T};const[G]=await n.select({count:ge()}).from(z).where(m);return{logs:T,start:i*o,limit:o,length:Number((G==null?void 0:G.count)??0)}},async get(e,t){const i=await n.select().from(z).where(g(c(z.tenant_id,e),c(z.log_id,t))).get();return i?$n(i):null}}}const pi="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jn=pi.length;function E_(){let t=Date.now(),i="";for(let s=10;s>0;s--)i=pi.charAt(t%jn)+i,t=Math.floor(t/jn);const o=new Uint8Array(16);crypto.getRandomValues(o);for(let s=0;s<16;s++)i+=pi.charAt(o[s]%jn);return i}function ln(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,credential_backed_up:o,confirmed:s,transports:l,...d}=n;return Q({...d,confirmed:!!s,credential_backed_up:o!=null?!!o:void 0,transports:F(l),created_at:ci(t),updated_at:ci(i)})}function x_(n){return{async create(e,t){const i=Date.now(),s={id:t.id||E_(),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(s),ln({...s,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?ln(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?ln(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(ln)},async update(e,t,i){const o={updated_at_ts:Date.now()};i.type!==void 0&&(o.type=i.type),i.phone_number!==void 0&&(o.phone_number=i.phone_number),i.totp_secret!==void 0&&(o.totp_secret=i.totp_secret),i.credential_id!==void 0&&(o.credential_id=i.credential_id),i.public_key!==void 0&&(o.public_key=i.public_key),i.sign_count!==void 0&&(o.sign_count=i.sign_count),i.credential_backed_up!==void 0&&(o.credential_backed_up=i.credential_backed_up?1:0),i.transports!==void 0&&(o.transports=JSON.stringify(i.transports)),i.friendly_name!==void 0&&(o.friendly_name=i.friendly_name),i.confirmed!==void 0&&(o.confirmed=i.confirmed?1:0),await n.update(ue).set(o).where(g(c(ue.tenant_id,e),c(ue.id,t)));const s=await this.get(e,t);if(!s)throw new Error(`Authentication method ${t} not found after update`);return s},async remove(e,t){return(await n.delete(ue).where(g(c(ue.tenant_id,e),c(ue.id,t))).returning()).length>0}}}function k_(){const{customAlphabet:n}=require("nanoid");return`org_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Vn(n){const{tenant_id:e,branding:t,metadata:i,enabled_connections:o,token_quota:s,...l}=n;return Q({...l,branding:F(t,{}),metadata:F(i,{}),enabled_connections:F(o,[]),token_quota:F(s,{})})}function O_(n){return{async create(e,t){var l,d;const i=new Date().toISOString(),s={id:t.id||k_(),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(ee).values(s)}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 _t(409,{message:"Organization already exists"}):u}return Vn({...s,tenant_id:e})},async get(e,t){let i=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.id,t))).get();return i||(i=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.name,t))).get()),i?Vn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.display_name!==void 0&&(o.display_name=i.display_name),i.branding!==void 0&&(o.branding=JSON.stringify(i.branding)),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.enabled_connections!==void 0&&(o.enabled_connections=JSON.stringify(i.enabled_connections)),i.token_quota!==void 0&&(o.token_quota=JSON.stringify(i.token_quota)),(await n.update(ee).set(o).where(g(c(ee.tenant_id,e),c(ee.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(ee).where(c(ee.tenant_id,e)).$dynamic();if(d&&(u=u.where($e(xt(ee.name,`%${d}%`),xt(ee.display_name,`%${d}%`)))),l!=null&&l.sort_by){const E=ee[l.sort_by];E&&(u=u.orderBy(l.sort_order==="desc"?se(E):he(E)))}const p=(await u.offset(i*o).limit(o)).map(Vn);if(!s)return{organizations:p};const m=[c(ee.tenant_id,e)];d&&m.push($e(xt(ee.name,`%${d}%`),xt(ee.display_name,`%${d}%`)));const[y]=await n.select({count:ge()}).from(ee).where(g(...m));return{organizations:p,start:i*o,limit:o,length:Number((y==null?void 0:y.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 Zn(n){const{tenant_id:e,is_current:t,...i}=n;return{...i,is_current:!!t}}function T_(n){return{async create(e,t){const i=new Date().toISOString(),o=t.id||Le();t.is_current!==!1&&await n.update(oe).set({is_current:0}).where(g(c(oe.tenant_id,e),c(oe.user_id,t.user_id)));const s={id:o,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(oe).values(s),Zn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(oe).where(g(c(oe.tenant_id,e),c(oe.user_id,t),c(oe.is_current,1))).get();return i?Zn(i):null},async list(e,t,i){let o=n.select().from(oe).where(g(c(oe.tenant_id,e),c(oe.user_id,t))).orderBy(se(oe.created_at)).$dynamic();return i&&(o=o.limit(i)),(await o).map(Zn)},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(oe).set(i).where(g(c(oe.tenant_id,e),c(oe.id,t.id))):await n.update(oe).set(i).where(g(c(oe.tenant_id,e),c(oe.user_id,t.user_id),c(oe.is_current,1))),!0}}}function A_(n){return{async get(e){const t=await n.select().from(Ut).where(c(Ut.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(Ut).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:Ut.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 dn(n){const{tenant_id:e,created_at_ts:t,expires_at_ts:i,idle_expires_at_ts:o,last_exchanged_at_ts:s,revoked_at_ts:l,rotated_at_ts:d,device:u,resource_servers:f,rotating:p,...m}=n,y=nn({created_at_ts:t,expires_at_ts:i,idle_expires_at_ts:o,last_exchanged_at_ts:s,revoked_at_ts:l,rotated_at_ts:d},["created_at_ts"],["expires_at_ts","idle_expires_at_ts","last_exchanged_at_ts","revoked_at_ts","rotated_at_ts"]);return Q({...m,...y,rotating:!!p,device:F(u,{}),resource_servers:F(f,[])})}function I_(n,e){return Math.max(n??0,e??0)}function C_(n){return{async create(e,t){const i=Date.now(),o={id:t.id||Le(),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,token_lookup:t.token_lookup??null,token_hash:t.token_hash??null,family_id:t.family_id??null,rotated_to:t.rotated_to??null,rotated_at_ts:ne(t.rotated_at),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(O`BEGIN`);try{await n.insert(J).values(o);const s=I_(o.expires_at_ts,o.idle_expires_at_ts);s>0&&o.login_id&&await n.update(Y).set({expires_at_ts:s,updated_at_ts:i}).where(g(c(Y.tenant_id,e),c(Y.id,o.login_id),Qe(Y.expires_at_ts,s))),await n.run(O`COMMIT`)}catch(s){throw await n.run(O`ROLLBACK`),s}return dn({...o,tenant_id:e})},async get(e,t){const i=await n.select().from(J).where(g(c(J.tenant_id,e),c(J.id,t))).get();return i?dn(i):null},async getByLookup(e,t){const i=await n.select().from(J).where(g(c(J.tenant_id,e),c(J.token_lookup,t))).get();return i?dn(i):null},async update(e,t,i,o){const s={};i.device!==void 0&&(s.device=JSON.stringify(i.device)),i.resource_servers!==void 0&&(s.resource_servers=JSON.stringify(i.resource_servers)),i.rotating!==void 0&&(s.rotating=i.rotating),i.token_lookup!==void 0&&(s.token_lookup=i.token_lookup),i.token_hash!==void 0&&(s.token_hash=i.token_hash),i.family_id!==void 0&&(s.family_id=i.family_id),i.rotated_to!==void 0&&(s.rotated_to=i.rotated_to),i.rotated_at!==void 0&&(s.rotated_at_ts=ne(i.rotated_at)),i.expires_at!==void 0&&(s.expires_at_ts=ne(i.expires_at)),i.idle_expires_at!==void 0&&(s.idle_expires_at_ts=ne(i.idle_expires_at)),i.last_exchanged_at!==void 0&&(s.last_exchanged_at_ts=ne(i.last_exchanged_at)),i.revoked_at!==void 0&&(s.revoked_at_ts=ne(i.revoked_at));const l=o==null?void 0:o.loginSessionBump,d=l?ne(l.expires_at):null,u=await n.update(J).set(s).where(g(c(J.tenant_id,e),c(J.id,t))).returning();return l!=null&&l.login_id&&d&&d>0&&await n.update(Y).set({expires_at_ts:d,updated_at_ts:Date.now()}).where(g(c(Y.tenant_id,e),c(Y.id,l.login_id),Qe(Y.expires_at_ts,d))).catch(()=>{}),u.length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(J).where(c(J.tenant_id,e)).$dynamic();if(d){const y=We(J,d,["user_id"]);y&&(u=u.where(g(c(J.tenant_id,e),y)))}if(l!=null&&l.sort_by){const y=J[l.sort_by];y&&(u=u.orderBy(l.sort_order==="desc"?se(y):he(y)))}const p=(await u.offset(i*o).limit(o)).map(dn);if(!s)return{refresh_tokens:p};const[m]=await n.select({count:ge()}).from(J).where(c(J.tenant_id,e));return{refresh_tokens:p,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async remove(e,t){return(await n.delete(J).where(g(c(J.tenant_id,e),c(J.id,t))).returning()).length>0},async revokeByLoginSession(e,t,i){return(await n.update(J).set({revoked_at_ts:ne(i)}).where(g(c(J.tenant_id,e),c(J.login_id,t),Ce(J.revoked_at_ts))).returning()).length},async revokeFamily(e,t,i){return(await n.update(J).set({revoked_at_ts:ne(i)}).where(g(c(J.tenant_id,e),c(J.family_id,t),Ce(J.revoked_at_ts))).returning()).length}}}function D_(){const{customAlphabet:n}=require("nanoid");return`api_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const fi=["skip_consent_for_verifiable_first_party_clients","allow_offline_access","is_system"],Ri=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 Hn(n){const{tenant_id:e,verification_key:t,scopes:i,options:o,metadata:s,...l}=n,d={...l};d.scopes=F(i,[]),d.options=F(o,{}),d.metadata=F(s),t!==void 0&&(d.verificationKey=t);for(const u of fi)l[u]!==void 0&&l[u]!==null&&(d[u]=!!l[u]);return Q(d)}function L_(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||D_(),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 fi)t[l]!==void 0&&(s[l]=t[l]?1:0);return s.is_system===void 0&&(s.is_system=0),await n.insert(te).values(s),Hn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(te).where(g(c(te.tenant_id,e),c(te.id,t))).get();return i?Hn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};i.name!==void 0&&(o.name=i.name),i.identifier!==void 0&&(o.identifier=i.identifier),i.signing_alg!==void 0&&(o.signing_alg=i.signing_alg),i.signing_secret!==void 0&&(o.signing_secret=i.signing_secret),i.token_lifetime!==void 0&&(o.token_lifetime=i.token_lifetime),i.token_lifetime_for_web!==void 0&&(o.token_lifetime_for_web=i.token_lifetime_for_web),i.scopes!==void 0&&(o.scopes=JSON.stringify(i.scopes)),i.options!==void 0&&(o.options=O`json_patch(COALESCE(${te.options}, '{}'), ${JSON.stringify(i.options)})`),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.verificationKey!==void 0&&(o.verification_key=i.verificationKey);for(const l of fi)i[l]!==void 0&&(o[l]=i[l]?1:0);return(await n.update(te).set(o).where(g(c(te.tenant_id,e),c(te.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=Math.max(0,Math.floor(Number(i)||0)),f=Math.min(Math.max(1,Math.floor(Number(o)||50)),500),p=[c(te.tenant_id,e)];if(d){const G=d.match(/^([^:]+):(.+)$/);if(G){const[,W,ie]=G,Me=W==null?void 0:W.startsWith("-"),Se=Me?W==null?void 0:W.substring(1):W;if(Se&&Ri.has(Se)&&!Me){const Ee=te[Se];p.push(xt(Ee,`%${ie}%`))}}}let m=n.select().from(te).where(g(...p)).$dynamic();if(l!=null&&l.sort_by&&Ri.has(l.sort_by)){const G=te[l.sort_by];m=m.orderBy(l.sort_order==="desc"?se(G):he(G))}const E=(await m.offset(u*f).limit(f)).map(Hn);if(!s)return{resource_servers:E};const[T]=await n.select({count:ge()}).from(te).where(g(...p));return{resource_servers:E,start:u*f,limit:f,length:Number((T==null?void 0:T.count)??0)}},async remove(e,t){return(await n.delete(te).where(g(c(te.tenant_id,e),c(te.id,t))).returning()).length>0}}}function R_(n){return{async assign(e,t,i){const o=new Date().toISOString();return await n.insert(Re).values(i.map(s=>({tenant_id:e,role_id:t,resource_server_identifier:s.resource_server_identifier,permission_name:s.permission_name,created_at:o}))).onConflictDoNothing(),!0},async list(e,t,i){const o=await n.select({resource_server_identifier:Re.resource_server_identifier,permission_name:Re.permission_name,created_at:Re.created_at}).from(Re).where(g(c(Re.tenant_id,e),c(Re.role_id,t))).all(),s=[...new Set(o.map(d=>d.resource_server_identifier))],l=new Map;if(s.length>0){const d=await n.select({identifier:te.identifier,name:te.name}).from(te).where(g(c(te.tenant_id,e),De(te.identifier,s))).all();for(const u of d)l.set(u.identifier,u.name)}return o.map(d=>({...d,resource_server_name:l.get(d.resource_server_identifier)||d.resource_server_identifier}))},async remove(e,t,i){const o=i.map(l=>g(c(Re.resource_server_identifier,l.resource_server_identifier),c(Re.permission_name,l.permission_name)));return(await n.delete(Re).where(g(c(Re.tenant_id,e),c(Re.role_id,t),$e(...o))).returning()).length>0}}}function U_(n){return{async create(e,t,i,o){var s,l;try{await n.insert(qe).values({tenant_id:e,user_id:t,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name,organization_id:o||"",created_at:new Date().toISOString()})}catch(d){if((s=d==null?void 0:d.message)!=null&&s.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,o){let s=[c(qe.tenant_id,e),c(qe.user_id,t)];o&&s.push(c(qe.organization_id,o));const l=await n.select().from(qe).where(g(...s)).all();return await Promise.all(l.map(async u=>{const f=await n.select({name:te.name}).from(te).where(g(c(te.tenant_id,e),c(te.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,o){return(await n.delete(qe).where(g(c(qe.tenant_id,e),c(qe.user_id,t),c(qe.resource_server_identifier,i.resource_server_identifier),c(qe.permission_name,i.permission_name),c(qe.organization_id,o||""))).returning()).length>0}}}function Kn(n){const{tenant_id:e,is_system:t,metadata:i,...o}=n;return Q({...o,is_system:t?!0:void 0,metadata:F(i)})}function z_(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||Le(),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(s),Kn({...s,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?Kn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.description!==void 0&&(o.description=i.description),i.is_system!==void 0&&(o.is_system=i.is_system?1:0),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),(await n.update(_e).set(o).where(g(c(_e.tenant_id,e),c(_e.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?We(_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"?se(T):he(T)))}const y=(await p.offset(i*o).limit(o)).map(Kn);if(!s)return{roles:y};const[E]=await n.select({count:ge()}).from(_e).where(f);return{roles:y,start:i*o,limit:o,length:Number((E==null?void 0:E.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 F_=["created_at_ts","updated_at_ts"],P_=["expires_at_ts","idle_expires_at_ts","authenticated_at_ts","last_interaction_at_ts","used_at_ts","revoked_at_ts"];function Jn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,expires_at_ts:o,idle_expires_at_ts:s,authenticated_at_ts:l,last_interaction_at_ts:d,used_at_ts:u,revoked_at_ts:f,device:p,clients:m,...y}=n,E=nn({created_at_ts:t,updated_at_ts:i,expires_at_ts:o,idle_expires_at_ts:s,authenticated_at_ts:l,last_interaction_at_ts:d,used_at_ts:u,revoked_at_ts:f},[...F_],[...P_]);return Q({...y,...E,device:F(p,{}),clients:F(m,[])})}function M_(n){return{async create(e,t){const i=Date.now(),o={id:t.id||Le(),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(ae).values(o),Jn({...o,tenant_id:e})},async get(e,t){const i=await n.select().from(ae).where(g(c(ae.tenant_id,e),c(ae.id,t))).get();return i?Jn(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.user_id!==void 0&&(o.user_id=i.user_id),i.login_session_id!==void 0&&(o.login_session_id=i.login_session_id),i.device!==void 0&&(o.device=JSON.stringify(i.device)),i.clients!==void 0&&(o.clients=JSON.stringify(i.clients)),i.expires_at!==void 0&&(o.expires_at_ts=ne(i.expires_at)),i.idle_expires_at!==void 0&&(o.idle_expires_at_ts=ne(i.idle_expires_at)),i.authenticated_at!==void 0&&(o.authenticated_at_ts=ne(i.authenticated_at)),i.last_interaction_at!==void 0&&(o.last_interaction_at_ts=ne(i.last_interaction_at)),i.used_at!==void 0&&(o.used_at_ts=ne(i.used_at)),i.revoked_at!==void 0&&(o.revoked_at_ts=ne(i.revoked_at)),(await n.update(ae).set(o).where(g(c(ae.tenant_id,e),c(ae.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?We(ae,d,["user_id"]):void 0,f=u?g(c(ae.tenant_id,e),u):c(ae.tenant_id,e);let p=n.select().from(ae).where(f).$dynamic();if(l!=null&&l.sort_by){const T=ae[l.sort_by];T&&(p=p.orderBy(l.sort_order==="desc"?se(T):he(T)))}const y=(await p.offset(i*o).limit(o)).map(Jn);if(!s)return{sessions:y};const[E]=await n.select({count:ge()}).from(ae).where(f);return{sessions:y,start:i*o,limit:o,length:Number((E==null?void 0:E.count)??0)}},async remove(e,t){return(await n.delete(ae).where(g(c(ae.tenant_id,e),c(ae.id,t))).returning()).length>0}}}const js=["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"],Vs=["allow_organization_name_in_authentication_api","customize_mfa_in_postlogin_action","pushed_authorization_requests_supported","authorization_response_iss_parameter_supported"];function Ui(n){const e={...n};for(const t of js)typeof e[t]=="string"&&(e[t]=F(e[t]));for(const t of Vs)e[t]!==void 0&&e[t]!==null&&(e[t]=e[t]===1);return Q(e)}function zi(n){const e={...n};hr(n,js,e);for(const t of Vs)n[t]!==void 0&&(e[t]=n[t]?1:0);return cs(e)}function q_(n){return{async create(e){var o,s;const t={id:e.id||Le(),created_at:new Date().toISOString(),updated_at:new Date().toISOString(),...e},i=zi(t);try{await n.insert(B).values(i)}catch(l){throw(o=l==null?void 0:l.message)!=null&&o.includes("UNIQUE constraint failed")||(s=l==null?void 0:l.message)!=null&&s.includes("duplicate key")||(l==null?void 0:l.code)==="SQLITE_CONSTRAINT"?new _t(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?Ui(t):null},async list(e){const{page:t=0,per_page:i=50,include_totals:o=!1,sort:s,q:l}=e||{};let d=n.select().from(B).$dynamic();if(l){const m=We(B,l,["friendly_name"]);m&&(d=d.where(m))}if(s!=null&&s.sort_by){const m=B[s.sort_by];m&&(d=d.orderBy(s.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(t*i).limit(i)).map(Ui);if(!o)return{tenants:f};const[p]=await n.select({count:ge()}).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=zi({...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 B_=["colors","borders","fonts","page_background","widget"];function Fi(n){const{tenant_id:e,...t}=n,i=_s(t,B_);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),Q(i)}function $_(n){return{async create(e,t,i){const o=new Date().toISOString(),s=i||Le(),d={...Yn(t),tenant_id:e,themeId:s,created_at:o,updated_at:o};return await n.insert(He).values(d),Fi({...d,tenant_id:e})},async get(e,t){const i=await n.select().from(He).where(g(c(He.tenant_id,e),c(He.themeId,t))).get();return i?Fi(i):null},async update(e,t,i){const o=Yn(i);return o.updated_at=new Date().toISOString(),await n.update(He).set(o).where(g(c(He.tenant_id,e),c(He.themeId,t))),!0},async remove(e,t){return(await n.delete(He).where(g(c(He.tenant_id,e),c(He.themeId,t))).returning()).length>0}}}function j_(n){return{async get(e){const t=await n.select({body:lt.body}).from(lt).where(c(lt.tenant_id,e)).get();return t?{body:t.body}:null},async set(e,t){const i=Date.now();await n.insert(lt).values({tenant_id:e,body:t.body,created_at_ts:i,updated_at_ts:i}).onConflictDoUpdate({target:lt.tenant_id,set:{body:t.body,updated_at_ts:i}})},async delete(e){await n.delete(lt).where(c(lt.tenant_id,e))}}}function Pi(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"?F(n.profileData,{}):{}},t}function Qn(n,e=[]){const{tenant_id:t,app_metadata:i,user_metadata:o,address:s,email_verified:l,phone_verified:d,is_social:u,linked_to:f,profileData:p,...m}=n,y=Pi(n,!0),E=e.map(T=>Pi(T,!1));return Q({...m,email:n.email||"",email_verified:!!l,phone_verified:d!=null?!!d:void 0,is_social:!!u,app_metadata:F(i,{}),user_metadata:F(o,{}),address:F(s),identities:[y,...E]})}function V_(n){const e=async(t,i)=>{var d,u;const o=new Date().toISOString(),s={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||o,updated_at:i.updated_at||o},l=i.password?Le():void 0;try{if(i.password&&l){await n.run(O`BEGIN`);try{await n.insert(Z).values(s),await n.insert(oe).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:o,updated_at:o}),await n.run(O`COMMIT`)}catch(f){throw await n.run(O`ROLLBACK`),f}}else await n.insert(Z).values(s)}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 _t(409,{message:"User already exists"}):(console.error("User upsert failed:",f==null?void 0:f.code,f==null?void 0:f.message),new _t(500,{message:"Internal server error"}))}return Qn(s)};return{create:e,rawCreate:e,async get(t,i){const o=await n.select().from(Z).where(g(c(Z.tenant_id,t),c(Z.user_id,i))).get();if(!o)return null;const s=await n.select().from(Z).where(g(c(Z.tenant_id,t),c(Z.linked_to,i))).all();return Qn(o,s)},async update(t,i,o){const s={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)o[u]!==void 0&&(s[u]=o[u]);return o.email_verified!==void 0&&(s.email_verified=o.email_verified),o.phone_verified!==void 0&&(s.phone_verified=o.phone_verified),o.is_social!==void 0&&(s.is_social=o.is_social),o.app_metadata!==void 0&&(s.app_metadata=JSON.stringify(o.app_metadata)),o.user_metadata!==void 0&&(s.user_metadata=JSON.stringify(o.user_metadata)),o.address!==void 0&&(s.address=JSON.stringify(o.address)),o.profileData!==void 0&&(s.profileData=JSON.stringify(o.profileData)),(await n.update(Z).set(s).where(g(c(Z.tenant_id,t),c(Z.user_id,i))).returning()).length>0},async list(t,i){const{page:o=0,per_page:s=50,include_totals:l=!1,sort:d,q:u}=i||{},f=[c(Z.tenant_id,t),Ce(Z.linked_to)];if(u){const ie=We(Z,u,["email","name","nickname","username"]);ie&&f.push(ie)}const p=g(...f);let m=n.select().from(Z).where(p).$dynamic();if(d!=null&&d.sort_by){const ie=Z[d.sort_by];ie&&(m=m.orderBy(d.sort_order==="desc"?se(ie):he(ie)))}const y=await m.offset(o*s).limit(s),E=y.map(ie=>ie.user_id);let T=[];E.length>0&&(T=await n.select().from(Z).where(g(c(Z.tenant_id,t),De(Z.linked_to,E))));const G=y.map(ie=>{const Me=T.filter(Se=>Se.linked_to===ie.user_id);return Qn(ie,Me)});if(!l)return{users:G};const[W]=await n.select({count:ge()}).from(Z).where(p);return{users:G,start:o*s,limit:s,length:Number((W==null?void 0:W.count)??0)}},async remove(t,i){await n.run(O`BEGIN`);try{const o=await n.select({user_id:Z.user_id}).from(Z).where(g(c(Z.tenant_id,t),c(Z.linked_to,i))),s=[i,...o.map(d=>d.user_id)];await n.delete(ue).where(g(c(ue.tenant_id,t),De(ue.user_id,s))),await n.delete(oe).where(g(c(oe.tenant_id,t),De(oe.user_id,s))),await n.delete(Z).where(g(c(Z.tenant_id,t),c(Z.linked_to,i)));const l=await n.delete(Z).where(g(c(Z.tenant_id,t),c(Z.user_id,i))).returning();return await n.run(O`COMMIT`),l.length>0}catch(o){throw await n.run(O`ROLLBACK`),o}},async unlink(t,i,o,s){const l=`${o}|${s}`;return(await n.update(Z).set({linked_to:null}).where(g(c(Z.tenant_id,t),c(Z.user_id,l),c(Z.linked_to,i))).returning()).length>0}}}function Z_(n){return{async create(e,t,i,o){var s,l;try{await n.insert(Be).values({tenant_id:e,user_id:t,role_id:i,organization_id:o||"",created_at:new Date().toISOString()})}catch(d){if((s=d==null?void 0:d.message)!=null&&s.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,o){let s=[c(Be.tenant_id,e),c(Be.user_id,t)];o&&s.push(c(Be.organization_id,o));const l=await n.select({role_id:Be.role_id}).from(Be).where(g(...s)).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:m,metadata:y,...E}=f;return Q({...E,is_system:m?!0:void 0,metadata:F(y)})}))).filter(Boolean)},async remove(e,t,i,o){return(await n.delete(Be).where(g(c(Be.tenant_id,e),c(Be.user_id,t),c(Be.role_id,i),c(Be.organization_id,o||""))).returning()).length>0}}}function H_(n){return{async create(e,t){var u,f;const i=new Date().toISOString(),s={id:t.id||Le(),tenant_id:e,user_id:t.user_id,organization_id:t.organization_id,created_at:i,updated_at:i};try{await n.insert(le).values(s)}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 _t(409,{message:"User organization already exists"}):p}const{tenant_id:l,...d}=s;return d},async get(e,t){const i=await n.select().from(le).where(g(c(le.tenant_id,e),c(le.id,t))).get();if(!i)return null;const{tenant_id:o,...s}=i;return s},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.user_id!==void 0&&(o.user_id=i.user_id),i.organization_id!==void 0&&(o.organization_id=i.organization_id),(await n.update(le).set(o).where(g(c(le.tenant_id,e),c(le.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,q:l}=t||{},d=c(le.tenant_id,e);let u=d;if(l){const y=We(le,l,["user_id","organization_id"]);y&&(u=g(d,y))}const p=(await n.select().from(le).where(u).offset(i*o).limit(o)).map(y=>{const{tenant_id:E,...T}=y;return T});if(!s)return{userOrganizations:p};const[m]=await n.select({count:ge()}).from(le).where(u);return{userOrganizations:p,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async listUserOrganizations(e,t,i){const{page:o=0,per_page:s=50,include_totals:l=!1}=i||{},d=await n.select().from(le).where(g(c(le.tenant_id,e),c(le.user_id,t))).offset(o*s).limit(s).all(),f=(await Promise.all(d.map(async m=>{const y=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.id,m.organization_id))).get();if(!y)return null;const{tenant_id:E,branding:T,metadata:G,enabled_connections:W,token_quota:ie,...Me}=y;return Q({...Me,branding:F(T,{}),metadata:F(G,{}),enabled_connections:F(W,[]),token_quota:F(ie,{})})}))).filter(Boolean);if(!l)return{organizations:f};const[p]=await n.select({count:ge()}).from(le).where(g(c(le.tenant_id,e),c(le.user_id,t)));return{organizations:f,start:o*s,limit:s,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(le).where(g(c(le.tenant_id,e),c(le.id,t))).returning()).length>0}}}const Mi=["s"],K_=["pwd_leak"];function qi(n){return/^\d{8}$/.test(n)?`${n.slice(0,4)}-${n.slice(4,6)}-${n.slice(6,8)}`:n}function J_(n){return{async getDaily(e,t){const i=new Date,o=t!=null&&t.from?qi(t.from):new Date(i.getTime()-30*24*60*60*1e3).toISOString().split("T")[0],s=t!=null&&t.to?qi(t.to):i.toISOString().split("T")[0];return(await n.select({date:O`substr(${z.date}, 1, 10)`.as("date"),logins:O`SUM(CASE WHEN ${z.type} IN (${O.join(Mi.map(d=>O`${d}`),O`, `)}) THEN 1 ELSE 0 END)`.as("logins"),signups:O`SUM(CASE WHEN ${z.type} = 'ss' THEN 1 ELSE 0 END)`.as("signups"),leaked_passwords:O`SUM(CASE WHEN ${z.type} IN (${O.join(K_.map(d=>O`${d}`),O`, `)}) THEN 1 ELSE 0 END)`.as("leaked_passwords")}).from(z).where(g(c(z.tenant_id,e),Tt(z.date,o),yt(z.date,`${s}T23:59:59.999Z`))).groupBy(O`substr(${z.date}, 1, 10)`).orderBy(O`substr(${z.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:O`COUNT(DISTINCT ${z.user_id})`.as("count")}).from(z).where(g(c(z.tenant_id,e),Tt(z.date,t),O`${z.type} IN (${O.join(Mi.map(o=>O`${o}`),O`, `)})`));return Number(i==null?void 0:i.count)||0}}}const Q_={"active-users":["s","seacft"],logins:["s","f","fp"],signups:["ss","fs"],"refresh-tokens":["seacft","fertft"],sessions:["slo"]},G_={"active-users":{alias:"active_users",type:"UInt64",agg:"uniq"},logins:{alias:"logins",type:"UInt64",agg:"count"},signups:{alias:"signups",type:"UInt64",agg:"count"},"refresh-tokens":{alias:"refresh_tokens",type:"UInt64",agg:"count"},sessions:{alias:"sessions",type:"UInt64",agg:"count"}};function W_(n){switch(n){case"hour":return O`substr(${z.date}, 1, 13)`;case"month":return O`substr(${z.date}, 1, 7)`;case"day":return O`substr(${z.date}, 1, 10)`;case"week":return O`date(substr(${z.date}, 1, 10), '-' || ((cast(strftime('%w', substr(${z.date}, 1, 10)) as integer) + 6) % 7) || ' days')`;default:throw new Error(`Unsupported interval '${n}' for SQL analytics adapter`)}}function Gn(n){return`"${n.replace(/"/g,'""')}"`}function X_(n){switch(n){case"connection":return z.connection;case"client_id":return z.client_id;case"user_type":return z.strategy_type;case"event":return z.type;case"time":throw new Error("time dimension handled separately")}}function Y_(n){return{async query(e,t,i){var G,W,ie,Me;const o=Date.now(),s=Q_[t],l=G_[t],d=[c(z.tenant_id,e),Tt(z.date,i.from),Qe(z.date,i.to),De(z.type,s)];(G=i.filters.connection)!=null&&G.length&&d.push(De(z.connection,i.filters.connection)),(W=i.filters.client_id)!=null&&W.length&&d.push(De(z.client_id,i.filters.client_id)),(ie=i.filters.user_type)!=null&&ie.length&&d.push(De(z.strategy_type,i.filters.user_type)),(Me=i.filters.user_id)!=null&&Me.length&&d.push(De(z.user_id,i.filters.user_id));const u={},f=[],p=[];for(const Se of i.group_by)if(Se==="time"){const Ee=W_(i.interval);u.time=Ee,f.push(Ee),p.push({name:"time",type:i.interval==="hour"?"DateTime":"Date"})}else{const Ee=X_(Se);u[Se]=Ee,f.push(Ee),p.push({name:Se,type:"String"})}u[l.alias]=l.agg==="uniq"?O`COUNT(DISTINCT ${z.user_id})`:O`COUNT(*)`,p.push({name:l.alias,type:l.type});let m=n.select(u).from(z).where(g(...d));f.length>0&&(m=m.groupBy(...f));const y=new Set([...Object.keys(u)]);if(i.order_by){const Se=i.order_by.startsWith("-"),Ee=Se?i.order_by.slice(1):i.order_by;if(!y.has(Ee))throw new Error(`Invalid order_by column '${Ee}' for analytics query`);const it=Gn(Ee);m=m.orderBy(O.raw(`${it} ${Se?"DESC":"ASC"}`))}else i.group_by[0]==="time"?m=m.orderBy(O.raw(`${Gn("time")} ASC`)):m=m.orderBy(O.raw(`${Gn(l.alias)} DESC`));m=m.limit(i.limit).offset(i.offset);const T=(await m.all()).map(Se=>{const Ee={};for(const it of p){const rt=Se[it.name];Ee[it.name]=it.type==="UInt64"?Number(rt)||0:rt??""}return Ee});return{meta:p,data:T,rows:T.length,rows_before_limit_at_least:T.length,statistics:{elapsed:(Date.now()-o)/1e3}}}}}function Bi(n){return{...n,payload:F(n.payload,{})}}function eu(n){return{async create(e,t){const i=Le(),o=new Date().toISOString();return await n.insert(M).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:o,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(M).where(De(M.id,e)).all()).map(Bi)},async getUnprocessed(e){const t=new Date().toISOString();return(await n.select().from(M).where(g(Ce(M.processed_at),$e(Ce(M.next_retry_at),yt(M.next_retry_at,t)),$e(Ce(M.claimed_by),yt(M.claim_expires_at,t)))).orderBy(M.created_at,M.id).limit(e).all()).map(Bi)},async claimEvents(e,t,i){if(e.length===0)return[];const o=new Date().toISOString(),s=new Date(Date.now()+i).toISOString();return await n.update(M).set({claimed_by:t,claim_expires_at:s}).where(g(De(M.id,e),Ce(M.processed_at),$e(Ce(M.claimed_by),yt(M.claim_expires_at,o)))),(await n.select({id:M.id}).from(M).where(g(De(M.id,e),c(M.claimed_by,t))).all()).map(d=>d.id)},async markProcessed(e){e.length!==0&&await n.update(M).set({processed_at:new Date().toISOString()}).where(De(M.id,e))},async markRetry(e,t,i){await n.update(M).set({error:t,next_retry_at:i,retry_count:O`${M.retry_count} + 1`,claimed_by:null,claim_expires_at:null}).where(c(M.id,e))},async cleanup(e){return(await n.delete(M).where(g(O`${M.processed_at} IS NOT NULL`,yt(M.processed_at,e))).returning()).length},async deadLetter(e,t){const i=new Date().toISOString();await n.update(M).set({processed_at:i,dead_lettered_at:i,final_error:t}).where(c(M.id,e))},async listFailed(e,t={}){const{page:i=0,per_page:o=50,include_totals:s=!1}=t,d=(await n.select().from(M).where(g(c(M.tenant_id,e),cn(M.dead_lettered_at))).orderBy(se(M.dead_lettered_at),he(M.id)).offset(i*o).limit(o).all()).map(f=>({...F(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(s){const[f]=await n.select({total:ge()}).from(M).where(g(c(M.tenant_id,e),cn(M.dead_lettered_at)));u=Number((f==null?void 0:f.total)??d.length)}return{events:d,start:i*o,limit:o,length:u}},async replay(e,t){return(await n.update(M).set({processed_at:null,dead_lettered_at:null,final_error:null,retry_count:0,next_retry_at:null,error:null}).where(g(c(M.id,e),c(M.tenant_id,t),cn(M.dead_lettered_at))).returning()).length>0}}}const tu=7*24*60*60*1e3;function nu(n){return async e=>{const t=Date.now()-tu;try{let i=[$e(Qe(J.expires_at_ts,t),Qe(J.idle_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)),i=[$e(Qe(ae.expires_at_ts,t),Qe(ae.idle_expires_at_ts,t))],e!=null&&e.tenant_id&&i.push(c(ae.tenant_id,e.tenant_id)),e!=null&&e.user_id&&i.push(c(ae.user_id,e.user_id)),await n.delete(ae).where(g(...i)),i=[Qe(Y.expires_at_ts,t)],e!=null&&e.tenant_id&&i.push(c(Y.tenant_id,e.tenant_id)),await n.delete(Y).where(g(...i))}catch(i){console.error("Session cleanup error:",i)}}}function iu(n,e={useTransactions:!0}){const t={actions:er(),actionExecutions:tr(),actionVersions:nr(),branding:vr(n),clients:wr(n),clientConnections:Nr(n),clientGrants:Or(n),clientRegistrationTokens:n_(n),codes:i_(n),connections:a_(n),customDomains:s_(n),customText:r_(n),emailProviders:l_(n),emailTemplates:d_(n),flows:c_(n),forms:__(n),hookCode:f_(n),hooks:m_(n),invites:v_(n),keys:w_(n),loginSessions:N_(n),logs:b_(n),authenticationMethods:x_(n),organizations:O_(n),passwords:T_(n),promptSettings:A_(n),refreshTokens:C_(n),resourceServers:L_(n),rolePermissions:R_(n),userPermissions:U_(n),roles:z_(n),sessions:M_(n),sessionCleanup:nu(n),tenants:q_(n),themes:$_(n),universalLoginTemplates:j_(n),users:V_(n),userRoles:Z_(n),userOrganizations:H_(n),stats:J_(n),analytics:Y_(n),outbox:eu(n),async transaction(i){if(e.useTransactions===!1)return i(t);await n.run(O`BEGIN`);try{const o=await i(t);return await n.run(O`COMMIT`),o}catch(o){throw await n.run(O`ROLLBACK`),o}}};return t}exports.default=iu;exports.sqlite=fr;
13
+ WHERE tenant_id = ${e} AND client_id = ${i}`);return(o.changes??((l=o.meta)==null?void 0:l.changes)??0)>0}}}let Er="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",xr=n=>crypto.getRandomValues(new Uint8Array(n)),kr=(n,e,t)=>{let i=256-256%n.length;if(i===256){let s=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]&s],d.length>=l)return d}}}let o=Math.ceil(1.6*256*e/i);return(s=e)=>{if(!s)return"";let l="";for(;;){let d=t(o),u=o;for(;u--;)if(d[u]<i&&(l+=n[d[u]%n.length],l.length>=s))return l}}},Or=(n,e=21)=>kr(n,e|0,xr),Le=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=Er[t[n]&63];return e};function Ln(n){const{tenant_id:e,scope:t,authorization_details_types:i,allow_any_organization:o,is_system:s,...l}=n;return G({...l,scope:z(t,[]),authorization_details_types:z(i,[]),allow_any_organization:!!o,is_system:!!s})}function Ar(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||Le(),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(ye).values(s),Ln({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(ye).where(g(c(ye.tenant_id,e),c(ye.id,t))).get();return i?Ln(i):null},async update(e,t,i){const{scope:o,authorization_details_types:s,allow_any_organization:l,is_system:d,...u}=i,f={...u,updated_at:new Date().toISOString()};return o!==void 0&&(f.scope=JSON.stringify(o)),s!==void 0&&(f.authorization_details_types=JSON.stringify(s)),l!==void 0&&(f.allow_any_organization=l?1:0),d!==void 0&&(f.is_system=d?1:0),(await n.update(ye).set(f).where(g(c(ye.tenant_id,e),c(ye.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?Qe(ye,d,["client_id","audience"]):void 0,f=u?g(c(ye.tenant_id,e),u):c(ye.tenant_id,e);let p=n.select().from(ye).where(f).$dynamic();if(l!=null&&l.sort_by){const A=ye[l.sort_by];A&&(p=p.orderBy(l.sort_order==="desc"?se(A):he(A)))}else p=p.orderBy(he(ye.created_at));const y=(await p.offset(i*o).limit(o)).map(Ln);if(!s)return{client_grants:y};const[E]=await n.select({count:ge()}).from(ye).where(f);return{client_grants:y,start:i*o,limit:o,length:Number((E==null?void 0:E.count)??0)}},async remove(e,t){return(await n.delete(ye).where(g(c(ye.tenant_id,e),c(ye.id,t))).returning()).length>0}}}function Tr(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 o=0,i=Object.getOwnPropertySymbols(n);o<i.length;o++)e.indexOf(i[o])<0&&Object.prototype.propertyIsEnumerable.call(n,i[o])&&(t[i[o]]=n[i[o]]);return t}function Ir(n,e){var t;return((t=n==null?void 0:n._def)===null||t===void 0?void 0:t.typeName)===e}function Lt(n,e){const t=n.ZodType.prototype[e];n.ZodType.prototype[e]=function(...i){const o=t.apply(this,i);return o._def.openapi=this._def.openapi,o}}function Cr(n){if(typeof n.ZodType.prototype.openapi<"u")return;n.ZodType.prototype.openapi=function(o,s){var l,d,u,f,p,m;const y=typeof o=="string"?s:o,E=y??{},{param:A}=E,J=Tr(E,["param"]),Q=Object.assign(Object.assign({},(l=this._def.openapi)===null||l===void 0?void 0:l._internal),typeof o=="string"?{refId:o}:void 0),ie=Object.assign(Object.assign(Object.assign({},(d=this._def.openapi)===null||d===void 0?void 0:d.metadata),J),!((f=(u=this._def.openapi)===null||u===void 0?void 0:u.metadata)===null||f===void 0)&&f.param||A?{param:Object.assign(Object.assign({},(m=(p=this._def.openapi)===null||p===void 0?void 0:p.metadata)===null||m===void 0?void 0:m.param),A)}:void 0),Pe=new this.constructor(Object.assign(Object.assign({},this._def),{openapi:Object.assign(Object.assign({},Object.keys(Q).length>0?{_internal:Q}:void 0),Object.keys(ie).length>0?{metadata:ie}:void 0)}));if(Ir(this,"ZodObject")){const Ne=this.extend;Pe.extend=function(...Ee){var it,rt,En,xn,kn,On,An;const Tn=Ne.apply(this,Ee);return Tn._def.openapi={_internal:{extendedFrom:!((rt=(it=this._def.openapi)===null||it===void 0?void 0:it._internal)===null||rt===void 0)&&rt.refId?{refId:(xn=(En=this._def.openapi)===null||En===void 0?void 0:En._internal)===null||xn===void 0?void 0:xn.refId,schema:this}:(On=(kn=this._def.openapi)===null||kn===void 0?void 0:kn._internal)===null||On===void 0?void 0:On.extendedFrom},metadata:(An=Tn._def.openapi)===null||An===void 0?void 0:An.metadata},Tn}}return Pe},Lt(n,"optional"),Lt(n,"nullable"),Lt(n,"default"),Lt(n,"transform"),Lt(n,"refine");const e=n.ZodObject.prototype.deepPartial;n.ZodObject.prototype.deepPartial=function(){const o=this._def.shape(),s=e.apply(this),l=s._def.shape();return Object.entries(l).forEach(([d,u])=>{var f,p;u._def.openapi=(p=(f=o[d])===null||f===void 0?void 0:f._def)===null||p===void 0?void 0:p.openapi}),s._def.openapi=void 0,s};const t=n.ZodObject.prototype.pick;n.ZodObject.prototype.pick=function(...o){const s=t.apply(this,o);return s._def.openapi=void 0,s};const i=n.ZodObject.prototype.omit;n.ZodObject.prototype.omit=function(...o){const s=i.apply(this,o);return s._def.openapi=void 0,s}}new Set(".\\+*[^]$()");var K;(function(n){n.assertEqual=o=>{};function e(o){}n.assertIs=e;function t(o){throw new Error}n.assertNever=t,n.arrayToEnum=o=>{const s={};for(const l of o)s[l]=l;return s},n.getValidEnumValues=o=>{const s=n.objectKeys(o).filter(d=>typeof o[o[d]]!="number"),l={};for(const d of s)l[d]=o[d];return n.objectValues(l)},n.objectValues=o=>n.objectKeys(o).map(function(s){return o[s]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const s=[];for(const l in o)Object.prototype.hasOwnProperty.call(o,l)&&s.push(l);return s},n.find=(o,s)=>{for(const l of o)if(s(l))return l},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function i(o,s=" | "){return o.map(l=>typeof l=="string"?`'${l}'`:l).join(s)}n.joinValues=i,n.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(K||(K={}));var ei;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(ei||(ei={}));const T=K.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),at=n=>{switch(typeof n){case"undefined":return T.undefined;case"string":return T.string;case"number":return Number.isNaN(n)?T.nan:T.number;case"boolean":return T.boolean;case"function":return T.function;case"bigint":return T.bigint;case"symbol":return T.symbol;case"object":return Array.isArray(n)?T.array:n===null?T.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?T.promise:typeof Map<"u"&&n instanceof Map?T.map:typeof Set<"u"&&n instanceof Set?T.set:typeof Date<"u"&&n instanceof Date?T.date:T.object;default:return T.unknown}},N=K.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 et 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(s){return s.message},i={_errors:[]},o=s=>{for(const l of s.issues)if(l.code==="invalid_union")l.unionErrors.map(o);else if(l.code==="invalid_return_type")o(l.returnTypeError);else if(l.code==="invalid_arguments")o(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 o(this),i}static assert(e){if(!(e instanceof et))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,K.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const o of this.issues)if(o.path.length>0){const s=o.path[0];t[s]=t[s]||[],t[s].push(e(o))}else i.push(e(o));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}et.create=n=>new et(n);const fn=(n,e)=>{let t;switch(n.code){case N.invalid_type:n.received===T.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case N.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,K.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:t=`Unrecognized key(s) in object: ${K.joinValues(n.keys,", ")}`;break;case N.invalid_union:t="Invalid input";break;case N.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${K.joinValues(n.options)}`;break;case N.invalid_enum_value:t=`Invalid enum value. Expected ${K.joinValues(n.options)}, received '${n.received}'`;break;case N.invalid_arguments:t="Invalid function arguments";break;case N.invalid_return_type:t="Invalid function return type";break;case N.invalid_date:t="Invalid date";break;case N.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}"`:K.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case N.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 N.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 N.custom:t="Invalid input";break;case N.invalid_intersection_types:t="Intersection results could not be merged";break;case N.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case N.not_finite:t="Number must be finite";break;default:t=e.defaultError,K.assertNever(n)}return{message:t}};let Dr=fn;function us(){return Dr}const ps=n=>{const{data:e,path:t,errorMaps:i,issueData:o}=n,s=[...t,...o.path||[]],l={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.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{...o,path:s,message:d}};function k(n,e){const t=us(),i=ps({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===fn?void 0:fn].filter(o=>!!o)});n.common.issues.push(i)}class Ae{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 o of t){if(o.status==="aborted")return R;o.status==="dirty"&&e.dirty(),i.push(o.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const o of t){const s=await o.key,l=await o.value;i.push({key:s,value:l})}return Ae.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const o of t){const{key:s,value:l}=o;if(s.status==="aborted"||l.status==="aborted")return R;s.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof l.value<"u"||o.alwaysSet)&&(i[s.value]=l.value)}return{status:e.value,value:i}}}const R=Object.freeze({status:"aborted"}),kt=n=>({status:"dirty",value:n}),ze=n=>({status:"valid",value:n}),ti=n=>n.status==="aborted",ni=n=>n.status==="dirty",Nt=n=>n.status==="valid",qt=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 tt{constructor(e,t,i,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=o}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 Ti=(n,e)=>{if(Nt(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 et(n.common.issues);return this._error=t,this._error}}};function q(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:o}=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:o}:{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:o}}class ${get description(){return this._def.description}_getType(e){return at(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:at(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ae,ctx:{common:e.parent.common,data:e.data,parsedType:at(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(qt(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:at(e)},o=this._parseSync({data:e,path:i.path,parent:i});return Ti(i,o)}"~validate"(e){var i,o;const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:at(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return Nt(s)?{value:s.value}:{issues:t.common.issues}}catch(s){(o=(i=s==null?void 0:s.message)==null?void 0:i.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>Nt(s)?{value:s.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:at(e)},o=this._parse({data:e,path:i.path,parent:i}),s=await(qt(o)?o:Promise.resolve(o));return Ti(i,s)}refine(e,t){const i=o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t;return this._refinement((o,s)=>{const l=e(o),d=()=>s.addIssue({code:N.custom,...i(o)});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,o)=>e(i)?!0:(o.addIssue(typeof t=="function"?t(i,o):t),!1))}_refinement(e){return new nt({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 Ye.create(this,this._def)}nullable(){return ft.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Je.create(this)}promise(){return Gt.create(this,this._def)}or(e){return Vt.create([this,e],this._def)}and(e){return Ht.create(this,e,this._def)}transform(e){return new nt({...q(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Jt({...q(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new Ni({typeName:U.ZodBranded,type:this,...q(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Qt({...q(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 Sn.create(this,e)}readonly(){return Xt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Lr=/^c[^\s-]{8,}$/i,Rr=/^[0-9a-z]+$/,Ur=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fr=/^[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,zr=/^[a-z0-9_-]{21}$/i,Mr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Pr=/^[-+]?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)?)??$/,qr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Br="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Rn;const $r=/^(?:(?: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])$/,jr=/^(?:(?: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])$/,Vr=/^(([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]))$/,Hr=/^(([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])$/,Zr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Kr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fs="((\\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])))",Wr=new RegExp(`^${fs}$`);function hs(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 Gr(n){return new RegExp(`^${hs(n)}$`)}function gs(n){let e=`${fs}T${hs(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 Jr(n,e){return!!((e==="v4"||!e)&&$r.test(n)||(e==="v6"||!e)&&Vr.test(n))}function Qr(n,e){if(!Mr.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,"="),o=JSON.parse(atob(i));return!(typeof o!="object"||o===null||"typ"in o&&(o==null?void 0:o.typ)!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Xr(n,e){return!!((e==="v4"||!e)&&jr.test(n)||(e==="v6"||!e)&&Hr.test(n))}class Xe extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==T.string){const s=this._getOrReturnCtx(e);return k(s,{code:N.invalid_type,expected:T.string,received:s.parsedType}),R}const i=new Ae;let o;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),i.dirty());else if(s.kind==="length"){const l=e.data.length>s.value,d=e.data.length<s.value;(l||d)&&(o=this._getOrReturnCtx(e,o),l?k(o,{code:N.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):d&&k(o,{code:N.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),i.dirty())}else if(s.kind==="email")qr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"email",code:N.invalid_string,message:s.message}),i.dirty());else if(s.kind==="emoji")Rn||(Rn=new RegExp(Br,"u")),Rn.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"emoji",code:N.invalid_string,message:s.message}),i.dirty());else if(s.kind==="uuid")Fr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"uuid",code:N.invalid_string,message:s.message}),i.dirty());else if(s.kind==="nanoid")zr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"nanoid",code:N.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid")Lr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid",code:N.invalid_string,message:s.message}),i.dirty());else if(s.kind==="cuid2")Rr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid2",code:N.invalid_string,message:s.message}),i.dirty());else if(s.kind==="ulid")Ur.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ulid",code:N.invalid_string,message:s.message}),i.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),k(o,{validation:"url",code:N.invalid_string,message:s.message}),i.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"regex",code:N.invalid_string,message:s.message}),i.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),k(o,{code:N.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),i.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:N.invalid_string,validation:{startsWith:s.value},message:s.message}),i.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:N.invalid_string,validation:{endsWith:s.value},message:s.message}),i.dirty()):s.kind==="datetime"?gs(s).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:N.invalid_string,validation:"datetime",message:s.message}),i.dirty()):s.kind==="date"?Wr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:N.invalid_string,validation:"date",message:s.message}),i.dirty()):s.kind==="time"?Gr(s).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:N.invalid_string,validation:"time",message:s.message}),i.dirty()):s.kind==="duration"?Pr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"duration",code:N.invalid_string,message:s.message}),i.dirty()):s.kind==="ip"?Jr(e.data,s.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ip",code:N.invalid_string,message:s.message}),i.dirty()):s.kind==="jwt"?Qr(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"jwt",code:N.invalid_string,message:s.message}),i.dirty()):s.kind==="cidr"?Xr(e.data,s.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cidr",code:N.invalid_string,message:s.message}),i.dirty()):s.kind==="base64"?Zr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64",code:N.invalid_string,message:s.message}),i.dirty()):s.kind==="base64url"?Kr.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64url",code:N.invalid_string,message:s.message}),i.dirty()):K.assertNever(s);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(o=>e.test(o),{validation:t,code:N.invalid_string,...C.errToObj(i)})}_addCheck(e){return new Xe({...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 Xe({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Xe({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Xe({...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}}Xe.create=n=>new Xe({checks:[],typeName:U.ZodString,coerce:(n==null?void 0:n.coerce)??!1,...q(n)});function Yr(n,e){const t=(n.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,o=t>i?t:i,s=Number.parseInt(n.toFixed(o).replace(".","")),l=Number.parseInt(e.toFixed(o).replace(".",""));return s%l/10**o}class St extends ${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)!==T.number){const s=this._getOrReturnCtx(e);return k(s,{code:N.invalid_type,expected:T.number,received:s.parsedType}),R}let i;const o=new Ae;for(const s of this._def.checks)s.kind==="int"?K.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:N.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:N.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:N.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Yr(e.data,s.value)!==0&&(i=this._getOrReturnCtx(e,i),k(i,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),k(i,{code:N.not_finite,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.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,o){return new St({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(o)}]})}_addCheck(e){return new St({...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"&&K.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)}}St.create=n=>new St({checks:[],typeName:U.ZodNumber,coerce:(n==null?void 0:n.coerce)||!1,...q(n)});class Tt extends ${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)!==T.bigint)return this._getInvalidInput(e);let i;const o=new Ae;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:N.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(i=this._getOrReturnCtx(e,i),k(i,{code:N.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),k(i,{code:N.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):K.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return k(t,{code:N.invalid_type,expected:T.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,o){return new Tt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:C.toString(o)}]})}_addCheck(e){return new Tt({...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}}Tt.create=n=>new Tt({checks:[],typeName:U.ZodBigInt,coerce:(n==null?void 0:n.coerce)??!1,...q(n)});class hn extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==T.boolean){const i=this._getOrReturnCtx(e);return k(i,{code:N.invalid_type,expected:T.boolean,received:i.parsedType}),R}return ze(e.data)}}hn.create=n=>new hn({typeName:U.ZodBoolean,coerce:(n==null?void 0:n.coerce)||!1,...q(n)});class Bt extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==T.date){const s=this._getOrReturnCtx(e);return k(s,{code:N.invalid_type,expected:T.date,received:s.parsedType}),R}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return k(s,{code:N.invalid_date}),R}const i=new Ae;let o;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:N.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),i.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:N.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),i.dirty()):K.assertNever(s);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Bt({...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}}Bt.create=n=>new Bt({checks:[],coerce:(n==null?void 0:n.coerce)||!1,typeName:U.ZodDate,...q(n)});class ii extends ${_parse(e){if(this._getType(e)!==T.symbol){const i=this._getOrReturnCtx(e);return k(i,{code:N.invalid_type,expected:T.symbol,received:i.parsedType}),R}return ze(e.data)}}ii.create=n=>new ii({typeName:U.ZodSymbol,...q(n)});class gn extends ${_parse(e){if(this._getType(e)!==T.undefined){const i=this._getOrReturnCtx(e);return k(i,{code:N.invalid_type,expected:T.undefined,received:i.parsedType}),R}return ze(e.data)}}gn.create=n=>new gn({typeName:U.ZodUndefined,...q(n)});class $t extends ${_parse(e){if(this._getType(e)!==T.null){const i=this._getOrReturnCtx(e);return k(i,{code:N.invalid_type,expected:T.null,received:i.parsedType}),R}return ze(e.data)}}$t.create=n=>new $t({typeName:U.ZodNull,...q(n)});class jt extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return ze(e.data)}}jt.create=n=>new jt({typeName:U.ZodAny,...q(n)});class mn extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return ze(e.data)}}mn.create=n=>new mn({typeName:U.ZodUnknown,...q(n)});class st extends ${_parse(e){const t=this._getOrReturnCtx(e);return k(t,{code:N.invalid_type,expected:T.never,received:t.parsedType}),R}}st.create=n=>new st({typeName:U.ZodNever,...q(n)});class oi extends ${_parse(e){if(this._getType(e)!==T.undefined){const i=this._getOrReturnCtx(e);return k(i,{code:N.invalid_type,expected:T.void,received:i.parsedType}),R}return ze(e.data)}}oi.create=n=>new oi({typeName:U.ZodVoid,...q(n)});class Je extends ${_parse(e){const{ctx:t,status:i}=this._processInputParams(e),o=this._def;if(t.parsedType!==T.array)return k(t,{code:N.invalid_type,expected:T.array,received:t.parsedType}),R;if(o.exactLength!==null){const l=t.data.length>o.exactLength.value,d=t.data.length<o.exactLength.value;(l||d)&&(k(t,{code:l?N.too_big:N.too_small,minimum:d?o.exactLength.value:void 0,maximum:l?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),i.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(k(t,{code:N.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),i.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(k(t,{code:N.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((l,d)=>o.type._parseAsync(new tt(t,l,t.path,d)))).then(l=>Ae.mergeArray(i,l));const s=[...t.data].map((l,d)=>o.type._parseSync(new tt(t,l,t.path,d)));return Ae.mergeArray(i,s)}get element(){return this._def.type}min(e,t){return new Je({...this._def,minLength:{value:e,message:C.toString(t)}})}max(e,t){return new Je({...this._def,maxLength:{value:e,message:C.toString(t)}})}length(e,t){return new Je({...this._def,exactLength:{value:e,message:C.toString(t)}})}nonempty(e){return this.min(1,e)}}Je.create=(n,e)=>new Je({type:n,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...q(e)});function Et(n){if(n instanceof de){const e={};for(const t in n.shape){const i=n.shape[t];e[t]=Ye.create(Et(i))}return new de({...n._def,shape:()=>e})}else return n instanceof Je?new Je({...n._def,type:Et(n.element)}):n instanceof Ye?Ye.create(Et(n.unwrap())):n instanceof ft?ft.create(Et(n.unwrap())):n instanceof ut?ut.create(n.items.map(e=>Et(e))):n}class de extends ${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=K.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==T.object){const f=this._getOrReturnCtx(e);return k(f,{code:N.invalid_type,expected:T.object,received:f.parsedType}),R}const{status:i,ctx:o}=this._processInputParams(e),{shape:s,keys:l}=this._getCached(),d=[];if(!(this._def.catchall instanceof st&&this._def.unknownKeys==="strip"))for(const f in o.data)l.includes(f)||d.push(f);const u=[];for(const f of l){const p=s[f],m=o.data[f];u.push({key:{status:"valid",value:f},value:p._parse(new tt(o,m,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof st){const f=this._def.unknownKeys;if(f==="passthrough")for(const p of d)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(f==="strict")d.length>0&&(k(o,{code:N.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 m=o.data[p];u.push({key:{status:"valid",value:p},value:f._parse(new tt(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const p of u){const m=await p.key,y=await p.value;f.push({key:m,value:y,alwaysSet:p.alwaysSet})}return f}).then(f=>Ae.mergeObjectSync(i,f)):Ae.mergeObjectSync(i,u)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new de({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var s,l;const o=((l=(s=this._def).errorMap)==null?void 0:l.call(s,t,i).message)??i.defaultError;return t.code==="unrecognized_keys"?{message:C.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new de({...this._def,unknownKeys:"strip"})}passthrough(){return new de({...this._def,unknownKeys:"passthrough"})}extend(e){return new de({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new de({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 de({...this._def,catchall:e})}pick(e){const t={};for(const i of K.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new de({...this._def,shape:()=>t})}omit(e){const t={};for(const i of K.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new de({...this._def,shape:()=>t})}deepPartial(){return Et(this)}partial(e){const t={};for(const i of K.objectKeys(this.shape)){const o=this.shape[i];e&&!e[i]?t[i]=o:t[i]=o.optional()}return new de({...this._def,shape:()=>t})}required(e){const t={};for(const i of K.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let s=this.shape[i];for(;s instanceof Ye;)s=s._def.innerType;t[i]=s}return new de({...this._def,shape:()=>t})}keyof(){return ms(K.objectKeys(this.shape))}}de.create=(n,e)=>new de({shape:()=>n,unknownKeys:"strip",catchall:st.create(),typeName:U.ZodObject,...q(e)});de.strictCreate=(n,e)=>new de({shape:()=>n,unknownKeys:"strict",catchall:st.create(),typeName:U.ZodObject,...q(e)});de.lazycreate=(n,e)=>new de({shape:n,unknownKeys:"strip",catchall:st.create(),typeName:U.ZodObject,...q(e)});class Vt extends ${_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function o(s){for(const d of s)if(d.result.status==="valid")return d.result;for(const d of s)if(d.result.status==="dirty")return t.common.issues.push(...d.ctx.common.issues),d.result;const l=s.map(d=>new et(d.ctx.common.issues));return k(t,{code:N.invalid_union,unionErrors:l}),R}if(t.common.async)return Promise.all(i.map(async s=>{const l={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:l}),ctx:l}})).then(o);{let s;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"&&!s&&(s={result:p,ctx:f}),f.common.issues.length&&l.push(f.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;const d=l.map(u=>new et(u));return k(t,{code:N.invalid_union,unionErrors:d}),R}}get options(){return this._def.options}}Vt.create=(n,e)=>new Vt({options:n,typeName:U.ZodUnion,...q(e)});const ot=n=>n instanceof yn?ot(n.schema):n instanceof nt?ot(n.innerType()):n instanceof Kt?[n.value]:n instanceof pt?n.options:n instanceof Wt?K.objectValues(n.enum):n instanceof Jt?ot(n._def.innerType):n instanceof gn?[void 0]:n instanceof $t?[null]:n instanceof Ye?[void 0,...ot(n.unwrap())]:n instanceof ft?[null,...ot(n.unwrap())]:n instanceof Ni||n instanceof Xt?ot(n.unwrap()):n instanceof Qt?ot(n._def.innerType):[];class Nn extends ${_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==T.object)return k(t,{code:N.invalid_type,expected:T.object,received:t.parsedType}),R;const i=this.discriminator,o=t.data[i],s=this.optionsMap.get(o);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(k(t,{code:N.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 o=new Map;for(const s of t){const l=ot(s.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(o.has(d))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(d)}`);o.set(d,s)}}return new Nn({typeName:U.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...q(i)})}}function ai(n,e){const t=at(n),i=at(e);if(n===e)return{valid:!0,data:n};if(t===T.object&&i===T.object){const o=K.objectKeys(e),s=K.objectKeys(n).filter(d=>o.indexOf(d)!==-1),l={...n,...e};for(const d of s){const u=ai(n[d],e[d]);if(!u.valid)return{valid:!1};l[d]=u.data}return{valid:!0,data:l}}else if(t===T.array&&i===T.array){if(n.length!==e.length)return{valid:!1};const o=[];for(let s=0;s<n.length;s++){const l=n[s],d=e[s],u=ai(l,d);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return t===T.date&&i===T.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class Ht extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e),o=(s,l)=>{if(ti(s)||ti(l))return R;const d=ai(s.value,l.value);return d.valid?((ni(s)||ni(l))&&t.dirty(),{status:t.value,value:d.data}):(k(i,{code:N.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(([s,l])=>o(s,l)):o(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Ht.create=(n,e,t)=>new Ht({left:n,right:e,typeName:U.ZodIntersection,...q(t)});class ut extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==T.array)return k(i,{code:N.invalid_type,expected:T.array,received:i.parsedType}),R;if(i.data.length<this._def.items.length)return k(i,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&i.data.length>this._def.items.length&&(k(i,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const s=[...i.data].map((l,d)=>{const u=this._def.items[d]||this._def.rest;return u?u._parse(new tt(i,l,i.path,d)):null}).filter(l=>!!l);return i.common.async?Promise.all(s).then(l=>Ae.mergeArray(t,l)):Ae.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new ut({...this._def,rest:e})}}ut.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ut({items:n,typeName:U.ZodTuple,rest:null,...q(e)})};class Zt extends ${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!==T.object)return k(i,{code:N.invalid_type,expected:T.object,received:i.parsedType}),R;const o=[],s=this._def.keyType,l=this._def.valueType;for(const d in i.data)o.push({key:s._parse(new tt(i,d,i.path,d)),value:l._parse(new tt(i,i.data[d],i.path,d)),alwaysSet:d in i.data});return i.common.async?Ae.mergeObjectAsync(t,o):Ae.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof $?new Zt({keyType:e,valueType:t,typeName:U.ZodRecord,...q(i)}):new Zt({keyType:Xe.create(),valueType:e,typeName:U.ZodRecord,...q(t)})}}class si extends ${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!==T.map)return k(i,{code:N.invalid_type,expected:T.map,received:i.parsedType}),R;const o=this._def.keyType,s=this._def.valueType,l=[...i.data.entries()].map(([d,u],f)=>({key:o._parse(new tt(i,d,i.path,[f,"key"])),value:s._parse(new tt(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}}}}si.create=(n,e,t)=>new si({valueType:e,keyType:n,typeName:U.ZodMap,...q(t)});class It extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==T.set)return k(i,{code:N.invalid_type,expected:T.set,received:i.parsedType}),R;const o=this._def;o.minSize!==null&&i.data.size<o.minSize.value&&(k(i,{code:N.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&i.data.size>o.maxSize.value&&(k(i,{code:N.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());const s=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)=>s._parse(new tt(i,u,i.path,f)));return i.common.async?Promise.all(d).then(u=>l(u)):l(d)}min(e,t){return new It({...this._def,minSize:{value:e,message:C.toString(t)}})}max(e,t){return new It({...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)}}It.create=(n,e)=>new It({valueType:n,minSize:null,maxSize:null,typeName:U.ZodSet,...q(e)});class yn extends ${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})}}yn.create=(n,e)=>new yn({getter:n,typeName:U.ZodLazy,...q(e)});class Kt extends ${_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return k(t,{received:t.data,code:N.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:e.data}}get value(){return this._def.value}}Kt.create=(n,e)=>new Kt({value:n,typeName:U.ZodLiteral,...q(e)});function ms(n,e){return new pt({values:n,typeName:U.ZodEnum,...q(e)})}class pt extends ${_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return k(t,{expected:K.joinValues(i),received:t.parsedType,code:N.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 k(t,{received:t.data,code:N.invalid_enum_value,options:i}),R}return ze(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 pt.create(e,{...this._def,...t})}exclude(e,t=this._def){return pt.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}pt.create=ms;class Wt extends ${_parse(e){const t=K.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==T.string&&i.parsedType!==T.number){const o=K.objectValues(t);return k(i,{expected:K.joinValues(o),received:i.parsedType,code:N.invalid_type}),R}if(this._cache||(this._cache=new Set(K.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const o=K.objectValues(t);return k(i,{received:i.data,code:N.invalid_enum_value,options:o}),R}return ze(e.data)}get enum(){return this._def.values}}Wt.create=(n,e)=>new Wt({values:n,typeName:U.ZodNativeEnum,...q(e)});class Gt extends ${unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==T.promise&&t.common.async===!1)return k(t,{code:N.invalid_type,expected:T.promise,received:t.parsedType}),R;const i=t.parsedType===T.promise?t.data:Promise.resolve(t.data);return ze(i.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Gt.create=(n,e)=>new Gt({type:n,typeName:U.ZodPromise,...q(e)});class nt extends ${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),o=this._def.effect||null,s={addIssue:l=>{k(i,l),l.fatal?t.abort():t.dirty()},get path(){return i.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){const l=o.transform(i.data,s);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"?kt(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"?kt(d.value):d}}if(o.type==="refinement"){const l=d=>{const u=o.refinement(d,s);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(o.type==="transform")if(i.common.async===!1){const l=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Nt(l))return R;const d=o.transform(l.value,s);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=>Nt(l)?Promise.resolve(o.transform(l.value,s)).then(d=>({status:t.value,value:d})):R);K.assertNever(o)}}nt.create=(n,e,t)=>new nt({schema:n,typeName:U.ZodEffects,effect:e,...q(t)});nt.createWithPreprocess=(n,e,t)=>new nt({schema:e,effect:{type:"preprocess",transform:n},typeName:U.ZodEffects,...q(t)});class Ye extends ${_parse(e){return this._getType(e)===T.undefined?ze(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ye.create=(n,e)=>new Ye({innerType:n,typeName:U.ZodOptional,...q(e)});class ft extends ${_parse(e){return this._getType(e)===T.null?ze(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ft.create=(n,e)=>new ft({innerType:n,typeName:U.ZodNullable,...q(e)});class Jt extends ${_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===T.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Jt.create=(n,e)=>new Jt({innerType:n,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...q(e)});class Qt extends ${_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return qt(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new et(i.common.issues)},input:i.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new et(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Qt.create=(n,e)=>new Qt({innerType:n,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...q(e)});class ri extends ${_parse(e){if(this._getType(e)!==T.nan){const i=this._getOrReturnCtx(e);return k(i,{code:N.invalid_type,expected:T.nan,received:i.parsedType}),R}return{status:"valid",value:e.data}}}ri.create=n=>new ri({typeName:U.ZodNaN,...q(n)});class Ni extends ${_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 Sn extends ${_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?R:s.status==="dirty"?(t.dirty(),kt(s.value)):this._def.out._parseAsync({data:s.value,path:i.path,parent:i})})();{const o=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?R:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:i.path,parent:i})}}static create(e,t){return new Sn({in:e,out:t,typeName:U.ZodPipeline})}}class Xt extends ${_parse(e){const t=this._def.innerType._parse(e),i=o=>(Nt(o)&&(o.value=Object.freeze(o.value)),o);return qt(t)?t.then(o=>i(o)):i(t)}unwrap(){return this._def.innerType}}Xt.create=(n,e)=>new Xt({innerType:n,typeName:U.ZodReadonly,...q(e)});function li(n,e={},t){return jt.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 a=Xe.create,x=St.create,h=hn.create,ys=$t.create,V=jt.create,Fe=mn.create;st.create;const S=Je.create,_=de.create,Me=Vt.create,Ct=Nn.create;Ht.create;ut.create;const M=Zt.create,I=Kt.create,b=pt.create,wt=Wt.create;Gt.create;Ye.create;ft.create;const vs=nt.createWithPreprocess,el=Object.freeze(Object.defineProperty({__proto__:null,DIRTY:kt,INVALID:R,OK:ze,ParseStatus:Ae,Schema:$,ZodAny:jt,ZodArray:Je,ZodBigInt:Tt,ZodBoolean:hn,ZodBranded:Ni,ZodCatch:Qt,ZodDate:Bt,ZodDefault:Jt,ZodDiscriminatedUnion:Nn,ZodEffects:nt,ZodEnum:pt,ZodError:et,get ZodFirstPartyTypeKind(){return U},ZodIntersection:Ht,ZodIssueCode:N,ZodLazy:yn,ZodLiteral:Kt,ZodMap:si,ZodNaN:ri,ZodNativeEnum:Wt,ZodNever:st,ZodNull:$t,ZodNullable:ft,ZodNumber:St,ZodObject:de,ZodOptional:Ye,ZodParsedType:T,ZodPipeline:Sn,ZodPromise:Gt,ZodReadonly:Xt,ZodRecord:Zt,ZodSchema:$,ZodSet:It,ZodString:Xe,ZodSymbol:ii,ZodTransformer:nt,ZodTuple:ut,ZodType:$,ZodUndefined:gn,ZodUnion:Vt,ZodUnknown:mn,ZodVoid:oi,addIssueToContext:k,any:V,array:S,boolean:h,custom:li,datetimeRegex:gs,defaultErrorMap:fn,discriminatedUnion:Ct,enum:b,getErrorMap:us,getParsedType:at,isAborted:ti,isAsync:qt,isDirty:ni,isValid:Nt,literal:I,makeIssue:ps,nativeEnum:wt,null:ys,number:x,object:_,get objectUtil(){return ei},preprocess:vs,record:M,string:a,union:Me,unknown:Fe,get util(){return K}},Symbol.toStringTag,{value:"Module"}));Cr(el);const He=_({created_at:a(),updated_at:a()}),ws=_({id:a(),version:a().optional()}),Ns=_({name:a(),version:a()}),Ss=_({name:a(),value:a().optional()}),bs=_({name:a().max(255),code:a().max(1e5),supported_triggers:S(ws).optional(),runtime:a().max(50).optional(),dependencies:S(Ns).optional(),secrets:S(Ss).optional(),is_system:h().optional(),inherit:h().optional()});bs.partial().extend({status:b(["draft","built"]).optional(),deployed_at:a().optional()});bs.extend({id:a(),tenant_id:a(),status:b(["draft","built"]).default("built"),deployed_at:a().optional(),secrets:S(_({name:a(),value:a().optional()})).optional(),...He.shape});const tl=a(),nl=b(["unspecified","pending","final","partial","canceled","suspended"]),il=_({id:a(),msg:a(),url:a().optional()}),ol=_({action_name:a(),error:il.nullable(),started_at:a(),ended_at:a()}),al=_({level:b(["log","info","warn","error","debug"]),message:a()}),sl=S(_({action_name:a(),lines:S(al)})),rl=_({id:a(),tenant_id:a(),trigger_id:tl,status:nl,results:S(ol),logs:sl.optional(),created_at:a(),updated_at:a()});rl.omit({tenant_id:!0,created_at:!0,updated_at:!0});const ll=_({action_id:a(),code:a().max(1e5),runtime:a().max(50).optional(),dependencies:S(Ns).optional(),secrets:S(Ss).optional(),supported_triggers:S(ws).optional(),deployed:h().default(!0)});ll.extend({id:a(),tenant_id:a(),number:x().int(),...He.shape});const dl=b(["user_action","admin_action","system","api"]),cl=_({type:b(["user","admin","system","api_key","client_credentials"]),id:a().optional(),email:a().optional(),org_id:a().optional(),org_name:a().optional(),scopes:S(a()).optional(),client_id:a().optional()}),_l=_({type:a(),id:a(),before:M(Fe()).optional(),after:M(Fe()).optional(),diff:M(_({old:Fe(),new:Fe()})).optional()}),ul=_({method:a(),path:a(),query:M(a()).optional(),body:Fe().optional(),ip:a(),user_agent:a().optional(),correlation_id:a().optional()}),pl=_({status_code:x(),body:Fe().optional()}),fl=_({country_code:a(),city_name:a(),latitude:a(),longitude:a(),time_zone:a(),continent_code:a()}),hl=_({name:a(),version:a(),env:M(a()).optional()}),gl=_({tenant_id:a(),event_type:a(),log_type:a(),description:a().optional(),category:dl,actor:cl,target:_l,request:ul,response:pl.optional(),connection:a().optional(),strategy:a().optional(),strategy_type:a().optional(),audience:a().optional(),scope:a().optional(),location:fl.optional(),auth0_client:hl.optional(),hostname:a(),is_mobile:h().optional(),timestamp:a()});gl.extend({id:a()});b(["AUTH0","EMAIL","REDIRECT"]);b(["CREATE_USER","GET_USER","UPDATE_USER","SEND_REQUEST","SEND_EMAIL"]);b(["VERIFY_EMAIL"]);const ml=_({require_mx_record:h().optional(),block_aliases:h().optional(),block_free_emails:h().optional(),block_disposable_emails:h().optional(),blocklist:S(a()).optional(),allowlist:S(a()).optional()}),yl=_({id:a(),alias:a().max(100).optional(),type:I("AUTH0"),action:I("UPDATE_USER"),allow_failure:h().optional(),mask_output:h().optional(),params:_({connection_id:a().optional(),user_id:a(),changes:M(a(),V())})}),vl=_({id:a(),alias:a().max(100).optional(),type:I("EMAIL"),action:I("VERIFY_EMAIL"),allow_failure:h().optional(),mask_output:h().optional(),params:_({email:a(),rules:ml.optional()})}),wl=b(["change-email","account","custom"]),Nl=_({id:a(),alias:a().max(100).optional(),type:I("REDIRECT"),action:I("REDIRECT_USER"),allow_failure:h().optional(),mask_output:h().optional(),params:_({target:wl.openapi({description:"The predefined target to redirect to, or 'custom' for a custom URL"}),custom_url:a().optional().openapi({description:"Custom URL to redirect to when target is 'custom'"})})}),Sl=Me([yl,vl,Nl]),bl=_({name:a().min(1).max(150).openapi({description:"The name of the flow"}),actions:S(Sl).optional().default([]).openapi({description:"The list of actions to execute in sequence"})});bl.extend({...He.shape,id:a().openapi({description:"Unique identifier for the flow",example:"af_12tMpdJ3iek7svMyZkSh5M"})});_({page:a().min(0).optional().default("0").transform(n=>parseInt(n,10)).openapi({description:"The page number where 0 is the first page"}),per_page:a().min(1).optional().default("10").transform(n=>parseInt(n,10)).openapi({description:"The number of items per page"}),include_totals:a().optional().default("false").transform(n=>n==="true").openapi({description:"If the total number of items should be included in the response"}),sort:a().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:a().optional().openapi({description:"A lucene query string used to filter the results"})});_({start:x(),limit:x(),length:x(),total:x().optional()});const El=_({email:a().optional(),email_verified:h().optional(),name:a().optional(),username:a().optional(),given_name:a().optional(),phone_number:a().optional(),phone_verified:h().optional(),family_name:a().optional()}).catchall(V()),xl=_({connection:a(),user_id:a(),provider:a(),isSocial:h(),email:a().optional(),email_verified:h().optional(),phone_number:a().optional(),phone_verified:h().optional(),username:a().optional(),access_token:a().optional(),access_token_secret:a().optional(),refresh_token:a().optional(),profileData:El.optional()}),kl=_({formatted:a().optional(),street_address:a().optional(),locality:a().optional(),region:a().optional(),postal_code:a().optional(),country:a().optional()}).optional(),Es=_({email:a().optional().transform(n=>n&&n.toLowerCase()),username:a().refine(n=>!n.includes("@"),{message:'Usernames must not contain "@". Use the email field for email addresses.'}).optional(),phone_number:a().optional(),phone_verified:h().optional(),given_name:a().optional(),family_name:a().optional(),nickname:a().optional(),name:a().optional(),picture:a().optional(),locale:a().optional(),linked_to:a().optional(),profileData:a().optional(),user_id:a().optional(),app_metadata:V().default({}).optional(),user_metadata:V().default({}).optional(),middle_name:a().optional(),preferred_username:a().optional(),profile:a().optional(),website:a().optional(),gender:a().optional(),birthdate:a().optional(),zoneinfo:a().optional(),address:kl}),Ol=Es.extend({email_verified:h().default(!1),verify_email:h().optional(),last_ip:a().optional(),last_login:a().optional(),user_id:a().optional(),provider:a().optional(),connection:a(),is_social:h().optional(),registration_completed_at:a().optional(),password:_({hash:a(),algorithm:a()}).optional()}),Al=_({...Ol.omit({password:!0}).shape,...He.shape,user_id:a(),provider:a(),is_social:h(),email:a().optional(),login_count:x().default(0),identities:S(xl).optional()});Al.omit({registration_completed_at:!0});Es.extend({login_count:x(),multifactor:S(a()).optional(),last_ip:a().optional(),last_login:a().optional(),user_id:a()}).catchall(V());let Tl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Il=(n=21)=>{let e="",t=crypto.getRandomValues(new Uint8Array(n|=0));for(;n--;)e+=Tl[t[n]&63];return e};const Cl=_({client_id:a().optional().openapi({description:"ID of this client. Generated server-side if omitted (Auth0 behavior)."}),name:a().min(1).openapi({description:"Name of this client (min length: 1 character, does not allow < or >)."}),description:a().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:a().default(()=>Il()).optional().openapi({description:"Client secret (which you must not make public)."}),app_type:b(["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:a().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:S(a()).default([]).optional().openapi({description:"Comma-separated list of URLs whitelisted for Auth0 to use as a callback to the client after authentication."}),allowed_origins:S(a()).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:S(a()).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:S(a()).default([]).optional().openapi({description:"List of audiences/realms for SAML protocol. Used by the wsfed addon."}),allowed_clients:S(a()).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:S(a()).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:S(a()).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:M(V()).default({}).optional().openapi({description:"Native to Web SSO Configuration"}),oidc_logout:M(V()).default({}).optional().openapi({description:"Configuration for OIDC backchannel logout"}),grant_types:S(a()).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:M(V()).default({}).optional().openapi({description:"Configuration related to JWTs for the client."}),signing_keys:S(M(V())).default([]).optional().openapi({description:"Signing certificates associated with this client."}),encryption_key:M(V()).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:a().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:a().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page."}),custom_login_page_preview:a().optional().openapi({description:"The content (HTML, CSS, JS) of the custom login page. (Used on Previews)"}),form_template:a().optional().openapi({description:"HTML form template to be used for WS-Federation."}),addons:M(V()).default({}).optional().openapi({description:"Addons enabled for this client and their associated configurations."}),token_endpoint_auth_method:b(["none","client_secret_post","client_secret_basic","client_secret_jwt","private_key_jwt"]).default("client_secret_basic").optional().openapi({description:"Defines the requested authentication method for the token endpoint. `none` (public client), `client_secret_post` / `client_secret_basic` (HTTP POST / Basic), `client_secret_jwt` (RFC 7523 HMAC assertion using client_secret), or `private_key_jwt` (RFC 7523 asymmetric assertion verified against the client's `jwks` / `jwks_uri`)."}),client_metadata:M(a().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]'}),hide_sign_up_disabled_error:h().default(!1).optional().openapi({description:"Enumeration-safe variant of the connection-level `disable_signup` flag. When a signup is blocked by the password connection and this is true, the identifier screen does not reveal that an email is unknown — it advances to the OTP/password challenge as if the account existed and fails at credential check. Mitigates email enumeration at the cost of UX: users without an account see a generic credential failure instead of an explicit signup-disabled message."}),mobile:M(V()).default({}).optional().openapi({description:"Additional configuration for native mobile apps."}),initiate_login_uri:a().url().optional().openapi({description:"Initiate login uri, must be https"}),native_social_login:M(V()).default({}).optional(),refresh_token:_({rotation_type:b(["rotating","non-rotating"]).optional().openapi({description:"Whether refresh tokens for this client are rotated on every exchange (Auth0 'rotating' behavior) or kept stable (legacy non-rotating). Defaults to 'non-rotating' when unset."}),leeway:x().int().min(0).max(600).optional().openapi({description:"Seconds after a parent token's first rotation during which presenting it again still mints a fresh sibling child instead of triggering reuse-detection. Defaults to 30s when unset."}),expiration_type:b(["expiring","non-expiring"]).optional().openapi({description:"Auth0-compatible: whether refresh tokens expire."}),token_lifetime:x().int().min(0).optional().openapi({description:"Auth0-compatible: refresh-token absolute lifetime in seconds."}),infinite_token_lifetime:h().optional().openapi({description:"Auth0-compatible: when true, refresh tokens have no absolute expiry."}),idle_token_lifetime:x().int().min(0).optional().openapi({description:"Auth0-compatible: refresh-token idle (sliding) lifetime in seconds."}),infinite_idle_token_lifetime:h().optional().openapi({description:"Auth0-compatible: when true, refresh tokens have no idle expiry."})}).default({}).optional().openapi({description:"Refresh token configuration"}),default_organization:M(V()).default({}).optional().openapi({description:"Defines the default Organization ID and flows"}),organization_usage:b(["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:b(["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:M(V()).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:M(V()).default({}).optional().openapi({description:"JWT-secured Authorization Requests (JAR) settings."}),compliance_level:b(["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:x().optional().openapi({description:"Specifies how long, in seconds, a Pushed Authorization Request URI remains valid"}),token_quota:M(V()).default({}).optional(),owner_user_id:a().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:b(["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:M(V()).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."}),user_linking_mode:b(["builtin","off"]).optional().openapi({description:"Per-client override for the built-in email-based user-linking path. `builtin` runs the legacy in-process linking at user creation/email update. `off` disables the legacy path; linking only happens if the tenant has enabled the `account-linking` template hook. When unset, the service-level `userLinkingMode` default applies."})});_({created_at:a(),updated_at:a(),...Cl.shape,client_id:a()});const Dl=_({client_id:a().min(1).openapi({description:"ID of the client."}),audience:a().min(1).openapi({description:"The audience (API identifier) of this client grant."}),scope:S(a()).optional().openapi({description:"Scopes allowed for this client grant."}),organization_usage:b(["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:b(["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:S(a()).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."})}),Ll=_({id:a().openapi({description:"ID of the client grant."}),...Dl.shape,created_at:a().optional(),updated_at:a().optional()});S(Ll);const xs=b(["iat","rat"]),Rl=_({id:a(),token_hash:a(),type:xs,client_id:a().optional(),sub:a().optional(),constraints:M(Fe()).optional(),single_use:h().default(!1),expires_at:a().optional()});_({created_at:a(),used_at:a().optional(),revoked_at:a().optional(),...Rl.shape});const Dt=_({x:x(),y:x()});var ks=(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))(ks||{}),Os=(n=>(n.BLOCK="BLOCK",n.FIELD="FIELD",n))(Os||{});const bn=_({id:a(),category:wt(Os),type:wt(ks)}),Ul=bn.extend({category:I("BLOCK"),type:I("RICH_TEXT"),config:_({content:a()}).passthrough()}),Fl=bn.extend({category:I("BLOCK"),type:Me([I("NEXT_BUTTON"),I("BACK_BUTTON"),I("SUBMIT_BUTTON")]),config:_({text:a()}).passthrough()}),zl=bn.extend({category:I("FIELD"),type:I("LEGAL"),required:h().optional(),sensitive:h().optional(),config:_({text:a()}).passthrough()}),Ml=bn.extend({category:I("FIELD"),type:Me([I("TEXT"),I("EMAIL"),I("PASSWORD"),I("NUMBER"),I("PHONE"),I("DATE"),I("CHECKBOX"),I("RADIO"),I("SELECT"),I("HIDDEN")]),required:h().optional(),sensitive:h().optional(),config:_({label:a().optional(),placeholder:a().optional()}).passthrough()}),Pl=_({id:a(),category:a(),type:a()}).passthrough(),ql=Me([Ul,Fl,zl,Ml,Pl]),Bl=_({id:a(),type:I("STEP"),coordinates:Dt,alias:a().optional(),config:_({components:S(ql),next_node:a()}).passthrough()}),$l=_({id:a(),type:I("FLOW"),coordinates:Dt,alias:a().optional(),config:_({flow_id:a(),next_node:a()})}),jl=_({id:a(),type:I("ACTION"),coordinates:Dt,alias:a().optional(),config:_({action_type:b(["REDIRECT"]).openapi({description:"The type of action to perform"}),target:b(["change-email","account","custom"]).openapi({description:"The predefined target to redirect to"}),custom_url:a().optional().openapi({description:"Custom URL when target is 'custom'"}),next_node:a().openapi({description:"The next node to navigate to after action (for non-redirect actions)"})}).passthrough()}),Vl=_({id:a(),type:a(),coordinates:Dt}).passthrough(),Hl=Me([Bl,$l,jl,Vl]),Zl=_({next_node:a(),coordinates:Dt}).passthrough(),Kl=_({resume_flow:h().optional(),coordinates:Dt}).passthrough(),Wl=_({id:a(),name:a(),languages:_({primary:a()}).passthrough(),nodes:S(Hl),start:Zl,ending:Kl,created_at:a(),updated_at:a(),links:_({sdkSrc:a().optional(),sdk_src:a().optional()}).passthrough()}).passthrough();Wl.omit({id:!0,created_at:!0,updated_at:!0});var As=(n=>(n.TOKEN="token",n.ID_TOKEN="id_token",n.TOKEN_ID_TOKEN="id_token token",n.CODE="code",n.CODE_ID_TOKEN="code id_token",n.CODE_TOKEN="code token",n.CODE_ID_TOKEN_TOKEN="code id_token token",n))(As||{}),Ts=(n=>(n.QUERY="query",n.FRAGMENT="fragment",n.FORM_POST="form_post",n.WEB_MESSAGE="web_message",n.SAML_POST="saml_post",n))(Ts||{}),Is=(n=>(n.S256="S256",n.Plain="plain",n))(Is||{});const Ii=Me([ys(),_({essential:h().optional(),value:Fe().optional(),values:S(Fe()).optional()})]).nullable(),Gl=_({userinfo:M(a(),Ii).optional(),id_token:M(a(),Ii).optional()}),Jl=_({client_id:a(),act_as:a().optional(),response_type:wt(As).optional(),response_mode:wt(Ts).optional(),redirect_uri:a().optional(),audience:a().optional(),organization:a().optional(),state:a().optional(),nonce:a().optional(),scope:a().optional(),prompt:a().optional(),code_challenge_method:wt(Is).optional(),code_challenge:a().optional(),username:a().optional(),ui_locales:a().optional(),max_age:x().optional(),acr_values:a().optional(),claims:Gl.optional(),vendor_id:a().optional()});_({colors:_({primary:a(),page_background:Me([a(),_({type:a().optional(),start:a().optional(),end:a().optional(),angle_deg:x().optional()})]).optional()}).optional(),logo_url:a().optional(),favicon_url:a().optional(),powered_by_logo_url:a().optional(),font:_({url:a()}).optional(),dark_mode:b(["dark","light","auto"]).optional()});const Ql=b(["password_reset","email_verification","otp","mfa_otp","authorization_code","oauth2_state","ticket"]),Xl=_({code_id:a().openapi({description:"The code that will be used in for instance an email verification flow"}),login_id:a().openapi({description:"The id of the login session that the code is connected to"}),connection_id:a().optional().openapi({description:"The connection that the code is connected to"}),code_type:Ql,code_verifier:a().optional().openapi({description:"The code verifier used in PKCE in outbound flows"}),code_challenge:a().optional().openapi({description:"The code challenge used in PKCE in outbound flows"}),code_challenge_method:b(["plain","S256"]).optional().openapi({description:"The code challenge method used in PKCE in outbound flows"}),redirect_uri:a().optional().openapi({description:"The redirect URI associated with the code"}),otp:a().optional().openapi({description:"The one-time password value for OTP-based flows"}),nonce:a().optional().openapi({description:"The nonce value used for security in OIDC flows"}),state:a().optional().openapi({description:"The state parameter used for CSRF protection in OAuth flows"}),expires_at:a(),used_at:a().optional(),user_id:a().optional()});_({...Xl.shape,created_at:a()});const Yl=_({kid:a().optional(),team_id:a().optional(),realms:a().optional(),authentication_method:a().optional(),client_id:a().optional(),client_secret:a().optional(),app_secret:a().optional(),scope:a().optional(),authorization_endpoint:a().optional(),token_endpoint:a().optional(),userinfo_endpoint:a().optional(),jwks_uri:a().optional(),discovery_url:a().optional(),issuer:a().optional(),token_endpoint_auth_method:b(["client_secret_basic","client_secret_post"]).optional(),provider:a().optional(),from:a().optional(),twilio_sid:a().optional(),twilio_token:a().optional(),icon_url:a().optional(),domain_aliases:S(a()).optional(),callback_url:a().url().optional(),passwordPolicy:b(["none","low","fair","good","excellent"]).optional(),password_complexity_options:_({min_length:x().optional()}).optional(),password_history:_({enable:h().optional(),size:x().optional()}).optional(),password_no_personal_info:_({enable:h().optional()}).optional(),password_dictionary:_({enable:h().optional(),dictionary:S(a()).optional()}).optional(),disable_signup:h().optional(),brute_force_protection:h().optional(),import_mode:h().optional(),configuration:_({token_endpoint:a().optional(),userinfo_endpoint:a().optional(),client_id:a().optional(),client_secret:a().optional(),realm:a().optional()}).optional(),attributes:_({email:_({identifier:_({active:h().optional()}).optional(),signup:_({status:b(["required","optional","disabled"]).optional(),verification:_({active:h().optional()}).optional()}).optional(),validation:_({allowed:h().optional()}).optional(),unique:h().optional(),profile_required:h().optional(),verification_method:b(["link","code"]).optional()}).optional(),username:_({identifier:_({active:h().optional()}).optional(),signup:_({status:b(["required","optional","disabled"]).optional()}).optional(),validation:_({max_length:x().optional(),min_length:x().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:b(["required","optional","disabled"]).optional()}).optional()}).optional()}).optional(),authentication_methods:_({password:_({enabled:h().optional()}).optional(),passkey:_({enabled:h().optional()}).optional()}).optional(),passkey_options:_({challenge_ui:b(["both","autofill","button"]).optional(),local_enrollment_enabled:h().optional(),progressive_enrollment_enabled:h().optional()}).optional(),requires_username:h().optional(),validation:_({username:_({min:x().optional(),max:x().optional()}).optional()}).optional(),set_user_root_attributes:b(["on_each_login","on_first_login","never_on_login"]).optional()});function di(n){if(n!==null){if(Array.isArray(n))return n.filter(e=>e!==null).map(di);if(n&&typeof n=="object"){const e={};for(const[t,i]of Object.entries(n))i!==null&&(e[t]=di(i));return e}return n}}const ed=_({id:a().optional(),name:a(),display_name:a().optional(),strategy:a(),options:vs(n=>n===null?{}:di(n),Yl).default({}),enabled_clients:S(a()).default([]).optional(),response_type:li().optional(),response_mode:li().optional(),is_domain_connection:h().optional(),show_as_button:h().optional(),metadata:M(V()).optional(),is_system:h().optional()});_({id:a(),created_at:a().transform(n=>n===null?"":n),updated_at:a().transform(n=>n===null?"":n)}).extend(ed.shape);const td=_({domain:a(),custom_domain_id:a().optional(),type:b(["auth0_managed_certs","self_managed_certs"]),verification_method:b(["txt"]).optional(),tls_policy:b(["recommended"]).optional(),custom_client_ip_header:b(["true-client-ip","cf-connecting-ip","x-forwarded-for","x-azure-clientip","null"]).optional(),domain_metadata:M(a().max(255)).optional()}),nd=Ct("name",[_({name:I("txt"),record:a(),domain:a()}),_({name:I("http"),http_body:a(),http_url:a()})]),id=_({...td.shape,custom_domain_id:a(),primary:h(),status:b(["disabled","pending","pending_verification","ready"]),origin_domain_name:a().optional(),verification:_({methods:S(nd)}).optional(),tls_policy:a().optional()});id.extend({tenant_id:a()});const Si=_({id:a(),order:x().optional(),visible:h().optional().default(!0)}),ht=Si.extend({category:I("BLOCK").optional()}),od=ht.extend({type:I("DIVIDER"),config:_({text:a().optional()}).optional()}),ad=ht.extend({type:I("HTML"),config:_({content:a().optional()}).optional()}),sd=ht.extend({type:I("IMAGE"),config:_({src:a().optional(),alt:a().optional(),width:x().optional(),height:x().optional()}).optional()}),rd=ht.extend({type:I("JUMP_BUTTON"),config:_({text:a().optional(),target_step:a().optional()})}),ld=ht.extend({type:I("RESEND_BUTTON"),config:_({text:a().optional(),resend_action:a().optional()})}),dd=ht.extend({type:I("NEXT_BUTTON"),config:_({text:a().optional()})}),cd=ht.extend({type:I("PREVIOUS_BUTTON"),config:_({text:a().optional()})}),_d=ht.extend({type:I("RICH_TEXT"),config:_({content:a().optional()}).optional()}),bi=Si.extend({category:I("WIDGET").optional(),label:a().min(1).optional(),hint:a().min(1).max(500).optional(),required:h().optional(),sensitive:h().optional()}),ud=bi.extend({type:I("AUTH0_VERIFIABLE_CREDENTIALS"),config:_({credential_type:a().optional()})}),pd=bi.extend({type:I("GMAPS_ADDRESS"),config:_({api_key:a().optional()})}),fd=bi.extend({type:I("RECAPTCHA"),config:_({site_key:a().optional()})}),be=Si.extend({category:I("FIELD").optional(),label:a().min(1).optional(),hint:a().min(1).max(500).optional(),messages:S(_({id:x().optional(),text:a(),type:b(["info","error","success","warning"])})).optional(),required:h().optional(),sensitive:h().optional()}),hd=be.extend({type:I("BOOLEAN"),config:_({default_value:h().optional()}).optional()}),gd=be.extend({type:I("CARDS"),config:_({options:S(_({value:a(),label:a(),description:a().optional(),image:a().optional()})).optional(),multi_select:h().optional()}).optional()}),md=be.extend({type:I("CHOICE"),config:_({options:S(_({value:a(),label:a()})).optional(),display:b(["radio","checkbox"]).optional(),multiple:h().optional(),default_value:Me([a(),S(a())]).optional()}).optional()}),yd=be.extend({type:I("CUSTOM"),config:_({component:a().optional(),props:M(V()).optional(),schema:M(V()).optional(),code:a().optional()})}),vd=be.extend({type:I("DATE"),config:_({format:a().optional(),min:a().optional(),max:a().optional(),default_value:a().optional()}).optional()}),wd=be.extend({type:I("DROPDOWN"),config:_({options:S(_({value:a(),label:a()})).optional(),placeholder:a().optional(),searchable:h().optional(),multiple:h().optional(),default_value:Me([a(),S(a())]).optional()}).optional()}),Nd=be.extend({type:I("EMAIL"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Sd=be.extend({type:I("FILE"),config:_({accept:a().optional(),max_size:x().optional(),multiple:h().optional()}).optional()}),bd=be.extend({type:I("LEGAL"),config:_({text:a(),html:h().optional()}).optional()}),Ed=be.extend({type:I("NUMBER"),config:_({placeholder:a().optional(),min:x().optional(),max:x().optional(),step:x().optional(),default_value:a().optional()}).optional()}),xd=be.extend({type:I("PASSWORD"),config:_({placeholder:a().optional(),min_length:x().optional(),show_toggle:h().optional(),forgot_password_link:a().optional(),default_value:a().optional()}).optional()}),kd=be.extend({type:I("PAYMENT"),config:_({provider:a().optional(),currency:a().optional()}).optional()}),Od=be.extend({type:I("SOCIAL"),config:_({providers:S(a()).optional(),provider_details:S(_({name:a(),strategy:a().optional(),display_name:a().optional(),icon_url:a().optional(),href:a().optional()})).optional()}).optional()}),Ad=be.extend({type:I("TEL"),config:_({placeholder:a().optional(),default_country:a().optional(),default_value:a().optional(),allow_email:h().optional()}).optional()}),Td=be.extend({type:I("TEXT"),config:_({placeholder:a().optional(),multiline:h().optional(),max_length:x().optional(),default_value:a().optional()}).optional()}),Id=be.extend({type:I("COUNTRY"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Cd=be.extend({type:I("URL"),config:_({placeholder:a().optional(),default_value:a().optional()}).optional()}),Dd=Ct("type",[od,ad,sd,rd,ld,dd,cd,_d]),Ld=Ct("type",[ud,pd,fd]),Rd=Ct("type",[hd,gd,md,Id,yd,vd,wd,Nd,Sd,bd,Ed,xd,kd,Od,Ad,Td,Cd]),Cs=Me([Dd,Ld,Rd]);_({id:a(),type:I("submit"),label:a(),className:a().optional(),disabled:h().optional().default(!1),order:x().optional(),visible:h().optional().default(!0),customizations:M(a(),V()).optional()});const Yt=_({x:x(),y:x()}),Ud=_({id:a(),type:I("FLOW"),coordinates:Yt,alias:a().min(1).max(150).optional(),config:_({flow_id:a().max(30),next_node:a().optional()})}),Fd=_({id:a(),type:I("ROUTER"),coordinates:Yt,alias:a().min(1).max(150),config:_({rules:S(_({id:a(),alias:a().min(1).max(150).optional(),condition:V(),next_node:a()})),fallback:a()})}),zd=_({id:a(),type:I("STEP"),coordinates:Yt,alias:a().min(1).max(150).optional(),config:_({components:S(Cs),next_node:a().optional()})}),Md=Ct("type",[Ud,Fd,zd]),Pd=_({name:a().openapi({description:"The name of the form"}),messages:_({errors:M(a(),V()).optional(),custom:M(a(),V()).optional()}).optional(),languages:_({primary:a().optional(),default:a().optional()}).optional(),translations:M(a(),V()).optional(),nodes:S(Md).optional(),start:_({hidden_fields:S(_({key:a(),value:a()})).optional(),next_node:a().optional(),coordinates:Yt.optional()}).optional(),ending:_({redirection:_({delay:x().optional(),target:a().optional()}).optional(),after_submit:_({flow_id:a().optional()}).optional(),coordinates:Yt.optional(),resume_flow:h().optional()}).optional(),style:_({css:a().optional()}).optional(),links:_({sdkSrc:a().optional(),sdk_src:a().optional()}).optional()}).openapi({description:"Schema for flow-based forms (matches Auth0 Forms structure)"});_({...He.shape,...Pd.shape,id:a()});const qd=_({id:x().optional(),text:a(),type:b(["info","error","success","warning"])}),Bd=_({id:a().optional(),text:a(),href:a(),linkText:a().optional()});_({name:a().optional(),action:a(),method:b(["POST","GET"]),title:a().optional(),description:a().optional(),components:S(Cs),messages:S(qd).optional(),links:S(Bd).optional(),footer:a().optional()});const Ds=b(["pre-user-registration","post-user-registration","post-user-login","post-user-update","validate-registration-username","pre-user-deletion","post-user-deletion"]),Ls=b(["pre-user-registration","post-user-registration","post-user-login","validate-registration-username","pre-user-deletion","post-user-deletion"]),Rs=b(["post-user-login","post-user-registration","post-user-update","credentials-exchange"]),Us=b(["post-user-login","credentials-exchange","pre-user-registration","post-user-registration"]),Fs=b(["ensure-username","set-preferred-username","account-linking"]),gt={enabled:h().default(!1),synchronous:h().default(!1),priority:x().optional(),hook_id:a().optional(),metadata:M(Fe()).optional()},$d=_({...gt,trigger_id:Ds,url:a()}),jd=_({...gt,trigger_id:Ls,form_id:a()}),Vd=_({...gt,trigger_id:Rs,template_id:Fs}),Hd=_({...gt,trigger_id:Us,code_id:a()});Me([$d,jd,Vd,Hd]);const Zd=_({...gt,trigger_id:Ds,...He.shape,hook_id:a(),url:a()}),Kd=_({...gt,trigger_id:Ls,...He.shape,hook_id:a(),form_id:a()}),Wd=_({...gt,trigger_id:Rs,...He.shape,hook_id:a(),template_id:Fs}),Gd=_({...gt,trigger_id:Us,...He.shape,hook_id:a(),code_id:a()});Me([Zd,Kd,Wd,Gd]);const Jd=_({code:a().max(1e5),secrets:M(a()).optional()});Jd.extend({id:a(),tenant_id:a(),...He.shape});const Qd=_({name:a().optional()}),Xd=_({email:a().optional()}),Yd=_({organization_id:a().max(50),inviter:Qd,invitee:Xd,invitation_url:a().url(),client_id:a(),connection_id:a().optional(),app_metadata:M(V()).default({}).optional(),user_metadata:M(V()).default({}).optional(),ttl_sec:x().int().max(2592e3).default(604800).optional(),roles:S(a()).default([]).optional(),send_invitation_email:h().default(!0).optional()});_({id:a(),organization_id:a().max(50),created_at:a().datetime(),expires_at:a().datetime(),ticket_id:a().optional()}).extend(Yd.shape);const ec=_({alg:b(["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512"]),kid:a(),kty:b(["RSA","EC","oct"]),use:b(["sig","enc"]).optional(),n:a().optional(),e:a().optional(),crv:a().optional(),x:a().optional(),y:a().optional(),x5t:a().optional(),x5c:S(a()).optional()}).superRefine((n,e)=>{if(n.kty==="RSA")for(const t of["n","e"])n[t]||e.addIssue({code:N.custom,path:[t],message:`RSA JWK is missing required member '${t}'`});else if(n.kty==="EC")for(const t of["crv","x","y"])n[t]||e.addIssue({code:N.custom,path:[t],message:`EC JWK is missing required member '${t}'`})});_({keys:S(ec)});_({issuer:a(),authorization_endpoint:a(),token_endpoint:a(),userinfo_endpoint:a(),jwks_uri:a(),registration_endpoint:a().optional(),revocation_endpoint:a(),end_session_endpoint:a().optional(),scopes_supported:S(a()),response_types_supported:S(a()),grant_types_supported:S(a()).optional(),code_challenge_methods_supported:S(a()),response_modes_supported:S(a()),subject_types_supported:S(a()),id_token_signing_alg_values_supported:S(a()),token_endpoint_auth_methods_supported:S(a()),claims_supported:S(a()),request_uri_parameter_supported:h(),request_parameter_supported:h(),claims_parameter_supported:h().optional(),request_object_signing_alg_values_supported:S(a()).optional(),token_endpoint_auth_signing_alg_values_supported:S(a())});var zs=(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))(zs||{});const tc=wt(zs),nc=_({strategy:a(),strategy_type:a()}),ic=_({csrf_token:a(),auth0Client:a().optional(),authParams:Jl,expires_at:a(),deleted_at:a().optional(),ip:a().optional(),useragent:a().optional(),session_id:a().optional(),authorization_url:a().optional(),state:tc.optional().default("pending"),state_data:a().optional(),failure_reason:a().optional(),user_id:a().optional(),auth_connection:a().optional(),auth_strategy:nc.optional(),authenticated_at:a().optional()}).openapi({description:"This represents a login sesion"});_({...ic.shape,id:a().openapi({description:"This is is used as the state in the universal login"}),created_at:a(),updated_at:a()});const Ms={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",INFORMATION:"i",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_HOOK:"sh",SUCCESS_PASSWORD_MIGRATION:"spm",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"},oc=a().refine(n=>Object.values(Ms).includes(n),{message:"Invalid log type"});(()=>{const n={};for(const[e,t]of Object.entries(Ms))e.startsWith("SUCCESS_")||e.startsWith("SUCCESSFUL_")||e.startsWith("SUCCESSFULLY_")?n[t]="success":e.startsWith("FAILED_")||e.startsWith("ERROR_")||e.startsWith("BREACHED_")||e.startsWith("BLOCKED_")||e==="MFA_AUTH_FAILED"||e==="MFA_AUTH_REJECTED"||e==="MFA_RECOVERY_FAILED"||e==="MFA_ENROLLMENT_FAILED"||e==="EMAIL_VERIFICATION_FAILED"||e==="WEBAUTHN_CHALLENGE_FAILED"||e==="WEBAUTHN_ENROLLMENT_FAILED"||e==="PASSKEY_CHALLENGE_FAILED"||e==="FLOWS_EXECUTION_FAILED"||e==="FORMS_SUBMISSION_FAILED"||e==="CIBA_EXCHANGE_FAILED"||e==="CIBA_START_FAILED"||e==="ACTIONS_EXECUTION_FAILED"||e==="RICH_CONSENTS_ACCESS_ERROR"||e==="USER_CANCELED_DEVICE_CONFIRMATION"||e==="TOO_MANY_MFA_FAILURES"||e==="MFA_RECOVERY_RATE_LIMIT_EXCEED"||e==="API_LIMIT"||e==="MAX_AMOUNT_OF_AUTHENTICATORS"?n[t]="failure":e.startsWith("WARNING_")||e==="API_LIMIT_WARNING"||e==="DEPRECATION_NOTICE"||e==="PRE_LOGIN_ASSESSMENT"?n[t]="warning":e==="CODE_SENT"||e==="CODE_LINK_SENT"||e==="MFA_EMAIL_SENT"||e==="MFA_SMS_SENT"||e==="EMAIL_VERIFICATION_SENT"||e==="PUSH_NOTIFICATION_SENT"?n[t]="code_sent":e==="INFORMATION"||e==="INFORMATION_FROM_SS_SSO_OPERATION"||e==="MANAGEMENT_API_READ_OPERATION"||e==="APPI"||e==="ACLS_SUMMARY"||e==="ORGANIZATION_MEMBER_ADDED"?n[t]="info":n[t]="other";return n})();const ac=_({name:a(),version:a(),env:_({node:a().optional()}).optional()}),sc=_({country_code:a().length(2),city_name:a(),latitude:a(),longitude:a(),time_zone:a(),continent_code:a()}),rc=_({type:oc,date:a(),description:a().optional(),ip:a().optional(),user_agent:a().optional(),details:V().optional(),isMobile:h(),user_id:a().optional(),user_name:a().optional(),connection:a().optional(),connection_id:a().optional(),client_id:a().optional(),client_name:a().optional(),audience:a().optional(),scope:a().optional(),strategy:a().optional(),strategy_type:a().optional(),hostname:a().optional(),auth0_client:ac.optional(),log_id:a().optional(),location_info:sc.optional()});_({...rc.shape,log_id:a()});const lc=b(["http","eventbridge","eventgrid","splunk","datadog","sumo"]),Ps=b(["active","paused","suspended"]),dc=_({type:a(),name:a()}),cc=_({name:a(),type:lc,status:Ps.optional(),sink:M(a(),Fe()),filters:S(dc).optional(),isPriority:h().optional()});cc.extend({id:a(),status:Ps,created_at:a().optional(),updated_at:a().optional()});const _c=b(["auth0","cognito","okta","oidc"]),uc=_({domain:a(),client_id:a(),client_secret:a(),audience:a().optional(),scope:a().optional()}),pc=_({id:a().optional(),name:a(),provider:_c,connection:a(),enabled:h().default(!0),credentials:uc});_({id:a(),created_at:a(),updated_at:a()}).extend(pc.shape);const fc=_({enabled:h().optional(),shields:S(a()).optional(),admin_notification_frequency:S(a()).optional(),method:a().optional(),stage:_({"pre-user-registration":_({shields:S(a()).optional()}).optional(),"pre-change-password":_({shields:S(a()).optional()}).optional()}).optional()}),hc=_({enabled:h().optional(),shields:S(a()).optional(),allowlist:S(a()).optional(),mode:a().optional(),max_attempts:x().optional()}),gc=_({enabled:h().optional(),shields:S(a()).optional(),allowlist:S(a()).optional(),stage:_({"pre-login":_({max_attempts:x().optional(),rate:x().optional()}).optional(),"pre-user-registration":_({max_attempts:x().optional(),rate:x().optional()}).optional()}).optional()}),mc=_({breached_password_detection:fc.optional(),brute_force_protection:hc.optional(),suspicious_ip_throttling:gc.optional()}),yc=_({id:a().optional(),user_id:a(),password:a(),algorithm:b(["bcrypt","argon2id"]).default("argon2id"),is_current:h().default(!0)});yc.extend({id:a(),created_at:a(),updated_at:a()});const qs=_({initial_user_agent:a().describe("First user agent of the device from which this user logged in"),initial_ip:a().describe("First IP address associated with this session"),initial_asn:a().describe("First autonomous system number associated with this session"),last_user_agent:a().describe("Last user agent of the device from which this user logged in"),last_ip:a().describe("Last IP address from which this user logged in"),last_asn:a().describe("Last autonomous system number from which this user logged in")}),vc=_({id:a(),revoked_at:a().optional(),used_at:a().optional(),user_id:a().describe("The user ID associated with the session"),expires_at:a().optional(),login_session_id:a(),idle_expires_at:a().optional(),device:qs.describe("Metadata related to the device used in the session"),clients:S(a()).describe("List of client details for the session")});_({created_at:a(),updated_at:a(),authenticated_at:a(),last_interaction_at:a(),...vc.shape});_({kid:a().openapi({description:"The key id of the signing key"}),tenant_id:a().optional().openapi({description:"The tenant the key belongs to. Omitted means the key is shared / control-plane scoped."}),cert:a().openapi({description:"The public certificate of the signing key"}),fingerprint:a().openapi({description:"The cert fingerprint"}),thumbprint:a().openapi({description:"The cert thumbprint"}),pkcs7:a().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:a().optional().openapi({description:"The date and time when the key became the current key"}),current_until:a().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:a().optional().openapi({description:"The date and time when the key was revoked"}),connection:a().optional().openapi({description:"The connection identifier associated with the key"}),type:b(["jwt_signing","saml_encryption"]).openapi({description:"The type of the signing key"})});const wc=_({id:a().optional(),audience:a(),friendly_name:a(),picture_url:a().optional(),support_email:a().optional(),support_url:a().optional(),sender_email:a().email(),sender_name:a(),session_lifetime:x().optional(),idle_session_lifetime:x().optional(),ephemeral_session_lifetime:x().optional(),idle_ephemeral_session_lifetime:x().optional(),session_cookie:_({mode:b(["persistent","non-persistent"]).optional()}).optional(),allowed_logout_urls:S(a()).optional(),default_redirection_uri:a().optional(),default_client_id:a().optional(),enabled_locales:S(a()).optional(),default_directory:a().optional(),error_page:_({html:a().optional(),show_log_link:h().optional(),url:a().optional()}).nullish(),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:S(a()).optional(),allow_http_return_to:S(a().refine(n=>{try{const e=new URL(n);return e.protocol==="http:"&&(e.pathname===""||e.pathname==="/")&&!e.search&&!e.hash&&n===e.origin}catch{return!1}},{message:"must be a fully-qualified http origin (scheme + host + port, no path)"})).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:a().optional(),legacy_sandbox_version:a().optional(),sandbox_versions_available:S(a()).optional(),change_password:_({enabled:h().optional(),html:a().optional()}).optional(),guardian_mfa_page:_({enabled:h().optional(),html:a().optional()}).optional(),device_flow:_({charset:b(["base20","digits"]).optional(),mask:a().max(20).optional()}).optional(),default_token_quota:_({clients:_({client_credentials:M(V()).optional()}).optional(),organizations:_({client_credentials:M(V()).optional()}).optional()}).nullish(),default_audience:a().optional(),default_organization:a().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:S(a()).optional(),mtls:_({enable_endpoint_aliases:h().optional()}).nullish(),pushed_authorization_requests_supported:h().optional(),authorization_response_iss_parameter_supported:h().optional(),attack_protection:mc.optional(),mfa:_({policy:b(["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:b(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:_({sid:a().optional(),auth_token:a().optional(),from:a().optional(),messaging_service_sid:a().optional()}).optional(),phone_message:_({message:a().optional()}).optional()}).optional()});_({created_at:a().nullable().transform(n=>n??""),updated_at:a().nullable().transform(n=>n??""),...wc.shape,id:a(),is_control_plane:h().optional()});_({access_token:a(),id_token:a().optional(),scope:a().optional(),state:a().optional(),refresh_token:a().optional(),token_type:a(),expires_in:x()});_({code:a(),state:a().optional()});const Nc=_({button_border_radius:x(),button_border_weight:x(),buttons_style:b(["pill","rounded","sharp"]),input_border_radius:x(),input_border_weight:x(),inputs_style:b(["pill","rounded","sharp"]),show_widget_shadow:h(),widget_border_weight:x(),widget_corner_radius:x()}),Sc=_({base_focus_color:a(),base_hover_color:a(),body_text:a(),captcha_widget_theme:b(["auto","dark","light"]),error:a(),header:a(),icons:a(),input_background:a(),input_border:a(),input_filled_text:a(),input_labels_placeholders:a(),links_focused_components:a(),primary_button:a(),primary_button_label:a(),secondary_button_border:a(),secondary_button_label:a(),success:a(),widget_background:a(),widget_border:a()}),bt=_({bold:h(),size:x()}),bc=_({body_text:bt,buttons_text:bt,font_url:a(),input_labels:bt,links:bt,links_style:b(["normal","underlined"]),reference_text_size:x(),subtitle:bt,title:bt}),Ec=_({background_color:a(),background_image_url:a(),page_layout:b(["center","left","right"]),logo_placement:b(["widget","chip","none"]).optional()}),xc=_({header_text_alignment:b(["center","left","right"]),logo_height:x(),logo_position:b(["center","left","none","right"]),logo_url:a(),social_buttons_layout:b(["bottom","top"])}),kc=_({borders:Nc,colors:Sc,displayName:a(),fonts:bc,page_background:Ec,widget:xc});kc.extend({themeId:a()});_({universal_login_experience:b(["new","classic"]).default("new"),identifier_first:h().default(!0),password_first:h().default(!1),webauthn_platform_first_factor:h()});_({name:a(),enabled:h().optional().default(!0),default_from_address:a().optional(),credentials:M(a(),Fe()),settings:_({}).optional()});const Oc=b(["verify_email","verify_email_by_code","reset_email","reset_email_by_code","welcome_email","blocked_account","stolen_credentials","enrollment_email","mfa_oob_code","change_password","password_reset","user_invitation"]);_({template:Oc,body:a(),from:a(),subject:a(),syntax:I("liquid").default("liquid"),resultUrl:a().optional(),urlLifetimeInSeconds:x().int().nonnegative().optional(),includeEmailInRedirect:h().default(!1),enabled:h().default(!0)});const Ac=_({id:a(),login_id:a(),user_id:a(),client_id:a(),expires_at:a().optional(),idle_expires_at:a().optional(),last_exchanged_at:a().optional(),device:qs,resource_servers:S(_({audience:a(),scopes:a()})),rotating:h(),token_lookup:a().optional(),token_hash:a().optional(),family_id:a().optional(),rotated_to:a().optional(),rotated_at:a().optional()});_({created_at:a(),revoked_at:a().optional(),...Ac.shape});_({to:a(),message:a()});_({name:a(),options:_({})});const Tc=_({value:a(),description:a().optional()}),Ic=_({token_dialect:b(["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()}),Cc=_({id:a().optional(),name:a(),identifier:a(),scopes:S(Tc).optional(),signing_alg:a().optional(),signing_secret:a().optional(),token_lifetime:x().default(86400),token_lifetime_for_web:x().default(7200),skip_consent_for_verifiable_first_party_clients:h().optional(),allow_offline_access:h().optional(),verificationKey:a().optional(),options:Ic.optional(),is_system:h().optional(),metadata:M(V()).optional()}),Dc=_({...Cc.shape,created_at:a().optional(),updated_at:a().optional()});S(Dc);const Lc=_({role_id:a(),resource_server_identifier:a(),permission_name:a()}),Rc=_({...Lc.shape,created_at:a()});S(Rc);const Uc=_({user_id:a(),resource_server_identifier:a(),permission_name:a(),organization_id:a().optional()}),Fc=_({...Uc.shape,tenant_id:a(),created_at:a().optional()});S(Fc);const zc=_({user_id:a(),resource_server_identifier:a(),resource_server_name:a(),permission_name:a(),description:a().nullable().optional(),created_at:a().optional(),organization_id:a().optional()});S(zc);const Mc=_({user_id:a(),role_id:a(),organization_id:a().optional()}),Pc=_({...Mc.shape,tenant_id:a(),created_at:a().optional()});S(Pc);const qc=_({id:a().optional().openapi({description:"The unique identifier of the role. If not provided, one will be generated."}),name:a().min(1).max(50).openapi({description:"The name of the role. Cannot include '<' or '>'"}),description:a().max(255).optional().openapi({description:"The description of the role"}),is_system:h().optional(),metadata:M(V()).optional().openapi({description:"Metadata associated with the role. Can be used to control sync behavior in multi-tenancy scenarios."})}),Bc=qc.extend({id:a().openapi({description:"The unique identifier of the role"}),created_at:a().optional(),updated_at:a().optional()});S(Bc);const $c=_({logo_url:a().optional().openapi({description:"URL of the organization's logo"}),colors:_({primary:a().optional().openapi({description:"Primary color in hex format (e.g., #FF0000)"}),page_background:a().optional().openapi({description:"Page background color in hex format (e.g., #FFFFFF)"})}).optional()}).optional(),jc=_({connection_id:a().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"})}),Vc=_({client_credentials:_({enforce:h().default(!1).openapi({description:"Whether to enforce token quota limits"}),per_day:x().min(0).default(0).openapi({description:"Maximum tokens per day (0 = unlimited)"}),per_hour:x().min(0).default(0).openapi({description:"Maximum tokens per hour (0 = unlimited)"})}).optional()}).optional(),Hc=_({id:a().optional(),name:a().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:a().optional().openapi({description:"The display name of the organization"}),branding:$c,metadata:M(V()).default({}).optional().openapi({description:"Custom metadata for the organization"}),enabled_connections:S(jc).default([]).optional().openapi({description:"List of enabled connections for the organization"}),token_quota:Vc});_({...Hc.shape,...He.shape,id:a(),name:a().min(1).openapi({description:"The name of the organization"})});const Zc=_({connection_id:a().openapi({description:"ID of the tenant-level connection to enable for the org."}),assign_membership_on_login:h().optional().default(!1),show_as_button:h().optional().default(!0),is_signup_enabled:h().optional().default(!0)}),Kc=_({...Zc.shape,connection:_({name:a().optional(),strategy:a().optional()}).optional(),created_at:a().optional(),updated_at:a().optional()});S(Kc);const Wc=_({user_id:a().openapi({description:"ID of the user"}),organization_id:a().openapi({description:"ID of the organization"})});_({...Wc.shape,...He.shape,id:a()});_({idle_session_lifetime:x().default(72),session_lifetime:x().default(168),session_cookie:_({mode:b(["persistent","non-persistent"]).optional()}).optional(),enable_client_connections:h().optional(),default_redirection_uri:a().optional(),enabled_locales:S(a()).optional(),default_directory:a().optional(),error_page:_({html:a().optional(),show_log_link:h().optional(),url:a().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:a().optional(),picture_url:a().optional(),support_email:a().optional(),support_url:a().optional(),sandbox_version:a().optional(),sandbox_versions_available:S(a()).optional(),change_password:_({enabled:h(),html:a()}).optional(),guardian_mfa_page:_({enabled:h(),html:a()}).optional(),default_audience:a().optional(),default_organization:a().optional(),sessions:_({oidc_logout_prompt_enabled:h().optional()}).optional(),mfa:_({policy:b(["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:b(["twilio","vonage","aws_sns","phone_message_hook"]).optional()}).optional(),twilio:_({sid:a().optional(),auth_token:a().optional(),from:a().optional(),messaging_service_sid:a().optional()}).optional(),phone_message:_({message:a().optional()}).optional()}).optional()});_({date:a().openapi({description:"Date these events occurred in ISO 8601 format",example:"2025-12-19"}),logins:x().openapi({description:"Number of logins on this date",example:150}),signups:x().openapi({description:"Number of signups on this date",example:25}),leaked_passwords:x().openapi({description:"Number of breached-password detections on this date (subscription required)",example:0}),updated_at:a().openapi({description:"Date and time this stats entry was last updated in ISO 8601 format",example:"2025-12-19T10:30:00.000Z"}),created_at:a().openapi({description:"Approximate date and time the first event occurred in ISO 8601 format",example:"2025-12-19T00:00:00.000Z"})});x().openapi({description:"Number of active users in the last 30 days",example:1234});b(["active-users","logins","signups","refresh-tokens","sessions"]);b(["hour","day","week","month"]);b(["time","connection","client_id","user_type","event"]);b(["password","social","passwordless","enterprise"]);const Gc=_({name:a(),type:a()}),Jc=_({elapsed:x(),rows_read:x().optional(),bytes_read:x().optional()});_({meta:S(Gc),data:S(M(a(),V())),rows:x(),rows_before_limit_at_least:x().optional(),statistics:Jc.optional()});const Qc=b(["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"]),Xc=M(a(),M(a(),a())).openapi({type:"object",additionalProperties:{type:"object",additionalProperties:{type:"string"}}});_({prompt:Qc,language:a(),custom_text:Xc});const Yc=b(["phone","totp","email","push","webauthn-roaming","webauthn-platform","passkey"]),Bs=_({user_id:a(),type:Yc,phone_number:a().optional(),totp_secret:a().optional(),credential_id:a().optional(),public_key:a().optional(),sign_count:x().int().nonnegative().optional(),credential_backed_up:h().optional(),transports:S(a()).optional(),friendly_name:a().optional(),confirmed:h().default(!1)});function $s(n,e){n.type==="phone"&&!n.phone_number&&e.addIssue({code:N.custom,message:"phone_number is required when type is 'phone'",path:["phone_number"]}),n.type==="totp"&&!n.totp_secret&&e.addIssue({code:N.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:N.custom,message:`credential_id is required when type is '${n.type}'`,path:["credential_id"]}),n.public_key||e.addIssue({code:N.custom,message:`public_key is required when type is '${n.type}'`,path:["public_key"]}))}Bs.superRefine($s);_({...Bs.shape,id:a(),created_at:a(),updated_at:a()}).superRefine($s);function e_(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function t_(n){if(!n)return;const e=JSON.parse(n);return e_(e)?e:void 0}function Un(n){return n==null?void 0:new Date(n).toISOString()}function an(n){if(!n)return null;const e=new Date(n);return isNaN(e.getTime())?null:e.getTime()}function Fn(n){const e=xs.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:t_(n.constraints),single_use:!!n.single_use,expires_at:Un(n.expires_at_ts),used_at:Un(n.used_at_ts),revoked_at:Un(n.revoked_at_ts),created_at:new Date(n.created_at_ts).toISOString()}}function n_(n){return{async create(e,t){const i=Date.now();return await n.insert(X).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:an(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(X).where(g(c(X.tenant_id,e),c(X.id,t))).get();return i?Fn(i):null},async getByHash(e,t){const i=await n.select().from(X).where(g(c(X.tenant_id,e),c(X.token_hash,t))).get();return i?Fn(i):null},async listByClient(e,t){return(await n.select().from(X).where(g(c(X.tenant_id,e),c(X.client_id,t))).orderBy(se(X.created_at_ts))).map(Fn)},async markUsed(e,t,i){return(await n.update(X).set({used_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.id,t),Ce(X.used_at_ts))).returning()).length>0},async revoke(e,t,i){return(await n.update(X).set({revoked_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.id,t),Ce(X.revoked_at_ts))).returning()).length>0},async revokeByClient(e,t,i){return(await n.update(X).set({revoked_at_ts:an(i)}).where(g(c(X.tenant_id,e),c(X.client_id,t),Ce(X.revoked_at_ts))).returning()).length},async remove(e,t){return(await n.delete(X).where(g(c(X.tenant_id,e),c(X.id,t))).returning()).length>0}}}function zn(n){const{tenant_id:e,...t}=n;return G(t)}function i_(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),zn(i)},async get(e,t,i){if(!e)throw new Error("tenant_id is required");const o=await n.select().from(re).where(g(c(re.tenant_id,e),c(re.code_id,t),c(re.code_type,i))).get();return o?zn(o):null},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(re).where(c(re.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=re[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(zn);if(!s)return{codes:f};const[p]=await n.select({count:ge()}).from(re).where(c(re.tenant_id,e));return{codes:f,start:i*o,limit:o,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),Ce(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 o_(){const{customAlphabet:n}=require("nanoid");return`con_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Mn(n){const{tenant_id:e,is_system:t,options:i,metadata:o,...s}=n;return G({...s,options:z(i,{}),metadata:z(o),is_system:t?!0:void 0})}function a_(n){return{async create(e,t){var s,l;const i=new Date().toISOString(),o={id:t.id||o_(),...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(o)}catch(d){throw(s=d==null?void 0:d.message)!=null&&s.includes("UNIQUE constraint failed")||(l=d==null?void 0:d.message)!=null&&l.includes("duplicate key")?new _t(409,{message:"Connection already exists"}):d}return Mn(o)},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?Mn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.strategy!==void 0&&(o.strategy=i.strategy),i.options!==void 0&&(o.options=JSON.stringify(i.options)),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.display_name!==void 0&&(o.display_name=i.display_name),i.response_type!==void 0&&(o.response_type=i.response_type),i.response_mode!==void 0&&(o.response_mode=i.response_mode),await n.update(pe).set(o).where(g(c(pe.tenant_id,e),c(pe.id,t))),!0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=c(pe.tenant_id,e);if(d){const E=Qe(pe,d,["name"]);E&&(u=g(u,E))}let f=n.select().from(pe).where(u).$dynamic();if(l!=null&&l.sort_by){const E=pe[l.sort_by];E&&(f=f.orderBy(l.sort_order==="desc"?se(E):he(E)))}const m=(await f.offset(i*o).limit(o)).map(Mn);if(!s)return{connections:m};const[y]=await n.select({count:ge()}).from(pe).where(u);return{connections:m,start:i*o,limit:o,length:Number((y==null?void 0:y.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 sn(n){const{tenant_id:e,domain_metadata:t,...i}=n;return G({...i,primary:!!i.primary,domain_metadata:z(t)})}function s_(n){return{async create(e,t){const i=new Date().toISOString(),s={custom_domain_id:t.custom_domain_id||Le(),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(Ie).values(s),sn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(Ie).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).get();return i?sn(i):null},async getByDomain(e){const t=await n.select().from(Ie).where(c(Ie.domain,e)).get();return t?{...sn(t),tenant_id:t.tenant_id}:null},async list(e){return(await n.select().from(Ie).where(c(Ie.tenant_id,e)).all()).map(sn)},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.domain!==void 0&&(o.domain=i.domain),i.primary!==void 0&&(o.primary=i.primary),i.status!==void 0&&(o.status=i.status),i.type!==void 0&&(o.type=i.type),i.origin_domain_name!==void 0&&(o.origin_domain_name=i.origin_domain_name),i.verification!==void 0&&(o.verification=i.verification),i.custom_client_ip_header!==void 0&&(o.custom_client_ip_header=i.custom_client_ip_header),i.tls_policy!==void 0&&(o.tls_policy=i.tls_policy),i.domain_metadata!==void 0&&(o.domain_metadata=JSON.stringify(i.domain_metadata)),(await n.update(Ie).set(o).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).returning()).length>0},async remove(e,t){return(await n.delete(Ie).where(g(c(Ie.tenant_id,e),c(Ie.custom_domain_id,t))).returning()).length>0}}}function r_(n){return{async get(e,t,i){const o=await n.select().from(Se).where(g(c(Se.tenant_id,e),c(Se.prompt,t),c(Se.language,i))).get();if(!o)return null;try{return JSON.parse(o.custom_text)}catch{return null}},async set(e,t,i,o){const s=Date.now(),l=JSON.stringify(o);await n.insert(Se).values({tenant_id:e,prompt:t,language:i,custom_text:l,created_at_ts:s,updated_at_ts:s}).onConflictDoUpdate({target:[Se.tenant_id,Se.prompt,Se.language],set:{custom_text:l,updated_at_ts:s}})},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 l_(n){return{async create(e,t){const i=new Date().toISOString();await n.insert(dt).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(dt).where(c(dt.tenant_id,e)).get();if(!t)return null;const{tenant_id:i,...o}=t;return G({...o,enabled:!!o.enabled,credentials:z(o.credentials,{}),settings:z(o.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(dt).set(i).where(c(dt.tenant_id,e))},async remove(e){await n.delete(dt).where(c(dt.tenant_id,e))}}}function Ci(n){const e={template:n.template,body:n.body,from:n.from,subject:n.subject,syntax:"liquid",includeEmailInRedirect:!!n.include_email_in_redirect,enabled:!!n.enabled};return G({...e,resultUrl:n.result_url??void 0,urlLifetimeInSeconds:n.url_lifetime_in_seconds??void 0})}function d_(n){return{async get(e,t){const i=await n.select().from(Ue).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).get();return i?Ci(i):null},async list(e){return(await n.select().from(Ue).where(c(Ue.tenant_id,e)).all()).map(Ci)},async create(e,t){const i=new Date().toISOString();return await n.insert(Ue).values({tenant_id:e,template:t.template,body:t.body,from:t.from,subject:t.subject,syntax:t.syntax,result_url:t.resultUrl??null,url_lifetime_in_seconds:t.urlLifetimeInSeconds??null,include_email_in_redirect:t.includeEmailInRedirect,enabled:t.enabled,created_at:i,updated_at:i}),t},async update(e,t,i){const o={updated_at:new Date().toISOString()};i.body!==void 0&&(o.body=i.body),i.from!==void 0&&(o.from=i.from),i.subject!==void 0&&(o.subject=i.subject),i.syntax!==void 0&&(o.syntax=i.syntax),i.resultUrl!==void 0&&(o.result_url=i.resultUrl),i.urlLifetimeInSeconds!==void 0&&(o.url_lifetime_in_seconds=i.urlLifetimeInSeconds),i.includeEmailInRedirect!==void 0&&(o.include_email_in_redirect=i.includeEmailInRedirect),i.enabled!==void 0&&(o.enabled=i.enabled);const s=await n.update(Ue).set(o).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).run();return Number(s.changes??0)>0},async remove(e,t){const i=await n.delete(Ue).where(g(c(Ue.tenant_id,e),c(Ue.template,t))).run();return Number(i.changes??0)>0}}}function c_(n){return{async create(e,t){const i=new Date().toISOString(),o=`af_${Le()}`;return await n.insert(Oe).values({id:o,tenant_id:e,name:t.name,actions:JSON.stringify(t.actions||[]),created_at:i,updated_at:i}),{id:o,name:t.name,actions:t.actions||[],created_at:i,updated_at:i}},async get(e,t){const i=await n.select().from(Oe).where(g(c(Oe.tenant_id,e),c(Oe.id,t))).get();if(!i)return null;const{tenant_id:o,actions:s,...l}=i;return G({...l,actions:z(s,[])})},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.actions!==void 0&&(o.actions=JSON.stringify(i.actions)),(await n.update(Oe).set(o).where(g(c(Oe.tenant_id,e),c(Oe.id,t))).returning()).length===0?null:this.get(e,t)},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(Oe).where(c(Oe.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=Oe[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(m=>{const{tenant_id:y,actions:E,...A}=m;return G({...A,actions:z(E,[])})});if(!s)return{flows:f};const[p]=await n.select({count:ge()}).from(Oe).where(c(Oe.tenant_id,e));return{flows:f,start:i*o,limit:o,length:Number((p==null?void 0:p.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 rn=["nodes","start","ending"];function __(n){return{async create(e,t){const i=new Date().toISOString(),o=Le(),s={id:o,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 rn)s[l]=JSON.stringify(t[l]||(l==="nodes"?[]:{}));return await n.insert(ke).values(s),{id:o,...t,created_at:i,updated_at:i}},async get(e,t){const i=await n.select().from(ke).where(g(c(ke.tenant_id,e),c(ke.id,t))).get();if(!i)return null;const{tenant_id:o,...s}=i,l={...s};for(const d of rn)l[d]=z(s[d]);return G(l)},async update(e,t,i){const o={updated_at:new Date().toISOString()};for(const[l,d]of Object.entries(i))d!==void 0&&(rn.includes(l)?o[l]=JSON.stringify(d):o[l]=d);return(await n.update(ke).set(o).where(g(c(ke.tenant_id,e),c(ke.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(ke).where(c(ke.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=ke[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(m=>{const{tenant_id:y,...E}=m,A={...E};for(const J of rn)A[J]=z(E[J]);return G(A)});if(!s)return{forms:f};const[p]=await n.select({count:ge()}).from(ke).where(c(ke.tenant_id,e));return{forms:f,start:i*o,limit:o,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(ke).where(g(c(ke.tenant_id,e),c(ke.id,t))).returning()).length>0}}}function js(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 ci(n,e=new Date(0).toISOString()){return js(n)??e}function ne(n){if(!n||n==="")return null;const e=new Date(n);return isNaN(e.getTime())?null:e.getTime()}function nn(n,e,t=[]){const i={};for(const o of e){const s=o.replace(/_ts$/,"");i[s]=ci(n[o])}for(const o of t){const s=o.replace(/_ts$/,"");i[s]=js(n[o])}return i}const u_=Or("0123456789abcdefghijklmnopqrstuvwxyz",17);function p_(){return`hc_${u_()}`}function Di(n){const{created_at_ts:e,updated_at_ts:t,secrets:i,...o}=n,s=nn({created_at_ts:e,updated_at_ts:t},["created_at_ts","updated_at_ts"]);return{...o,...s,secrets:i?JSON.parse(i):void 0}}function f_(n){return{async create(e,t){const i=Date.now(),s={id:p_(),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(Ke).values(s),Di({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(Ke).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).get();return i?Di(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.code!==void 0&&(o.code=i.code),i.secrets!==void 0&&(o.secrets=JSON.stringify(i.secrets)),(await n.update(Ke).set(o).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).returning()).length>0},async remove(e,t){return(await n.delete(Ke).where(g(c(Ke.tenant_id,e),c(Ke.id,t))).returning()).length>0}}}function h_(){const{customAlphabet:n}=require("nanoid");return`h_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function g_(n){if(!(typeof n!="string"||!n))try{const e=JSON.parse(n);return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}catch{return}}function Pn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,metadata:o,...s}=n,l=nn({created_at_ts:t,updated_at_ts:i},["created_at_ts","updated_at_ts"]);return G({...s,enabled:!!s.enabled,synchronous:!!s.synchronous,metadata:g_(o),...l})}function m_(n){return{async create(e,t){const i=Date.now(),s={hook_id:t.hook_id||h_(),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,metadata:t.metadata?JSON.stringify(t.metadata):null,created_at_ts:i,updated_at_ts:i};return await n.insert(me).values(s),Pn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(me).where(g(c(me.tenant_id,e),c(me.hook_id,t))).get();return i?Pn(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.trigger_id!==void 0&&(o.trigger_id=i.trigger_id),i.url!==void 0&&(o.url=i.url),i.enabled!==void 0&&(o.enabled=i.enabled),i.synchronous!==void 0&&(o.synchronous=i.synchronous),i.priority!==void 0&&(o.priority=i.priority),i.form_id!==void 0&&(o.form_id=i.form_id),i.template_id!==void 0&&(o.template_id=i.template_id),i.code_id!==void 0&&(o.code_id=i.code_id),i.metadata!==void 0&&(o.metadata=i.metadata===null?null:JSON.stringify(i.metadata)),(await n.update(me).set(o).where(g(c(me.tenant_id,e),c(me.hook_id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?Qe(me,d,["url","form_id","template_id","code_id"]):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();const m=l!=null&&l.sort_by?me[l.sort_by]:void 0;m?p=p.orderBy((l==null?void 0:l.sort_order)==="desc"?se(m):he(m)):p=p.orderBy(se(me.priority),he(me.created_at_ts));const E=(await p.offset(i*o).limit(o)).map(Pn);if(!s)return{hooks:E};const[A]=await n.select({count:ge()}).from(me).where(f);return{hooks:E,start:i*o,limit:o,length:Number((A==null?void 0:A.count)??0)}},async remove(e,t){return(await n.delete(me).where(g(c(me.tenant_id,e),c(me.hook_id,t))).returning()).length>0}}}function y_(){const{customAlphabet:n}=require("nanoid");return`inv_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const _i=["inviter","invitee","app_metadata","user_metadata","roles"];function qn(n){const{tenant_id:e,send_invitation_email:t,...i}=n,o={...i};for(const s of _i)o[s]=z(i[s],s==="roles"?[]:{});return o.send_invitation_email=!!t,G(o)}function v_(n){return{async create(e,t){var u,f;const i=t.id||y_(),o=t.ttl_sec||604800,s=new Date,l=new Date(s.getTime()+o*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:o,send_invitation_email:t.send_invitation_email!==!1?1:0,created_at:s.toISOString(),expires_at:l};for(const p of _i)t[p]!==void 0&&(d[p]=JSON.stringify(t[p]));try{await n.insert(xe).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 _t(409,{message:"Invite already exists"}):p}return qn({...d,tenant_id:e})},async get(e,t){const i=await n.select().from(xe).where(g(c(xe.tenant_id,e),c(xe.id,t))).get();return i?qn(i):null},async update(e,t,i){const o={};for(const l of _i)i[l]!==void 0&&(o[l]=JSON.stringify(i[l]));return i.connection_id!==void 0&&(o.connection_id=i.connection_id),i.ttl_sec!==void 0&&(o.ttl_sec=i.ttl_sec,o.expires_at=new Date(Date.now()+i.ttl_sec*1e3).toISOString()),(await n.update(xe).set(o).where(g(c(xe.tenant_id,e),c(xe.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l}=t||{};let d=n.select().from(xe).where(c(xe.tenant_id,e)).$dynamic();if(l!=null&&l.sort_by){const m=xe[l.sort_by];m&&(d=d.orderBy(l.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(i*o).limit(o)).map(qn);if(!s)return{invites:f};const[p]=await n.select({count:ge()}).from(xe).where(c(xe.tenant_id,e));return{invites:f,start:i*o,limit:o,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}}}function w_(n){return{async create(e){await n.insert(We).values({...e,created_at:new Date().toDateString()})},async list(e){const{page:t=0,per_page:i=50,include_totals:o=!1,sort:s}=e||{},l=new Date().toISOString();let d=n.select().from(We).where($e(pn(We.revoked_at,l),Ce(We.revoked_at))).$dynamic();if(s!=null&&s.sort_by){const m=We[s.sort_by];m&&(d=d.orderBy(s.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(t*i).limit(i)).map(m=>{const{created_at:y,...E}=m;return G(E)});if(!o)return{signingKeys:f};const[p]=await n.select({count:ge()}).from(We).where($e(pn(We.revoked_at,l),Ce(We.revoked_at)));return{signingKeys:f,start:t*i,limit:i,length:yr((p==null?void 0:p.count)??0)}},async update(e,t){return(await n.update(We).set(t).where(c(We.kid,e)).returning()).length>0}}}const ui="0123456789ABCDEFGHJKMNPQRSTVWXYZ",Bn=ui.length;function N_(){let t=Date.now(),i="";for(let s=10;s>0;s--)i=ui.charAt(t%Bn)+i,t=Math.floor(t/Bn);const o=new Uint8Array(16);crypto.getRandomValues(o);for(let s=0;s<16;s++)i+=ui.charAt(o[s]%Bn);return i}function Li(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,expires_at_ts:o,state_data:s,auth_params:l,...d}=n,u=nn({created_at_ts:t,updated_at_ts:i,expires_at_ts:o},["created_at_ts","updated_at_ts","expires_at_ts"]),f={};for(const[m,y]of Object.entries(d))y!=null&&(f[m]=y);const p=_s(f,["auth_strategy"]);return G({...p,authParams:typeof l=="string"&&l.length>0?JSON.parse(l):{},...u,state_data:z(s)})}function S_(n){return{async create(e,t){var l,d;const i=Date.now(),s={id:N_(),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(Y).values(s),Li({...s,tenant_id:e})},async get(e,t){const i=e?g(c(Y.tenant_id,e),c(Y.id,t)):c(Y.id,t),o=await n.select().from(Y).where(i).get();return o?Li(o):null},async update(e,t,i){var s,l,d;const o={updated_at_ts:Date.now()};if(i.session_id!==void 0&&(o.session_id=i.session_id),i.state!==void 0&&(o.state=i.state),i.state_data!==void 0&&(o.state_data=JSON.stringify(i.state_data)),i.failure_reason!==void 0&&(o.failure_reason=i.failure_reason),i.user_id!==void 0&&(o.user_id=i.user_id),i.auth_connection!==void 0&&(o.auth_connection=i.auth_connection),i.auth_strategy!==void 0&&(o.auth_strategy_strategy=(s=i.auth_strategy)==null?void 0:s.strategy,o.auth_strategy_strategy_type=(l=i.auth_strategy)==null?void 0:l.strategy_type),i.authenticated_at!==void 0&&(o.authenticated_at=i.authenticated_at),i.authorization_url!==void 0&&(o.authorization_url=(d=i.authorization_url)==null?void 0:d.substring(0,1024)),i.expires_at!==void 0&&(o.expires_at_ts=ne(i.expires_at)),i.authParams!==void 0){const u=await n.select({auth_params:Y.auth_params}).from(Y).where(g(c(Y.tenant_id,e),c(Y.id,t))).get(),f=u!=null&&u.auth_params&&typeof u.auth_params=="string"&&u.auth_params.length>0?JSON.parse(u.auth_params):{};o.auth_params=JSON.stringify({...f,...i.authParams})}return await n.update(Y).set(o).where(g(c(Y.tenant_id,e),c(Y.id,t))),!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 $n(n){const{tenant_id:e,isMobile:t,auth0_client:i,details:o,country_code:s,city_name:l,latitude:d,longitude:u,time_zone:f,continent_code:p,scope:m,...y}=n,E={...y,isMobile:!!t,auth0_client:z(i),details:z(o),scope:m?m.split(","):void 0};return s&&(E.location_info=G({country_code:s,city_name:l,latitude:d,longitude:u,time_zone:f,continent_code:p})),G(E)}function b_(n){return{async create(e,t){var s,l;const o={log_id:t.log_id||Le(),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:(s=t.user_agent)==null?void 0:s.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&&(o.auth0_client=JSON.stringify(t.auth0_client)),t.details&&(o.details=JSON.stringify(t.details).substring(0,8192)),t.location_info&&(o.country_code=t.location_info.country_code,o.city_name=t.location_info.city_name,o.latitude=t.location_info.latitude,o.longitude=t.location_info.longitude,o.time_zone=t.location_info.time_zone,o.continent_code=t.location_info.continent_code),await n.insert(F).values(o),$n({...o,tenant_id:e})},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d,from_date:u,to_date:f}=t||{},p=[c(F.tenant_id,e)];if(d){const Q=Qe(F,d,["user_id","ip","type","client_id"]);Q&&p.push(Q)}typeof u=="number"&&Number.isFinite(u)&&p.push(At(F.date,new Date(Math.floor(u)*1e3).toISOString())),typeof f=="number"&&Number.isFinite(f)&&p.push(Ge(F.date,new Date((Math.floor(f)+1)*1e3).toISOString()));const m=g(...p);let y=n.select().from(F).where(m).$dynamic();if(l!=null&&l.sort_by){const Q=F[l.sort_by];Q&&(y=y.orderBy(l.sort_order==="desc"?se(Q):he(Q)))}else y=y.orderBy(se(F.date));const A=(await y.offset(i*o).limit(o)).map($n);if(!s)return{logs:A};const[J]=await n.select({count:ge()}).from(F).where(m);return{logs:A,start:i*o,limit:o,length:Number((J==null?void 0:J.count)??0)}},async get(e,t){const i=await n.select().from(F).where(g(c(F.tenant_id,e),c(F.log_id,t))).get();return i?$n(i):null}}}const pi="0123456789ABCDEFGHJKMNPQRSTVWXYZ",jn=pi.length;function E_(){let t=Date.now(),i="";for(let s=10;s>0;s--)i=pi.charAt(t%jn)+i,t=Math.floor(t/jn);const o=new Uint8Array(16);crypto.getRandomValues(o);for(let s=0;s<16;s++)i+=pi.charAt(o[s]%jn);return i}function ln(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,credential_backed_up:o,confirmed:s,transports:l,...d}=n;return G({...d,confirmed:!!s,credential_backed_up:o!=null?!!o:void 0,transports:z(l),created_at:ci(t),updated_at:ci(i)})}function x_(n){return{async create(e,t){const i=Date.now(),s={id:t.id||E_(),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(s),ln({...s,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?ln(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?ln(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(ln)},async update(e,t,i){const o={updated_at_ts:Date.now()};i.type!==void 0&&(o.type=i.type),i.phone_number!==void 0&&(o.phone_number=i.phone_number),i.totp_secret!==void 0&&(o.totp_secret=i.totp_secret),i.credential_id!==void 0&&(o.credential_id=i.credential_id),i.public_key!==void 0&&(o.public_key=i.public_key),i.sign_count!==void 0&&(o.sign_count=i.sign_count),i.credential_backed_up!==void 0&&(o.credential_backed_up=i.credential_backed_up?1:0),i.transports!==void 0&&(o.transports=JSON.stringify(i.transports)),i.friendly_name!==void 0&&(o.friendly_name=i.friendly_name),i.confirmed!==void 0&&(o.confirmed=i.confirmed?1:0),await n.update(ue).set(o).where(g(c(ue.tenant_id,e),c(ue.id,t)));const s=await this.get(e,t);if(!s)throw new Error(`Authentication method ${t} not found after update`);return s},async remove(e,t){return(await n.delete(ue).where(g(c(ue.tenant_id,e),c(ue.id,t))).returning()).length>0}}}function k_(){const{customAlphabet:n}=require("nanoid");return`org_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}function Vn(n){const{tenant_id:e,branding:t,metadata:i,enabled_connections:o,token_quota:s,...l}=n;return G({...l,branding:z(t,{}),metadata:z(i,{}),enabled_connections:z(o,[]),token_quota:z(s,{})})}function O_(n){return{async create(e,t){var l,d;const i=new Date().toISOString(),s={id:t.id||k_(),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(ee).values(s)}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 _t(409,{message:"Organization already exists"}):u}return Vn({...s,tenant_id:e})},async get(e,t){let i=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.id,t))).get();return i||(i=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.name,t))).get()),i?Vn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.display_name!==void 0&&(o.display_name=i.display_name),i.branding!==void 0&&(o.branding=JSON.stringify(i.branding)),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.enabled_connections!==void 0&&(o.enabled_connections=JSON.stringify(i.enabled_connections)),i.token_quota!==void 0&&(o.token_quota=JSON.stringify(i.token_quota)),(await n.update(ee).set(o).where(g(c(ee.tenant_id,e),c(ee.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(ee).where(c(ee.tenant_id,e)).$dynamic();if(d&&(u=u.where($e(xt(ee.name,`%${d}%`),xt(ee.display_name,`%${d}%`)))),l!=null&&l.sort_by){const E=ee[l.sort_by];E&&(u=u.orderBy(l.sort_order==="desc"?se(E):he(E)))}const p=(await u.offset(i*o).limit(o)).map(Vn);if(!s)return{organizations:p};const m=[c(ee.tenant_id,e)];d&&m.push($e(xt(ee.name,`%${d}%`),xt(ee.display_name,`%${d}%`)));const[y]=await n.select({count:ge()}).from(ee).where(g(...m));return{organizations:p,start:i*o,limit:o,length:Number((y==null?void 0:y.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 Hn(n){const{tenant_id:e,is_current:t,...i}=n;return{...i,is_current:!!t}}function A_(n){return{async create(e,t){const i=new Date().toISOString(),o=t.id||Le();t.is_current!==!1&&await n.update(oe).set({is_current:0}).where(g(c(oe.tenant_id,e),c(oe.user_id,t.user_id)));const s={id:o,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(oe).values(s),Hn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(oe).where(g(c(oe.tenant_id,e),c(oe.user_id,t),c(oe.is_current,1))).get();return i?Hn(i):null},async list(e,t,i){let o=n.select().from(oe).where(g(c(oe.tenant_id,e),c(oe.user_id,t))).orderBy(se(oe.created_at)).$dynamic();return i&&(o=o.limit(i)),(await o).map(Hn)},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(oe).set(i).where(g(c(oe.tenant_id,e),c(oe.id,t.id))):await n.update(oe).set(i).where(g(c(oe.tenant_id,e),c(oe.user_id,t.user_id),c(oe.is_current,1))),!0}}}function T_(n){return{async get(e){const t=await n.select().from(Ut).where(c(Ut.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(Ut).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:Ut.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 dn(n){const{tenant_id:e,created_at_ts:t,expires_at_ts:i,idle_expires_at_ts:o,last_exchanged_at_ts:s,revoked_at_ts:l,rotated_at_ts:d,device:u,resource_servers:f,rotating:p,...m}=n,y=nn({created_at_ts:t,expires_at_ts:i,idle_expires_at_ts:o,last_exchanged_at_ts:s,revoked_at_ts:l,rotated_at_ts:d},["created_at_ts"],["expires_at_ts","idle_expires_at_ts","last_exchanged_at_ts","revoked_at_ts","rotated_at_ts"]);return G({...m,...y,rotating:!!p,device:z(u,{}),resource_servers:z(f,[])})}function I_(n,e){return Math.max(n??0,e??0)}function C_(n){return{async create(e,t){const i=Date.now(),o={id:t.id||Le(),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,token_lookup:t.token_lookup??null,token_hash:t.token_hash??null,family_id:t.family_id??null,rotated_to:t.rotated_to??null,rotated_at_ts:ne(t.rotated_at),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(O`BEGIN`);try{await n.insert(W).values(o);const s=I_(o.expires_at_ts,o.idle_expires_at_ts);s>0&&o.login_id&&await n.update(Y).set({expires_at_ts:s,updated_at_ts:i}).where(g(c(Y.tenant_id,e),c(Y.id,o.login_id),Ge(Y.expires_at_ts,s))),await n.run(O`COMMIT`)}catch(s){throw await n.run(O`ROLLBACK`),s}return dn({...o,tenant_id:e})},async get(e,t){const i=await n.select().from(W).where(g(c(W.tenant_id,e),c(W.id,t))).get();return i?dn(i):null},async getByLookup(e,t){const i=await n.select().from(W).where(g(c(W.tenant_id,e),c(W.token_lookup,t))).get();return i?dn(i):null},async update(e,t,i,o){const s={};i.device!==void 0&&(s.device=JSON.stringify(i.device)),i.resource_servers!==void 0&&(s.resource_servers=JSON.stringify(i.resource_servers)),i.rotating!==void 0&&(s.rotating=i.rotating),i.token_lookup!==void 0&&(s.token_lookup=i.token_lookup),i.token_hash!==void 0&&(s.token_hash=i.token_hash),i.family_id!==void 0&&(s.family_id=i.family_id),i.rotated_to!==void 0&&(s.rotated_to=i.rotated_to),i.rotated_at!==void 0&&(s.rotated_at_ts=ne(i.rotated_at)),i.expires_at!==void 0&&(s.expires_at_ts=ne(i.expires_at)),i.idle_expires_at!==void 0&&(s.idle_expires_at_ts=ne(i.idle_expires_at)),i.last_exchanged_at!==void 0&&(s.last_exchanged_at_ts=ne(i.last_exchanged_at)),i.revoked_at!==void 0&&(s.revoked_at_ts=ne(i.revoked_at));const l=o==null?void 0:o.loginSessionBump,d=l?ne(l.expires_at):null,u=await n.update(W).set(s).where(g(c(W.tenant_id,e),c(W.id,t))).returning();return l!=null&&l.login_id&&d&&d>0&&await n.update(Y).set({expires_at_ts:d,updated_at_ts:Date.now()}).where(g(c(Y.tenant_id,e),c(Y.id,l.login_id),Ge(Y.expires_at_ts,d))).catch(()=>{}),u.length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{};let u=n.select().from(W).where(c(W.tenant_id,e)).$dynamic();if(d){const y=Qe(W,d,["user_id"]);y&&(u=u.where(g(c(W.tenant_id,e),y)))}if(l!=null&&l.sort_by){const y=W[l.sort_by];y&&(u=u.orderBy(l.sort_order==="desc"?se(y):he(y)))}const p=(await u.offset(i*o).limit(o)).map(dn);if(!s)return{refresh_tokens:p};const[m]=await n.select({count:ge()}).from(W).where(c(W.tenant_id,e));return{refresh_tokens:p,start:i*o,limit:o,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},async revokeByLoginSession(e,t,i){return(await n.update(W).set({revoked_at_ts:ne(i)}).where(g(c(W.tenant_id,e),c(W.login_id,t),Ce(W.revoked_at_ts))).returning()).length},async revokeFamily(e,t,i){return(await n.update(W).set({revoked_at_ts:ne(i)}).where(g(c(W.tenant_id,e),c(W.family_id,t),Ce(W.revoked_at_ts))).returning()).length}}}function D_(){const{customAlphabet:n}=require("nanoid");return`api_${n("0123456789abcdefghijklmnopqrstuvwxyz",17)()}`}const fi=["skip_consent_for_verifiable_first_party_clients","allow_offline_access","is_system"],Ri=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:o,metadata:s,...l}=n,d={...l};d.scopes=z(i,[]),d.options=z(o,{}),d.metadata=z(s),t!==void 0&&(d.verificationKey=t);for(const u of fi)l[u]!==void 0&&l[u]!==null&&(d[u]=!!l[u]);return G(d)}function L_(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||D_(),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 fi)t[l]!==void 0&&(s[l]=t[l]?1:0);return s.is_system===void 0&&(s.is_system=0),await n.insert(te).values(s),Zn({...s,tenant_id:e})},async get(e,t){const i=await n.select().from(te).where(g(c(te.tenant_id,e),c(te.id,t))).get();return i?Zn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};i.name!==void 0&&(o.name=i.name),i.identifier!==void 0&&(o.identifier=i.identifier),i.signing_alg!==void 0&&(o.signing_alg=i.signing_alg),i.signing_secret!==void 0&&(o.signing_secret=i.signing_secret),i.token_lifetime!==void 0&&(o.token_lifetime=i.token_lifetime),i.token_lifetime_for_web!==void 0&&(o.token_lifetime_for_web=i.token_lifetime_for_web),i.scopes!==void 0&&(o.scopes=JSON.stringify(i.scopes)),i.options!==void 0&&(o.options=O`json_patch(COALESCE(${te.options}, '{}'), ${JSON.stringify(i.options)})`),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),i.verificationKey!==void 0&&(o.verification_key=i.verificationKey);for(const l of fi)i[l]!==void 0&&(o[l]=i[l]?1:0);return(await n.update(te).set(o).where(g(c(te.tenant_id,e),c(te.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=Math.max(0,Math.floor(Number(i)||0)),f=Math.min(Math.max(1,Math.floor(Number(o)||50)),500),p=[c(te.tenant_id,e)];if(d){const J=d.match(/^([^:]+):(.+)$/);if(J){const[,Q,ie]=J,Pe=Q==null?void 0:Q.startsWith("-"),Ne=Pe?Q==null?void 0:Q.substring(1):Q;if(Ne&&Ri.has(Ne)&&!Pe){const Ee=te[Ne];p.push(xt(Ee,`%${ie}%`))}}}let m=n.select().from(te).where(g(...p)).$dynamic();if(l!=null&&l.sort_by&&Ri.has(l.sort_by)){const J=te[l.sort_by];m=m.orderBy(l.sort_order==="desc"?se(J):he(J))}const E=(await m.offset(u*f).limit(f)).map(Zn);if(!s)return{resource_servers:E};const[A]=await n.select({count:ge()}).from(te).where(g(...p));return{resource_servers:E,start:u*f,limit:f,length:Number((A==null?void 0:A.count)??0)}},async remove(e,t){return(await n.delete(te).where(g(c(te.tenant_id,e),c(te.id,t))).returning()).length>0}}}function R_(n){return{async assign(e,t,i){const o=new Date().toISOString();return await n.insert(Re).values(i.map(s=>({tenant_id:e,role_id:t,resource_server_identifier:s.resource_server_identifier,permission_name:s.permission_name,created_at:o}))).onConflictDoNothing(),!0},async list(e,t,i){const o=await n.select({resource_server_identifier:Re.resource_server_identifier,permission_name:Re.permission_name,created_at:Re.created_at}).from(Re).where(g(c(Re.tenant_id,e),c(Re.role_id,t))).all(),s=[...new Set(o.map(d=>d.resource_server_identifier))],l=new Map;if(s.length>0){const d=await n.select({identifier:te.identifier,name:te.name}).from(te).where(g(c(te.tenant_id,e),De(te.identifier,s))).all();for(const u of d)l.set(u.identifier,u.name)}return o.map(d=>({...d,resource_server_name:l.get(d.resource_server_identifier)||d.resource_server_identifier}))},async remove(e,t,i){const o=i.map(l=>g(c(Re.resource_server_identifier,l.resource_server_identifier),c(Re.permission_name,l.permission_name)));return(await n.delete(Re).where(g(c(Re.tenant_id,e),c(Re.role_id,t),$e(...o))).returning()).length>0}}}function U_(n){return{async create(e,t,i,o){var s,l;try{await n.insert(qe).values({tenant_id:e,user_id:t,resource_server_identifier:i.resource_server_identifier,permission_name:i.permission_name,organization_id:o||"",created_at:new Date().toISOString()})}catch(d){if((s=d==null?void 0:d.message)!=null&&s.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,o){let s=[c(qe.tenant_id,e),c(qe.user_id,t)];o&&s.push(c(qe.organization_id,o));const l=await n.select().from(qe).where(g(...s)).all();return await Promise.all(l.map(async u=>{const f=await n.select({name:te.name}).from(te).where(g(c(te.tenant_id,e),c(te.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,o){return(await n.delete(qe).where(g(c(qe.tenant_id,e),c(qe.user_id,t),c(qe.resource_server_identifier,i.resource_server_identifier),c(qe.permission_name,i.permission_name),c(qe.organization_id,o||""))).returning()).length>0}}}function Kn(n){const{tenant_id:e,is_system:t,metadata:i,...o}=n;return G({...o,is_system:t?!0:void 0,metadata:z(i)})}function F_(n){return{async create(e,t){const i=new Date().toISOString(),s={id:t.id||Le(),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(s),Kn({...s,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?Kn(i):null},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.name!==void 0&&(o.name=i.name),i.description!==void 0&&(o.description=i.description),i.is_system!==void 0&&(o.is_system=i.is_system?1:0),i.metadata!==void 0&&(o.metadata=JSON.stringify(i.metadata)),(await n.update(_e).set(o).where(g(c(_e.tenant_id,e),c(_e.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?Qe(_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 A=_e[l.sort_by];A&&(p=p.orderBy(l.sort_order==="desc"?se(A):he(A)))}const y=(await p.offset(i*o).limit(o)).map(Kn);if(!s)return{roles:y};const[E]=await n.select({count:ge()}).from(_e).where(f);return{roles:y,start:i*o,limit:o,length:Number((E==null?void 0:E.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 z_=["created_at_ts","updated_at_ts"],M_=["expires_at_ts","idle_expires_at_ts","authenticated_at_ts","last_interaction_at_ts","used_at_ts","revoked_at_ts"];function Wn(n){const{tenant_id:e,created_at_ts:t,updated_at_ts:i,expires_at_ts:o,idle_expires_at_ts:s,authenticated_at_ts:l,last_interaction_at_ts:d,used_at_ts:u,revoked_at_ts:f,device:p,clients:m,...y}=n,E=nn({created_at_ts:t,updated_at_ts:i,expires_at_ts:o,idle_expires_at_ts:s,authenticated_at_ts:l,last_interaction_at_ts:d,used_at_ts:u,revoked_at_ts:f},[...z_],[...M_]);return G({...y,...E,device:z(p,{}),clients:z(m,[])})}function P_(n){return{async create(e,t){const i=Date.now(),o={id:t.id||Le(),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(ae).values(o),Wn({...o,tenant_id:e})},async get(e,t){const i=await n.select().from(ae).where(g(c(ae.tenant_id,e),c(ae.id,t))).get();return i?Wn(i):null},async update(e,t,i){const o={updated_at_ts:Date.now()};return i.user_id!==void 0&&(o.user_id=i.user_id),i.login_session_id!==void 0&&(o.login_session_id=i.login_session_id),i.device!==void 0&&(o.device=JSON.stringify(i.device)),i.clients!==void 0&&(o.clients=JSON.stringify(i.clients)),i.expires_at!==void 0&&(o.expires_at_ts=ne(i.expires_at)),i.idle_expires_at!==void 0&&(o.idle_expires_at_ts=ne(i.idle_expires_at)),i.authenticated_at!==void 0&&(o.authenticated_at_ts=ne(i.authenticated_at)),i.last_interaction_at!==void 0&&(o.last_interaction_at_ts=ne(i.last_interaction_at)),i.used_at!==void 0&&(o.used_at_ts=ne(i.used_at)),i.revoked_at!==void 0&&(o.revoked_at_ts=ne(i.revoked_at)),(await n.update(ae).set(o).where(g(c(ae.tenant_id,e),c(ae.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,sort:l,q:d}=t||{},u=d?Qe(ae,d,["user_id"]):void 0,f=u?g(c(ae.tenant_id,e),u):c(ae.tenant_id,e);let p=n.select().from(ae).where(f).$dynamic();if(l!=null&&l.sort_by){const A=ae[l.sort_by];A&&(p=p.orderBy(l.sort_order==="desc"?se(A):he(A)))}const y=(await p.offset(i*o).limit(o)).map(Wn);if(!s)return{sessions:y};const[E]=await n.select({count:ge()}).from(ae).where(f);return{sessions:y,start:i*o,limit:o,length:Number((E==null?void 0:E.count)??0)}},async remove(e,t){return(await n.delete(ae).where(g(c(ae.tenant_id,e),c(ae.id,t))).returning()).length>0}}}const Vs=["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"],Hs=["allow_organization_name_in_authentication_api","customize_mfa_in_postlogin_action","pushed_authorization_requests_supported","authorization_response_iss_parameter_supported"];function Ui(n){const e={...n};for(const t of Vs)typeof e[t]=="string"&&(e[t]=z(e[t]));for(const t of Hs)e[t]!==void 0&&e[t]!==null&&(e[t]=e[t]===1);return G(e)}function Fi(n){const e={...n};gr(n,Vs,e);for(const t of Hs)n[t]!==void 0&&(e[t]=n[t]?1:0);return cs(e)}function q_(n){return{async create(e){var o,s;const t={id:e.id||Le(),created_at:new Date().toISOString(),updated_at:new Date().toISOString(),...e},i=Fi(t);try{await n.insert(B).values(i)}catch(l){throw(o=l==null?void 0:l.message)!=null&&o.includes("UNIQUE constraint failed")||(s=l==null?void 0:l.message)!=null&&s.includes("duplicate key")||(l==null?void 0:l.code)==="SQLITE_CONSTRAINT"?new _t(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?Ui(t):null},async list(e){const{page:t=0,per_page:i=50,include_totals:o=!1,sort:s,q:l}=e||{};let d=n.select().from(B).$dynamic();if(l){const m=Qe(B,l,["friendly_name"]);m&&(d=d.where(m))}if(s!=null&&s.sort_by){const m=B[s.sort_by];m&&(d=d.orderBy(s.sort_order==="desc"?se(m):he(m)))}const f=(await d.offset(t*i).limit(i)).map(Ui);if(!o)return{tenants:f};const[p]=await n.select({count:ge()}).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=Fi({...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 B_=["colors","borders","fonts","page_background","widget"];function zi(n){const{tenant_id:e,...t}=n,i=_s(t,B_);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),G(i)}function $_(n){return{async create(e,t,i){const o=new Date().toISOString(),s=i||Le(),d={...Yn(t),tenant_id:e,themeId:s,created_at:o,updated_at:o};return await n.insert(Ze).values(d),zi({...d,tenant_id:e})},async get(e,t){const i=await n.select().from(Ze).where(g(c(Ze.tenant_id,e),c(Ze.themeId,t))).get();return i?zi(i):null},async update(e,t,i){const o=Yn(i);return o.updated_at=new Date().toISOString(),await n.update(Ze).set(o).where(g(c(Ze.tenant_id,e),c(Ze.themeId,t))),!0},async remove(e,t){return(await n.delete(Ze).where(g(c(Ze.tenant_id,e),c(Ze.themeId,t))).returning()).length>0}}}function j_(n){return{async get(e){const t=await n.select({body:lt.body}).from(lt).where(c(lt.tenant_id,e)).get();return t?{body:t.body}:null},async set(e,t){const i=Date.now();await n.insert(lt).values({tenant_id:e,body:t.body,created_at_ts:i,updated_at_ts:i}).onConflictDoUpdate({target:lt.tenant_id,set:{body:t.body,updated_at_ts:i}})},async delete(e){await n.delete(lt).where(c(lt.tenant_id,e))}}}function Mi(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 Gn(n,e=[]){const{tenant_id:t,app_metadata:i,user_metadata:o,address:s,email_verified:l,phone_verified:d,is_social:u,linked_to:f,profileData:p,...m}=n,y=Mi(n,!0),E=e.map(A=>Mi(A,!1));return G({...m,email:n.email||"",email_verified:!!l,phone_verified:d!=null?!!d:void 0,is_social:!!u,app_metadata:z(i,{}),user_metadata:z(o,{}),address:z(s),identities:[y,...E]})}function V_(n){const e=async(t,i)=>{var d,u;const o=new Date().toISOString(),s={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||o,updated_at:i.updated_at||o},l=i.password?Le():void 0;try{if(i.password&&l){await n.run(O`BEGIN`);try{await n.insert(H).values(s),await n.insert(oe).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:o,updated_at:o}),await n.run(O`COMMIT`)}catch(f){throw await n.run(O`ROLLBACK`),f}}else await n.insert(H).values(s)}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 _t(409,{message:"User already exists"}):(console.error("User upsert failed:",f==null?void 0:f.code,f==null?void 0:f.message),new _t(500,{message:"Internal server error"}))}return Gn(s)};return{create:e,rawCreate:e,async get(t,i){const o=await n.select().from(H).where(g(c(H.tenant_id,t),c(H.user_id,i))).get();if(!o)return null;const s=await n.select().from(H).where(g(c(H.tenant_id,t),c(H.linked_to,i))).all();return Gn(o,s)},async update(t,i,o){const s={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)o[u]!==void 0&&(s[u]=o[u]);return o.email_verified!==void 0&&(s.email_verified=o.email_verified),o.phone_verified!==void 0&&(s.phone_verified=o.phone_verified),o.is_social!==void 0&&(s.is_social=o.is_social),o.app_metadata!==void 0&&(s.app_metadata=JSON.stringify(o.app_metadata)),o.user_metadata!==void 0&&(s.user_metadata=JSON.stringify(o.user_metadata)),o.address!==void 0&&(s.address=JSON.stringify(o.address)),o.profileData!==void 0&&(s.profileData=JSON.stringify(o.profileData)),(await n.update(H).set(s).where(g(c(H.tenant_id,t),c(H.user_id,i))).returning()).length>0},async list(t,i){const{page:o=0,per_page:s=50,include_totals:l=!1,sort:d,q:u}=i||{},f=[c(H.tenant_id,t),Ce(H.linked_to)];if(u){const ie=Qe(H,u,["email","name","nickname","username"]);ie&&f.push(ie)}const p=g(...f);let m=n.select().from(H).where(p).$dynamic();if(d!=null&&d.sort_by){const ie=H[d.sort_by];ie&&(m=m.orderBy(d.sort_order==="desc"?se(ie):he(ie)))}const y=await m.offset(o*s).limit(s),E=y.map(ie=>ie.user_id);let A=[];E.length>0&&(A=await n.select().from(H).where(g(c(H.tenant_id,t),De(H.linked_to,E))));const J=y.map(ie=>{const Pe=A.filter(Ne=>Ne.linked_to===ie.user_id);return Gn(ie,Pe)});if(!l)return{users:J};const[Q]=await n.select({count:ge()}).from(H).where(p);return{users:J,start:o*s,limit:s,length:Number((Q==null?void 0:Q.count)??0)}},async remove(t,i){await n.run(O`BEGIN`);try{const o=await n.select({user_id:H.user_id}).from(H).where(g(c(H.tenant_id,t),c(H.linked_to,i))),s=[i,...o.map(d=>d.user_id)];await n.delete(ue).where(g(c(ue.tenant_id,t),De(ue.user_id,s))),await n.delete(oe).where(g(c(oe.tenant_id,t),De(oe.user_id,s))),await n.delete(H).where(g(c(H.tenant_id,t),c(H.linked_to,i)));const l=await n.delete(H).where(g(c(H.tenant_id,t),c(H.user_id,i))).returning();return await n.run(O`COMMIT`),l.length>0}catch(o){throw await n.run(O`ROLLBACK`),o}},async unlink(t,i,o,s){const l=`${o}|${s}`;return(await n.update(H).set({linked_to:null}).where(g(c(H.tenant_id,t),c(H.user_id,l),c(H.linked_to,i))).returning()).length>0}}}function H_(n){return{async create(e,t,i,o){var s,l;try{await n.insert(Be).values({tenant_id:e,user_id:t,role_id:i,organization_id:o||"",created_at:new Date().toISOString()})}catch(d){if((s=d==null?void 0:d.message)!=null&&s.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,o){let s=[c(Be.tenant_id,e),c(Be.user_id,t)];o&&s.push(c(Be.organization_id,o));const l=await n.select({role_id:Be.role_id}).from(Be).where(g(...s)).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:m,metadata:y,...E}=f;return G({...E,is_system:m?!0:void 0,metadata:z(y)})}))).filter(Boolean)},async remove(e,t,i,o){return(await n.delete(Be).where(g(c(Be.tenant_id,e),c(Be.user_id,t),c(Be.role_id,i),c(Be.organization_id,o||""))).returning()).length>0}}}function Z_(n){return{async create(e,t){var u,f;const i=new Date().toISOString(),s={id:t.id||Le(),tenant_id:e,user_id:t.user_id,organization_id:t.organization_id,created_at:i,updated_at:i};try{await n.insert(le).values(s)}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 _t(409,{message:"User organization already exists"}):p}const{tenant_id:l,...d}=s;return d},async get(e,t){const i=await n.select().from(le).where(g(c(le.tenant_id,e),c(le.id,t))).get();if(!i)return null;const{tenant_id:o,...s}=i;return s},async update(e,t,i){const o={updated_at:new Date().toISOString()};return i.user_id!==void 0&&(o.user_id=i.user_id),i.organization_id!==void 0&&(o.organization_id=i.organization_id),(await n.update(le).set(o).where(g(c(le.tenant_id,e),c(le.id,t))).returning()).length>0},async list(e,t){const{page:i=0,per_page:o=50,include_totals:s=!1,q:l}=t||{},d=c(le.tenant_id,e);let u=d;if(l){const y=Qe(le,l,["user_id","organization_id"]);y&&(u=g(d,y))}const p=(await n.select().from(le).where(u).offset(i*o).limit(o)).map(y=>{const{tenant_id:E,...A}=y;return A});if(!s)return{userOrganizations:p};const[m]=await n.select({count:ge()}).from(le).where(u);return{userOrganizations:p,start:i*o,limit:o,length:Number((m==null?void 0:m.count)??0)}},async listUserOrganizations(e,t,i){const{page:o=0,per_page:s=50,include_totals:l=!1}=i||{},d=await n.select().from(le).where(g(c(le.tenant_id,e),c(le.user_id,t))).offset(o*s).limit(s).all(),f=(await Promise.all(d.map(async m=>{const y=await n.select().from(ee).where(g(c(ee.tenant_id,e),c(ee.id,m.organization_id))).get();if(!y)return null;const{tenant_id:E,branding:A,metadata:J,enabled_connections:Q,token_quota:ie,...Pe}=y;return G({...Pe,branding:z(A,{}),metadata:z(J,{}),enabled_connections:z(Q,[]),token_quota:z(ie,{})})}))).filter(Boolean);if(!l)return{organizations:f};const[p]=await n.select({count:ge()}).from(le).where(g(c(le.tenant_id,e),c(le.user_id,t)));return{organizations:f,start:o*s,limit:s,length:Number((p==null?void 0:p.count)??0)}},async remove(e,t){return(await n.delete(le).where(g(c(le.tenant_id,e),c(le.id,t))).returning()).length>0}}}const Pi=["s"],K_=["pwd_leak"];function qi(n){return/^\d{8}$/.test(n)?`${n.slice(0,4)}-${n.slice(4,6)}-${n.slice(6,8)}`:n}function W_(n){return{async getDaily(e,t){const i=new Date,o=t!=null&&t.from?qi(t.from):new Date(i.getTime()-30*24*60*60*1e3).toISOString().split("T")[0],s=t!=null&&t.to?qi(t.to):i.toISOString().split("T")[0];return(await n.select({date:O`substr(${F.date}, 1, 10)`.as("date"),logins:O`SUM(CASE WHEN ${F.type} IN (${O.join(Pi.map(d=>O`${d}`),O`, `)}) THEN 1 ELSE 0 END)`.as("logins"),signups:O`SUM(CASE WHEN ${F.type} = 'ss' THEN 1 ELSE 0 END)`.as("signups"),leaked_passwords:O`SUM(CASE WHEN ${F.type} IN (${O.join(K_.map(d=>O`${d}`),O`, `)}) THEN 1 ELSE 0 END)`.as("leaked_passwords")}).from(F).where(g(c(F.tenant_id,e),At(F.date,o),yt(F.date,`${s}T23:59:59.999Z`))).groupBy(O`substr(${F.date}, 1, 10)`).orderBy(O`substr(${F.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:O`COUNT(DISTINCT ${F.user_id})`.as("count")}).from(F).where(g(c(F.tenant_id,e),At(F.date,t),O`${F.type} IN (${O.join(Pi.map(o=>O`${o}`),O`, `)})`));return Number(i==null?void 0:i.count)||0}}}const G_={"active-users":["s","seacft"],logins:["s","f","fp"],signups:["ss","fs"],"refresh-tokens":["seacft","fertft"],sessions:["slo"]},J_={"active-users":{alias:"active_users",type:"UInt64",agg:"uniq"},logins:{alias:"logins",type:"UInt64",agg:"count"},signups:{alias:"signups",type:"UInt64",agg:"count"},"refresh-tokens":{alias:"refresh_tokens",type:"UInt64",agg:"count"},sessions:{alias:"sessions",type:"UInt64",agg:"count"}};function Q_(n){switch(n){case"hour":return O`substr(${F.date}, 1, 13)`;case"month":return O`substr(${F.date}, 1, 7)`;case"day":return O`substr(${F.date}, 1, 10)`;case"week":return O`date(substr(${F.date}, 1, 10), '-' || ((cast(strftime('%w', substr(${F.date}, 1, 10)) as integer) + 6) % 7) || ' days')`;default:throw new Error(`Unsupported interval '${n}' for SQL analytics adapter`)}}function Jn(n){return`"${n.replace(/"/g,'""')}"`}function X_(n){switch(n){case"connection":return F.connection;case"client_id":return F.client_id;case"user_type":return F.strategy_type;case"event":return F.type;case"time":throw new Error("time dimension handled separately")}}function Y_(n){return{async query(e,t,i){var J,Q,ie,Pe;const o=Date.now(),s=G_[t],l=J_[t],d=[c(F.tenant_id,e),At(F.date,i.from),Ge(F.date,i.to),De(F.type,s)];(J=i.filters.connection)!=null&&J.length&&d.push(De(F.connection,i.filters.connection)),(Q=i.filters.client_id)!=null&&Q.length&&d.push(De(F.client_id,i.filters.client_id)),(ie=i.filters.user_type)!=null&&ie.length&&d.push(De(F.strategy_type,i.filters.user_type)),(Pe=i.filters.user_id)!=null&&Pe.length&&d.push(De(F.user_id,i.filters.user_id));const u={},f=[],p=[];for(const Ne of i.group_by)if(Ne==="time"){const Ee=Q_(i.interval);u.time=Ee,f.push(Ee),p.push({name:"time",type:i.interval==="hour"?"DateTime":"Date"})}else{const Ee=X_(Ne);u[Ne]=Ee,f.push(Ee),p.push({name:Ne,type:"String"})}u[l.alias]=l.agg==="uniq"?O`COUNT(DISTINCT ${F.user_id})`:O`COUNT(*)`,p.push({name:l.alias,type:l.type});let m=n.select(u).from(F).where(g(...d));f.length>0&&(m=m.groupBy(...f));const y=new Set([...Object.keys(u)]);if(i.order_by){const Ne=i.order_by.startsWith("-"),Ee=Ne?i.order_by.slice(1):i.order_by;if(!y.has(Ee))throw new Error(`Invalid order_by column '${Ee}' for analytics query`);const it=Jn(Ee);m=m.orderBy(O.raw(`${it} ${Ne?"DESC":"ASC"}`))}else i.group_by[0]==="time"?m=m.orderBy(O.raw(`${Jn("time")} ASC`)):m=m.orderBy(O.raw(`${Jn(l.alias)} DESC`));m=m.limit(i.limit).offset(i.offset);const A=(await m.all()).map(Ne=>{const Ee={};for(const it of p){const rt=Ne[it.name];Ee[it.name]=it.type==="UInt64"?Number(rt)||0:rt??""}return Ee});return{meta:p,data:A,rows:A.length,rows_before_limit_at_least:A.length,statistics:{elapsed:(Date.now()-o)/1e3}}}}}function Bi(n){return{...n,payload:z(n.payload,{})}}function eu(n){return{async create(e,t){const i=Le(),o=new Date().toISOString();return await n.insert(P).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:o,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(P).where(De(P.id,e)).all()).map(Bi)},async getUnprocessed(e){const t=new Date().toISOString();return(await n.select().from(P).where(g(Ce(P.processed_at),$e(Ce(P.next_retry_at),yt(P.next_retry_at,t)),$e(Ce(P.claimed_by),yt(P.claim_expires_at,t)))).orderBy(P.created_at,P.id).limit(e).all()).map(Bi)},async claimEvents(e,t,i){if(e.length===0)return[];const o=new Date().toISOString(),s=new Date(Date.now()+i).toISOString();return await n.update(P).set({claimed_by:t,claim_expires_at:s}).where(g(De(P.id,e),Ce(P.processed_at),$e(Ce(P.claimed_by),yt(P.claim_expires_at,o)))),(await n.select({id:P.id}).from(P).where(g(De(P.id,e),c(P.claimed_by,t))).all()).map(d=>d.id)},async markProcessed(e){e.length!==0&&await n.update(P).set({processed_at:new Date().toISOString()}).where(De(P.id,e))},async markRetry(e,t,i){await n.update(P).set({error:t,next_retry_at:i,retry_count:O`${P.retry_count} + 1`,claimed_by:null,claim_expires_at:null}).where(c(P.id,e))},async cleanup(e){return(await n.delete(P).where(g(O`${P.processed_at} IS NOT NULL`,yt(P.processed_at,e))).returning()).length},async deadLetter(e,t){const i=new Date().toISOString();await n.update(P).set({processed_at:i,dead_lettered_at:i,final_error:t}).where(c(P.id,e))},async listFailed(e,t={}){const{page:i=0,per_page:o=50,include_totals:s=!1}=t,d=(await n.select().from(P).where(g(c(P.tenant_id,e),cn(P.dead_lettered_at))).orderBy(se(P.dead_lettered_at),he(P.id)).offset(i*o).limit(o).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(s){const[f]=await n.select({total:ge()}).from(P).where(g(c(P.tenant_id,e),cn(P.dead_lettered_at)));u=Number((f==null?void 0:f.total)??d.length)}return{events:d,start:i*o,limit:o,length:u}},async replay(e,t){return(await n.update(P).set({processed_at:null,dead_lettered_at:null,final_error:null,retry_count:0,next_retry_at:null,error:null}).where(g(c(P.id,e),c(P.tenant_id,t),cn(P.dead_lettered_at))).returning()).length>0}}}const tu=7*24*60*60*1e3;function nu(n){return async e=>{const t=Date.now()-tu;try{let i=[$e(Ge(W.expires_at_ts,t),Ge(W.idle_expires_at_ts,t))];e!=null&&e.tenant_id&&i.push(c(W.tenant_id,e.tenant_id)),await n.delete(W).where(g(...i)),i=[$e(Ge(ae.expires_at_ts,t),Ge(ae.idle_expires_at_ts,t))],e!=null&&e.tenant_id&&i.push(c(ae.tenant_id,e.tenant_id)),e!=null&&e.user_id&&i.push(c(ae.user_id,e.user_id)),await n.delete(ae).where(g(...i)),i=[Ge(Y.expires_at_ts,t)],e!=null&&e.tenant_id&&i.push(c(Y.tenant_id,e.tenant_id)),await n.delete(Y).where(g(...i))}catch(i){console.error("Session cleanup error:",i)}}}function iu(n,e={useTransactions:!0}){const t={actions:tr(),actionExecutions:nr(),actionVersions:ir(),branding:wr(n),clients:Nr(n),clientConnections:br(n),clientGrants:Ar(n),clientRegistrationTokens:n_(n),codes:i_(n),connections:a_(n),customDomains:s_(n),customText:r_(n),emailProviders:l_(n),emailTemplates:d_(n),flows:c_(n),forms:__(n),hookCode:f_(n),hooks:m_(n),invites:v_(n),keys:w_(n),loginSessions:S_(n),logs:b_(n),authenticationMethods:x_(n),organizations:O_(n),passwords:A_(n),promptSettings:T_(n),refreshTokens:C_(n),resourceServers:L_(n),rolePermissions:R_(n),userPermissions:U_(n),roles:F_(n),sessions:P_(n),sessionCleanup:nu(n),tenants:q_(n),themes:$_(n),universalLoginTemplates:j_(n),users:V_(n),userRoles:H_(n),userOrganizations:Z_(n),stats:W_(n),analytics:Y_(n),outbox:eu(n),async transaction(i){if(e.useTransactions===!1)return i(t);await n.run(O`BEGIN`);try{const o=await i(t);return await n.run(O`COMMIT`),o}catch(o){throw await n.run(O`ROLLBACK`),o}}};return t}exports.default=iu;exports.sqlite=hr;